@tea-agent/loop-agent 0.1.0-fe-test.3 → 0.1.0-fe-test.5

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 (485) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +607 -93
  3. package/README.md +11 -5
  4. package/bin/loop-agent.js +7 -3
  5. package/dist/adapters/context-transfer/optional-pi-handoff.js +31 -0
  6. package/dist/adapters/context-transfer/pi-session.js +61 -0
  7. package/dist/application/dag/generate-task-dag.js +90 -21
  8. package/dist/application/dag/run-dag.js +41 -0
  9. package/dist/application/task-lifecycle/advance.js +40 -5
  10. package/dist/application/task-lifecycle/observe.js +171 -17
  11. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  12. package/dist/application/task-lifecycle/recommendations.js +13 -2
  13. package/dist/build-stamp.json +3 -3
  14. package/dist/cli/command-definitions.js +44 -10
  15. package/dist/cli/program.js +82 -6
  16. package/dist/cli/update/notifier.js +2 -2
  17. package/dist/cli/update/runtime-activity.js +1 -29
  18. package/dist/cli.js +2 -1
  19. package/dist/commands/client-recovery.js +11 -36
  20. package/dist/commands/dag-artifact.js +284 -0
  21. package/dist/commands/dag-context.js +184 -0
  22. package/dist/commands/dag-follow-up.js +138 -0
  23. package/dist/commands/dag-rerun-task.js +2 -0
  24. package/dist/commands/dag-rerun.js +261 -2
  25. package/dist/commands/init-model-catalog.js +486 -0
  26. package/dist/commands/init-upgrade.js +265 -97
  27. package/dist/commands/init.js +455 -28
  28. package/dist/commands/inspect-next.js +8 -0
  29. package/dist/commands/task-advance.js +73 -1
  30. package/dist/commands/task-source-prepare.js +5 -0
  31. package/dist/commands/task-status.js +1 -0
  32. package/dist/executors/dag-pi-executor.js +4323 -231
  33. package/dist/executors/pi-event-serializer.js +42 -1
  34. package/dist/executors/pi-executor.js +70 -6
  35. package/dist/executors/pi-extension-resolver.js +245 -0
  36. package/dist/executors/pi-playwright-cli-tool.js +74 -28
  37. package/dist/executors/pi-read-budget-policy.js +239 -0
  38. package/dist/executors/pi-sdk-executor.js +263 -59
  39. package/dist/executors/pi-writer-tool-policy.js +57 -1
  40. package/dist/executors/shell-executor.js +1456 -240
  41. package/dist/executors/shell-write-guard.js +14 -0
  42. package/dist/executors/workspace-write-snapshot.js +68 -0
  43. package/dist/governance/checks.js +1 -0
  44. package/dist/{worker → infrastructure}/console/app-data.js +4 -0
  45. package/dist/infrastructure/console/artifact-revision-store.js +430 -0
  46. package/dist/infrastructure/console/context-export-store.js +160 -0
  47. package/dist/infrastructure/console/dir-lock.js +132 -0
  48. package/dist/infrastructure/console/operation-store.js +417 -0
  49. package/dist/infrastructure/harness/artifact-store.js +10 -1
  50. package/dist/infrastructure/harness/atomic-write.js +35 -2
  51. package/dist/shared/context-transfer/artifact-revision.js +172 -0
  52. package/dist/shared/context-transfer.js +418 -0
  53. package/dist/shared/dag-failure-category.js +150 -0
  54. package/dist/shared/dag-prompt-override.js +27 -0
  55. package/dist/shared/openspec-spec.js +70 -4
  56. package/dist/shared/operator/capabilities.js +65 -4
  57. package/dist/shared/operator/safe-run-summary.js +1 -0
  58. package/dist/shared/path-safety.js +93 -0
  59. package/dist/shared/pi-context-pressure/checkpoint.js +116 -0
  60. package/dist/shared/pi-context-pressure/compaction-policy.js +151 -0
  61. package/dist/shared/pi-context-pressure/env.js +58 -0
  62. package/dist/shared/pi-context-pressure/extension.js +100 -0
  63. package/dist/shared/pi-context-pressure/index.js +7 -0
  64. package/dist/shared/pi-context-pressure/overflow.js +252 -0
  65. package/dist/shared/pi-context-pressure/sift-bridge.js +386 -0
  66. package/dist/shared/pi-context-pressure/telemetry.js +51 -0
  67. package/dist/shared/playwright-cli-command-policy.js +15 -0
  68. package/dist/shared/preview.js +28 -4
  69. package/dist/shared/update/console-notifier.js +100 -0
  70. package/dist/{cli → shared}/update/npm-client.js +70 -15
  71. package/dist/{cli → shared}/update/state.js +41 -13
  72. package/dist/task/config-types.js +125 -6
  73. package/dist/task/contract/adopt.js +4 -0
  74. package/dist/task/contract/apply.js +11 -1
  75. package/dist/task/contract/constants.js +3 -0
  76. package/dist/task/contract/diff.js +26 -0
  77. package/dist/task/contract/hash.js +3 -0
  78. package/dist/task/contract/import-revision.js +4 -0
  79. package/dist/task/contract/observe.js +25 -4
  80. package/dist/task/contract/paths.js +2 -1
  81. package/dist/task/contract/project.js +23 -1
  82. package/dist/task/contract/schema.js +9 -1
  83. package/dist/task/contract/transaction.js +12 -0
  84. package/dist/task/frontend-project-capability.js +203 -20
  85. package/dist/task/runtime.js +5 -2
  86. package/dist/task/source-prepare/build-draft.js +18 -3
  87. package/dist/task/source-prepare/completeness.js +188 -0
  88. package/dist/task/source-prepare/fragment-inventory.js +513 -0
  89. package/dist/task/source-prepare/index.js +3 -0
  90. package/dist/task/source-prepare/ledger-reconciliation.js +127 -0
  91. package/dist/task/source-prepare/ledger-review.js +214 -0
  92. package/dist/task/source-prepare/ledger.js +545 -0
  93. package/dist/task/source-prepare/parse-intent.js +24 -4
  94. package/dist/task/source-prepare/prepare.js +368 -2
  95. package/dist/task/source-prepare/semantic-intake.js +25 -5
  96. package/dist/task/source-prepare/source-fidelity-pi.js +384 -0
  97. package/dist/task/source-prepare/types.js +22 -0
  98. package/dist/task/source-references.js +22 -1
  99. package/dist/task/task-demand-routing.js +3 -0
  100. package/dist/worker/cli.js +18 -2
  101. package/dist/worker/console/chat/assistant-content.js +7 -0
  102. package/dist/worker/console/chat/chat-event-store.js +159 -18
  103. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  104. package/dist/worker/console/chat/context-panel.js +7 -0
  105. package/dist/worker/console/chat/deferred-turn.js +103 -0
  106. package/dist/worker/console/chat/goal-round-driver.js +72 -0
  107. package/dist/worker/console/chat/goals.js +300 -0
  108. package/dist/worker/console/chat/model-resolver.js +7 -4
  109. package/dist/worker/console/chat/operation-card.js +8 -1
  110. package/dist/worker/console/chat/pi-console-config.js +81 -10
  111. package/dist/worker/console/chat/pi-runtime.js +868 -30
  112. package/dist/worker/console/chat/provider-error.js +99 -0
  113. package/dist/worker/console/chat/repo-browser.js +101 -12
  114. package/dist/worker/console/chat/resource-preferences-store.js +1 -1
  115. package/dist/worker/console/chat/routes.js +1451 -145
  116. package/dist/worker/console/chat/sdd-data-alignment.js +222 -0
  117. package/dist/worker/console/chat/semantic-activity.js +25 -24
  118. package/dist/worker/console/chat/session-catalog.js +50 -0
  119. package/dist/worker/console/chat/session-stats.js +275 -0
  120. package/dist/worker/console/chat/session-store.js +348 -76
  121. package/dist/worker/console/chat/shortcuts.js +26 -3
  122. package/dist/worker/console/chat/sift-bridge.js +1 -0
  123. package/dist/worker/console/chat/todos.js +115 -0
  124. package/dist/worker/console/chat/tool-preview.js +42 -0
  125. package/dist/worker/console/chat/turn-process.js +185 -112
  126. package/dist/worker/console/chat/user-questions.js +266 -0
  127. package/dist/worker/console/chat/workspace-landing.js +79 -0
  128. package/dist/worker/console/console-handoff.js +82 -0
  129. package/dist/worker/console/console-update-and-init.js +115 -0
  130. package/dist/worker/console/console-update-runtime.js +84 -0
  131. package/dist/worker/console/context-transfer-diagnostics.js +198 -0
  132. package/dist/worker/console/dag-confirmation.js +1 -1
  133. package/dist/worker/console/dag-execution-receipt.js +54 -3
  134. package/dist/worker/console/doctor.js +1 -1
  135. package/dist/worker/console/draft-store.js +50 -1
  136. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  137. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  138. package/dist/worker/console/human-gate-token.js +1 -1
  139. package/dist/worker/console/index.js +6 -3
  140. package/dist/worker/console/inspect-split.js +18 -0
  141. package/dist/worker/console/interview/assessment.js +1 -1
  142. package/dist/worker/console/interview/session.js +1 -1
  143. package/dist/worker/console/native-directory-picker.js +13 -0
  144. package/dist/worker/console/operation-run-facts.js +19 -3
  145. package/dist/worker/console/operation-runner.js +45 -4
  146. package/dist/worker/console/operation-sse.js +1 -1
  147. package/dist/worker/console/operation-wait.js +1 -1
  148. package/dist/worker/console/operator-actions.js +534 -15
  149. package/dist/worker/console/operator-selection.js +6 -2
  150. package/dist/worker/console/operator-surface-health.js +2 -1
  151. package/dist/worker/console/operator-user-error.js +171 -2
  152. package/dist/worker/console/pi-plugins.catalog.json +73658 -0
  153. package/dist/worker/console/pi-plugins.js +238 -0
  154. package/dist/worker/console/pi-readiness.js +7 -6
  155. package/dist/worker/console/prd-intake-bridge.js +13 -0
  156. package/dist/worker/console/recovery-cta.js +4 -4
  157. package/dist/worker/console/recovery-error-copy.js +4 -4
  158. package/dist/worker/console/routes.js +1231 -10
  159. package/dist/worker/console/security.js +102 -13
  160. package/dist/worker/console/server.js +762 -159
  161. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BmOEx0gA.js → abnfDiagram-N423BO3Z-BZogYNl1.js} +1 -1
  162. package/dist/worker/console/static/assets/{arc-BGiVVe8b.js → arc-DcJTLe2v.js} +1 -1
  163. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-nDdu4rgJ.js → architectureDiagram-T3A2C74G-B39EQQ9n.js} +1 -1
  164. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bb5u0BWf.js → blockDiagram-VBNYF7ZC-CitCGV56.js} +1 -1
  165. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BlhC0j94.js → c4Diagram-5PPSVZJV-rvWuOHLG.js} +1 -1
  166. package/dist/worker/console/static/assets/channel-CXqdP5pW.js +1 -0
  167. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Ai8_qQXI.js → chunk-2GRJ4B5K-DGXplIJs.js} +1 -1
  168. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-B9gyCjqX.js → chunk-2Q5K7J3B-ur9OqjPn.js} +1 -1
  169. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bzbj3zGH.js → chunk-5RXB4S5H-D1KqU_Vi.js} +1 -1
  170. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BT415PvT.js → chunk-5VM5RSS4-BlVZrbtM.js} +1 -1
  171. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D_A5_5QL.js → chunk-6Q2QTUOP-BAzz3nQy.js} +1 -1
  172. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-srJkaP3f.js → chunk-GF5L2VYU-CP_nYuCV.js} +1 -1
  173. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-UYGvEP4l.js → chunk-JWPE2WC7-CWvKQ80X.js} +1 -1
  174. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-B8luBrrz.js → chunk-KBJHAD2P-CyUki8wp.js} +1 -1
  175. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DN7wXZSq.js → chunk-RYQCIY6F-5NYzNKfY.js} +1 -1
  176. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DXKyMuKS.js → chunk-XXDRQBXY-DHdUgjS-.js} +1 -1
  177. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9C3agF7.js +1 -0
  178. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9C3agF7.js +1 -0
  179. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-dqvoynXj.js → cose-bilkent-JH36ORCC-ANQ5g_t6.js} +1 -1
  180. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2--PcyL34A.js → cynefin-VYW2F7L2-CruT_4-0.js} +1 -1
  181. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-DvWs_hTY.js → cynefinDiagram-MW4NZA55-rbFo77ID.js} +1 -1
  182. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-DxeIxbyO.js → dagre-VZM6K2ZE-asstxBQs.js} +1 -1
  183. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DPCG61Of.js → diagram-7IWD3JNH-DzTyBZwI.js} +1 -1
  184. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmuU50-U.js → diagram-B4RE2ZJO-gw8ccH3B.js} +1 -1
  185. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B61XLD_v.js → diagram-LBJQPF4R-B8RpZzOf.js} +1 -1
  186. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BB7HTRRY.js → diagram-Q27KOJAE-B1zJkCS9.js} +1 -1
  187. package/dist/worker/console/static/assets/{diagram-UB23O5K3-DvkboAIp.js → diagram-UB23O5K3-B6JLWZmO.js} +1 -1
  188. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-BdJ_y1fL.js → ebnfDiagram-BXEA7PRR-q2iZP-Ps.js} +1 -1
  189. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-9bUBZTRi.js → erDiagram-JOGREHBK-B3dbbktQ.js} +1 -1
  190. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-Dw4L4RBa.js → flowDiagram-UKHOOZJN-C-zc6-kB.js} +1 -1
  191. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Jr82N_QP.js → ganttDiagram-PKOTCBZU-BSolnot9.js} +1 -1
  192. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DAz9wFLr.js → gitGraphDiagram-DS77QQ5N-Bo8jGxTk.js} +1 -1
  193. package/dist/worker/console/static/assets/index-CAZ2fC_X.css +1 -0
  194. package/dist/worker/console/static/assets/index-DhfjOafu.js +449 -0
  195. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CBB5Np7y.js → infoDiagram-6WML65LV-DQaZqJOH.js} +1 -1
  196. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-D8IOp94y.js → ishikawaDiagram-WSZJBQD7-DsdX1WnE.js} +1 -1
  197. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Dgd3AHGG.js → journeyDiagram-NVQOT4AX-CP5EYDZL.js} +1 -1
  198. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BmYOxLE9.js → kanban-definition-27J2QSJJ-DAm14Dr8.js} +1 -1
  199. package/dist/worker/console/static/assets/{linear-DfYTEF6J.js → linear-gZECoLc5.js} +1 -1
  200. package/dist/worker/console/static/assets/{mermaid.core-BjuFPRqa.js → mermaid.core-BRJNIM6p.js} +5 -5
  201. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CLyUViGd.js → mindmap-definition-FAOFIHXS-Cja3kLkR.js} +1 -1
  202. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BvX2Di4-.js → pegDiagram-VL7TDLO6-22ZGFisL.js} +1 -1
  203. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BFj0_OLv.js → pieDiagram-7S7Q4E2Y-BXin0Y1o.js} +1 -1
  204. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BIUrD_hx.js → quadrantDiagram-CIZ2JOQS-Cw6T69Yt.js} +1 -1
  205. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CHBB48fj.js → railroadDiagram-AXF67PYL-C1-gTieN.js} +1 -1
  206. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-sJrYw2Sf.js → requirementDiagram-LRYGKXZP--H5N2iI1.js} +1 -1
  207. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BzHH6fPR.js → sankeyDiagram-W5VNT64P-CgWAPeRz.js} +1 -1
  208. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-7QCnelCt.js → sequenceDiagram-SI44F4Z6-CrKqzGvt.js} +1 -1
  209. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-sDYSxn72.js → sizeCapture-X5ZJPWSS-BB3wG06K.js} +1 -1
  210. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-XpiUdwzm.js → stateDiagram-OKZ733FA-DjsGgdgY.js} +1 -1
  211. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Tp7V0U4q.js +1 -0
  212. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DvqgNPzD.js → swimlanes-SLNWSIFB-DYKEbvAR.js} +2 -2
  213. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DUZWZWi8.js +8 -0
  214. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-2TyOYNx0.js → timeline-definition-Z64GVDOM-eQOb5k9Y.js} +1 -1
  215. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-B-nM6wM2.js → vennDiagram-T6HMQDX7-B2-l9FIu.js} +1 -1
  216. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-B86wPdbr.js → wardleyDiagram-T6FBY63Y-BX2Cda3l.js} +1 -1
  217. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dr1C4AQz.js → xychartDiagram-ELKLHX3M-D9S892ph.js} +1 -1
  218. package/dist/worker/console/static/index.html +7 -2
  219. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  220. package/dist/worker/console/static-src/app/console-types.js +68 -4
  221. package/dist/worker/console/static-src/app/useConsoleShell.js +30 -12
  222. package/dist/worker/console/static-src/app/useOperatorActions.js +43 -7
  223. package/dist/worker/console/static-src/app/useRecoveryActions.js +2 -2
  224. package/dist/worker/console/static-src/app/useRecoveryConsole.js +45 -10
  225. package/dist/worker/console/static-src/app/useRunProgress.js +54 -0
  226. package/dist/worker/console/static-src/app/useTaskWizard.js +74 -2
  227. package/dist/worker/console/static-src/night/useNightBoard.js +8 -5
  228. package/dist/worker/console/static-src/operator-chat/cards/failure-category-advice.js +25 -0
  229. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +264 -13
  230. package/dist/worker/console/static-src/operator-chat/compaction-message.js +113 -0
  231. package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +22 -0
  232. package/dist/worker/console/static-src/operator-chat/details-dag-actions.js +122 -0
  233. package/dist/worker/console/static-src/operator-chat/input-history.js +78 -0
  234. package/dist/worker/console/static-src/operator-chat/mutation-gate.js +1 -1
  235. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +338 -0
  236. package/dist/worker/console/static-src/operator-chat/refs.js +3 -0
  237. package/dist/worker/console/static-src/operator-chat/runtime-selection-labels.js +27 -0
  238. package/dist/worker/console/static-src/operator-chat/runtime-snapshot-store.js +10 -0
  239. package/dist/worker/console/static-src/operator-chat/spatial-overlay.js +1 -2
  240. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +33 -1
  241. package/dist/worker/console/static-src/operator-chat/turn-submission.js +55 -0
  242. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +448 -109
  243. package/dist/worker/console/static-src/operator-chat/useChatStream.js +344 -27
  244. package/dist/worker/console/static-src/operator-chat/useChatThread.js +323 -11
  245. package/dist/worker/console/static-src/operator-chat/useComposer.js +45 -4
  246. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +97 -13
  247. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +57 -9
  248. package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +8 -2
  249. package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
  250. package/dist/worker/console/static-src/operator-chat/workspace-layout-mode.js +3 -3
  251. package/dist/worker/console/static-src/operator-chat/workspace-reorder.js +18 -0
  252. package/dist/worker/console/static-src/pages/tasks/run-id-resolution.js +79 -0
  253. package/dist/worker/console/static-src/pages/tasks/run-ownership-verify.js +23 -0
  254. package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +216 -0
  255. package/dist/worker/console/static-src/shell/console-update-reload.js +52 -0
  256. package/dist/worker/console/static-src/shell/useWorkspaces.js +415 -0
  257. package/dist/worker/console/static-src/shell/workspace-route.js +356 -0
  258. package/dist/worker/console/workspace-context.js +399 -0
  259. package/dist/worker/console/workspace-registry.js +487 -0
  260. package/dist/worker/continuation/worker-continuation.js +278 -0
  261. package/dist/worker/loop-agent/loop-agent-client.js +7 -3
  262. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  263. package/dist/worker/materialize/harness-task-lineage.js +5 -2
  264. package/dist/worker/observability/init-runtime-activity.js +26 -0
  265. package/dist/worker/observability/read-model.js +26 -0
  266. package/dist/worker/observe/health.js +1 -1
  267. package/dist/worker/observe/node-input.js +160 -3
  268. package/dist/worker/observe/node-process.js +377 -0
  269. package/dist/worker/observe/node-transparency.js +572 -0
  270. package/dist/worker/observe/routes.js +278 -3
  271. package/dist/worker/observe/server.js +4 -0
  272. package/dist/worker/observe/shell-handler-keys.js +34 -0
  273. package/dist/worker/observe/static/api.js +154 -4
  274. package/dist/worker/observe/static/app.js +18 -70
  275. package/dist/worker/observe/static/constants.js +26 -19
  276. package/dist/worker/observe/static/dag-context-reason-labels.d.ts +9 -0
  277. package/dist/worker/observe/static/dag-context-reason-labels.js +139 -0
  278. package/dist/worker/observe/static/dag-helpers.js +4 -2
  279. package/dist/worker/observe/static/dag-history-labels.js +5 -0
  280. package/dist/worker/observe/static/dag-inspector-humanize.d.ts +16 -0
  281. package/dist/worker/observe/static/dag-inspector-humanize.js +339 -0
  282. package/dist/worker/observe/static/dag-node-purpose.d.ts +6 -0
  283. package/dist/worker/observe/static/dag-node-purpose.js +208 -0
  284. package/dist/worker/observe/static/format.js +60 -0
  285. package/dist/worker/observe/static/index.html +10 -5
  286. package/dist/worker/observe/static/inspect-bootstrap.d.ts +8 -0
  287. package/dist/worker/observe/static/inspect-bootstrap.js +57 -0
  288. package/dist/worker/observe/static/inspect-workspace.js +374 -0
  289. package/dist/worker/observe/static/kpi.js +2 -2
  290. package/dist/worker/observe/static/markdown-render.js +20 -1
  291. package/dist/worker/observe/static/operator-chrome.css +168 -24
  292. package/dist/worker/observe/static/operator-chrome.d.ts +30 -5
  293. package/dist/worker/observe/static/operator-chrome.js +354 -101
  294. package/dist/worker/observe/static/prompt-restart-candidates.d.ts +18 -0
  295. package/dist/worker/observe/static/prompt-restart-candidates.js +38 -0
  296. package/dist/worker/observe/static/relations.js +7 -7
  297. package/dist/worker/observe/static/router.d.ts +57 -0
  298. package/dist/worker/observe/static/router.js +67 -1
  299. package/dist/worker/observe/static/run-processing.js +4 -2
  300. package/dist/worker/observe/static/shell-chrome.js +2 -2
  301. package/dist/worker/observe/static/state.d.ts +50 -0
  302. package/dist/worker/observe/static/state.js +191 -1
  303. package/dist/worker/observe/static/styles.css +1720 -86
  304. package/dist/worker/observe/static/views/dag-graph.js +5 -3
  305. package/dist/worker/observe/static/views/dag-inspector.js +2601 -188
  306. package/dist/worker/observe/static/views/dag.d.ts +13 -0
  307. package/dist/worker/observe/static/views/dag.js +39 -18
  308. package/dist/worker/observe/static/views/dags.js +10 -6
  309. package/dist/worker/observe/static/views/dashboard.js +18 -8
  310. package/dist/worker/observe/static/views/failures.js +5 -2
  311. package/dist/worker/observe/static/views/night.js +2 -2
  312. package/dist/worker/observe/static/views/pool.js +8 -2
  313. package/dist/worker/observe/static/views/run.js +15 -4
  314. package/dist/worker/observe/static/views/session-timeline.js +386 -25
  315. package/dist/worker/observe/static/views/task.js +63 -3
  316. package/dist/worker/outcomes/adapters.js +19 -0
  317. package/dist/worker/outcomes/types.js +1 -0
  318. package/dist/worker/pool/attempt-lease.js +97 -66
  319. package/dist/worker/pool/begin-attempt-with-lease.js +1 -0
  320. package/dist/worker/pool/reconcile.js +46 -1
  321. package/dist/worker/pool/run-store.js +2 -0
  322. package/dist/worker/pool/state-projection.js +2 -0
  323. package/dist/worker/task-spec/workflow-routing.js +8 -3
  324. package/dist/workflows/dag/artifact-bindings.js +149 -0
  325. package/dist/workflows/dag/artifact-revision-schema-registry.js +31 -0
  326. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +470 -31
  327. package/dist/workflows/dag/backend-test-markdown-workflow.js +189 -2
  328. package/dist/workflows/dag/backend-test-plan-protocol.js +210 -0
  329. package/dist/workflows/dag/backend-test-pytest-collection.js +168 -16
  330. package/dist/workflows/dag/backend-test-result-contract.js +5 -1
  331. package/dist/workflows/dag/backend-test-scenario-param.js +506 -73
  332. package/dist/workflows/dag/backend-test-scenario-partitions.js +135 -2
  333. package/dist/workflows/dag/backend-test-writer-completeness.js +131 -28
  334. package/dist/workflows/dag/budget-enforcement.js +10 -0
  335. package/dist/workflows/dag/context-receipt.js +305 -0
  336. package/dist/workflows/dag/context-transfer/context-bundle.js +423 -0
  337. package/dist/workflows/dag/context-transfer/operator-actions.js +61 -0
  338. package/dist/workflows/dag/context-transfer/renderers.js +93 -0
  339. package/dist/workflows/dag/contract-output-registry.js +15 -0
  340. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  341. package/dist/workflows/dag/convergence/controller.js +141 -0
  342. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  343. package/dist/workflows/dag/dynamic-runtime/loop-until.js +1 -1
  344. package/dist/workflows/dag/dynamic-runtime/map.js +17 -3
  345. package/dist/workflows/dag/failure-category.js +7 -116
  346. package/dist/workflows/dag/frontend-closeout.js +221 -0
  347. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  348. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  349. package/dist/workflows/dag/frontend-implementation-contract.js +1377 -141
  350. package/dist/workflows/dag/frontend-plan-render.js +26 -1
  351. package/dist/workflows/dag/frontend-prewrite-gate.js +376 -318
  352. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  353. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  354. package/dist/workflows/dag/frontend-recovery-controller.js +226 -0
  355. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  356. package/dist/workflows/dag/frontend-recovery-plan.js +21 -10
  357. package/dist/workflows/dag/frontend-recovery-run.js +166 -34
  358. package/dist/workflows/dag/frontend-repair.js +7 -424
  359. package/dist/workflows/dag/frontend-review-context.js +348 -20
  360. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  361. package/dist/workflows/dag/frontend-risk.js +15 -2
  362. package/dist/workflows/dag/frontend-shadow-dual-write.js +941 -0
  363. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  364. package/dist/workflows/dag/frontend-shape-facts.js +419 -0
  365. package/dist/workflows/dag/frontend-shape.js +435 -0
  366. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  367. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  368. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  369. package/dist/workflows/dag/frontend-test-case-checklist.js +32 -4
  370. package/dist/workflows/dag/frontend-test-case-generation-assessment.js +69 -0
  371. package/dist/workflows/dag/frontend-test-case-manifest.js +17 -5
  372. package/dist/workflows/dag/frontend-test-case-quality.js +11 -16
  373. package/dist/workflows/dag/frontend-test-environment-probe.js +230 -0
  374. package/dist/workflows/dag/frontend-test-html-report.js +3 -1
  375. package/dist/workflows/dag/frontend-test-l5-report.js +3 -1
  376. package/dist/workflows/dag/frontend-test-layout.js +159 -0
  377. package/dist/workflows/dag/frontend-test-markdown.js +61 -0
  378. package/dist/workflows/dag/frontend-test-result-contract.js +202 -42
  379. package/dist/workflows/dag/frontend-test-standard-scenarios.js +70 -0
  380. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  381. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  382. package/dist/workflows/dag/frontend-verification-trace.js +281 -29
  383. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  384. package/dist/workflows/dag/frontend-writer-admission.js +319 -0
  385. package/dist/workflows/dag/frontend-writer-rollback.js +32 -0
  386. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  387. package/dist/workflows/dag/init-hybrid.js +1771 -717
  388. package/dist/workflows/dag/interrupt-request.js +10 -3
  389. package/dist/workflows/dag/lifecycle.js +3 -3
  390. package/dist/workflows/dag/node-execution.js +1141 -32
  391. package/dist/workflows/dag/path-safety.js +1 -0
  392. package/dist/workflows/dag/prompt.js +158 -7
  393. package/dist/workflows/dag/recovery-lease.js +170 -0
  394. package/dist/workflows/dag/report.js +37 -1
  395. package/dist/workflows/dag/rerun-feedback.js +526 -0
  396. package/dist/workflows/dag/rerun-plan.js +790 -28
  397. package/dist/workflows/dag/rerun-run.js +700 -21
  398. package/dist/workflows/dag/rerun-task.js +311 -14
  399. package/dist/workflows/dag/retry-policy.js +336 -101
  400. package/dist/workflows/dag/runner.js +596 -121
  401. package/dist/workflows/dag/scheduler.js +133 -20
  402. package/dist/workflows/dag/skill-snapshot.js +17 -0
  403. package/dist/workflows/dag/structured-output-repair.js +712 -0
  404. package/dist/workflows/dag/types.js +600 -31
  405. package/dist/workflows/dag/validate.js +92 -32
  406. package/docs/README.md +2 -0
  407. package/docs/architecture/evolution.md +45 -0
  408. package/docs/architecture/runtime-boundaries.md +8 -7
  409. package/docs/architecture/worker-and-feature.md +1 -1
  410. package/docs/examples/README.md +5 -0
  411. package/docs/init-surface.manifest.json +36 -12
  412. package/docs/operations/README.md +1 -1
  413. package/docs/operations/local-development-environment.md +22 -5
  414. package/docs/skills/vetted-skill-registry.md +16 -0
  415. package/docs/templates/README.md +4 -2
  416. package/docs/templates/agent-dag-report.schema.json +8 -2
  417. package/docs/templates/agent-dag.schema.json +95 -1
  418. package/docs/templates/backend-test-dag.json +278 -244
  419. package/docs/templates/frontend-implementation-contract.schema.json +684 -24
  420. package/docs/templates/frontend-implementation-dag.json +89 -0
  421. package/docs/templates/frontend-test-case-checklist.md +2 -2
  422. package/docs/templates/frontend-test-dag.json +10 -12
  423. package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +1 -1
  424. package/docs/templates/init-managed-agents.md +13 -3
  425. package/docs/templates/product-line/task.yaml +1 -1
  426. package/docs/templates/spec-registry.schema.json +45 -0
  427. package/harness.json +2 -2
  428. package/package.json +19 -5
  429. package/scripts/next-info.mjs +356 -0
  430. package/scripts/next-publish-gate.mjs +238 -0
  431. package/scripts/release-source-binding.mjs +251 -0
  432. package/skills/analyze-product-requirements/SKILL.md +8 -5
  433. package/skills/analyze-product-requirements/references/acceptance-criteria.md +1 -1
  434. package/skills/analyze-product-requirements/references/clarification-and-knowledge.md +10 -6
  435. package/skills/analyze-product-requirements/references/example.md +50 -0
  436. package/skills/analyze-product-requirements/references/forward-test-cases.md +11 -7
  437. package/skills/analyze-product-requirements/references/kb-integration.md +5 -5
  438. package/skills/analyze-product-requirements/references/product-analysis-schema.md +8 -4
  439. package/skills/analyze-product-requirements/references/product-requirement-schema.md +2 -2
  440. package/skills/analyze-product-requirements/references/requirement-clarification-schema.md +1 -1
  441. package/skills/analyze-product-requirements/scripts/test-validators.mjs +11 -1
  442. package/skills/analyze-product-requirements/scripts/validate-product-analysis.mjs +20 -1
  443. package/skills/analyze-product-requirements/scripts/validate-requirement-clarification.mjs +9 -0
  444. package/skills/codebase-scout/SKILL.md +1 -1
  445. package/skills/fe-test-ui-scout/SKILL.md +65 -0
  446. package/skills/fe-test-ui-scout/references/ledger-schema.md +62 -0
  447. package/skills/fe-test-ui-scout/references/recon-protocol.md +54 -0
  448. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  449. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  450. package/skills/frontend-contract/SKILL.md +23 -0
  451. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  452. package/skills/frontend-design-review/SKILL.md +22 -41
  453. package/skills/frontend-plan/SKILL.md +26 -0
  454. package/skills/frontend-plan/references/decision-contract.md +37 -0
  455. package/skills/frontend-plan/references/design-decisions.md +17 -0
  456. package/skills/frontend-review/SKILL.md +20 -15
  457. package/skills/frontend-review/references/review-findings.md +6 -7
  458. package/skills/frontend-scout/SKILL.md +25 -0
  459. package/skills/frontend-scout/references/design-evidence.md +16 -0
  460. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  461. package/skills/frontend-verification/SKILL.md +1 -1
  462. package/skills/improve-codebase-architecture/SKILL.md +81 -0
  463. package/skills/improve-codebase-architecture/deepening.md +37 -0
  464. package/skills/improve-codebase-architecture/html-report.md +123 -0
  465. package/skills/improve-codebase-architecture/interface-design.md +44 -0
  466. package/skills/improve-codebase-architecture/language.md +53 -0
  467. package/skills/loop-agent/references/command-reference.md +32 -4
  468. package/skills/loop-agent/references/hybrid-dag.md +9 -2
  469. package/skills/playwright-cli/SKILL.md +23 -1
  470. package/skills/playwright-cli-case-generator/SKILL.md +50 -13
  471. package/dist/worker/console/operation-store.js +0 -169
  472. package/dist/worker/console/static/assets/channel-Tl-FkUqr.js +0 -1
  473. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BaehtRk4.js +0 -1
  474. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BaehtRk4.js +0 -1
  475. package/dist/worker/console/static/assets/index-B7Y-0g3J.css +0 -1
  476. package/dist/worker/console/static/assets/index-DkCrqaYg.js +0 -325
  477. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-eEhq2A8Y.js +0 -1
  478. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-la8AC7fo.js +0 -8
  479. package/dist/worker/console/static-src/operator-chat/activity-rail-presentation.js +0 -73
  480. package/dist/worker/console/static-src/operator-chat/useActivityRailTransition.js +0 -59
  481. package/skills/frontend-implementation/SKILL.md +0 -52
  482. package/skills/frontend-implementation/references/code-standards.md +0 -33
  483. package/skills/frontend-implementation/references/design-spec.md +0 -56
  484. package/skills/frontend-implementation/references/node-contracts.md +0 -31
  485. /package/dist/{worker → infrastructure}/console/repo-fingerprint.js +0 -0
@@ -26,18 +26,24 @@
26
26
  * `createDefaultPiSdkBindings()`.
27
27
  */
28
28
  import { createHash, randomBytes } from "node:crypto";
29
- import { access } from "node:fs/promises";
29
+ import { access, mkdir, rm, stat, writeFile } from "node:fs/promises";
30
30
  import path from "node:path";
31
31
  import { extractAssistantContentBlocks, extractAssistantText, isAssistantSdkMessage, } from "./assistant-content.js";
32
+ import { parseProviderError, } from "./provider-error.js";
32
33
  import { projectCompactSnapshot, } from "./chat-event-store.js";
33
34
  import { extractUsageSample } from "./usage.js";
34
35
  import { OPERATOR_CHAT_ALLOWED_TOOLS, authorizeOperatorChatTool, assertNoWriteToolInList, } from "./tools.js";
35
36
  import { createOperatorChatResourceLoader, } from "./resource-loader.js";
36
37
  import { applySkillAutoInvocationPreferences, isAutoInvocationEnabled, loadResourcePreferences, skillResourceId, } from "./resource-preferences-store.js";
37
38
  import { buildModelCallableToolSchemas } from "./tool-adapter.js";
39
+ import { applyProcessCompactionOverride, createCompactionController, createContextPressureExtension, createSiftBridgeState, housekeepSiftStash, isConsoleSiftEnabled, parseCompactionPolicy, parseSiftBridgeConfig, projectPromptPressure, deriveEffectiveWindow, projectSafeTelemetry, emptyContextPressureCounters, } from "../../../shared/pi-context-pressure/index.js";
40
+ import { incrementCounter as incrementPressureCounter } from "../../../shared/pi-context-pressure/telemetry.js";
38
41
  import { resolveDefaultChatModel, resolveLowChatModel, } from "./model-resolver.js";
39
42
  import { filterActiveInterviewTools } from "../interview/tools.js";
40
43
  import { RUNTIME_CONTEXT_TEXT_MAX, redactRuntimeText, } from "./runtime-context.js";
44
+ import { buildTodoContinuationContext, } from "./todos.js";
45
+ import { buildGoalContinuationContext, } from "./goals.js";
46
+ import { injectWizardLocalHeaders, } from "./sdd-data-alignment.js";
41
47
  /**
42
48
  * Base system prompt fragment every General Operator Chat session receives.
43
49
  *
@@ -62,10 +68,11 @@ export const OPERATOR_CHAT_SYSTEM_PROMPT_BASE = [
62
68
  "You are General Operator Chat.",
63
69
  "Use operator tools first (dagReport, dagRerunPlan, dagRerun). Pi read/write/edit/bash/grep/find/ls are available; obey repository AGENTS.md. apply_patch, full-tools, shell and coding-chat are denied. Prefer safe-read/safe-grep for probes.",
64
70
  "No harness and asked to init: `loop-agent init instructions --repo-root .`, then `loop-agent init --repo-root . --profile full --merge`; verify with doctor, inspect and docs audit. Updates: `loop-agent init upgrade --repo-root . --json` until stable; `loop-agent init check-update` is read-only.",
65
- "Long DAGs: prepareDagExecution → runDag → operationId. Never foreground-Bash task advance, tail/head pipes or nohup/Start-Process/start; do not end on accepted/queued/running or an operationId — NOT completion. Supervise operationGet/status/dagReport/dagDoctor/operationWait with 60s → 90s → 120s → 180s backoff; reset to 60s on state change; 30-60s re-checks when stall suspected. Every operationWait continuation MUST use afterSeq=previous nextSeq (prefer recommendedNextCall); never reuse an older cursor. Heartbeats are not meaningful progress.",
66
- "On failure consume terminal runSummary first. If progress exists, wait; else dagReport then dagRerunPlan(fromNode=primaryFailure.nodeId); eligible → dagRerun (node rerun only: reruns the failed subgraph, keeps prior successes). If plan ineligible (unsafe-shell subgraph, binding/workspace drift): Worker Failed → workerTaskRetry; standalone → standaloneTaskRerun after contract adopt (regenerates the whole task, not node continue). Do not call dagResume. A run-failed task without an open gate is terminal: do not re-advance a run-failed task. Before run start, two identical lifecycleState/blocker/revision/DAG-hash observations mean no progress: stop and report after one bounded probe; never loop identical bash/read/grep. Auto-approve only bounded writeSet inside allowedPaths, outside forbiddenPaths, with structured verification.",
67
- "Iterate toward the goal in bounded rounds: first summarize the previous round's error in one line (wrong fix, wrong node, or environment), fix its root cause — not the symptom — then rerun the failed node with a fresh plan. Never resubmit an unchanged fix; after two rounds failing the same way, stop and report evidence and remaining routes.",
71
+ "Long DAGs: prepareDagExecution → runDag → operationId. Never foreground-Bash task advance, tail/head pipes or nohup/Start-Process/start; do not end on accepted/queued/running or an operationId — NOT completion. Supervise operationGet/status/dagReport/dagDoctor/operationWait at 60s → 90s → 120s → 180s; reset to 60s on state change; 30-60s re-checks when stall suspected. operationWait MUST use afterSeq=previous nextSeq (recommendedNextCall). Heartbeats: not meaningful progress. Run id ≠ task id.",
72
+ "Failure: terminal runSummary first. With progress wait; else dagRerunPlan(fromNode=primaryFailure.nodeId); eligible → dagRerun: reruns the failed subgraph, keeps prior successes. Ineligible: Worker → workerTaskRetry; standalone → standaloneTaskRerun after contract adopt (regenerates the whole task, not node continue). Do not call dagResume; do not re-advance a run-failed task. Pre-run identical state twice: stop and report; never loop identical bash/read/grep. Approve only bounded writeSet inside allowedPaths, outside forbiddenPaths, with structured verification.",
73
+ "Iterate toward the goal in bounded rounds: first summarize the previous round's error in one line, fix its root cause — not the symptom — then rerun the failed node with a fresh plan. Never resubmit an unchanged fix; after two rounds failing the same way, stop and report evidence and remaining routes.",
68
74
  "Continue until success, user stop, or no safe recovery remains; then stop and report failure/evidence. Never create a new task for a transient failure or replace repair-pi with direct edits.",
75
+ "Narrate long-DAG progress briefly at start, meaningful phase changes/findings, verification failure/recovery, prolonged quiet and terminal state: say what finished and what is next. Never narrate unchanged operationWait polls or heartbeats, or claim beyond structured facts.",
69
76
  ].join("\n");
70
77
  /** Compose the inspectable system prompt actually injected into Operator Chat. */
71
78
  export function composeOperatorChatSystemPrompt(input) {
@@ -210,6 +217,106 @@ async function bindSessionExtensions(session) {
210
217
  function pinOperatorChatTools(session) {
211
218
  session.setActiveToolsByName(computeOperatorChatActiveToolNames(session));
212
219
  }
220
+ /**
221
+ * Pi has no hook result that merely appends instructions to its built-in
222
+ * automatic compactor: session_before_compact must either cancel or replace
223
+ * the whole compaction result. Keep the SDK algorithm intact and inject the
224
+ * current Todo as ephemeral context only after a successful compaction. The
225
+ * next turn resets the marker and TodoListRegistry clears the list.
226
+ */
227
+ export function createTodoCompactionContextExtension(options) {
228
+ return {
229
+ name: "operator-chat-todo-compaction-context",
230
+ hidden: true,
231
+ factory: (api) => {
232
+ let compactedInCurrentTurn = false;
233
+ api.on("turn_start", () => {
234
+ compactedInCurrentTurn = false;
235
+ });
236
+ api.on("session_compact", () => {
237
+ compactedInCurrentTurn = true;
238
+ });
239
+ api.on("context", (rawEvent) => {
240
+ if (!compactedInCurrentTurn)
241
+ return undefined;
242
+ const context = buildTodoContinuationContext(options.registry.get(options.sessionId));
243
+ if (!context)
244
+ return undefined;
245
+ const messages = Array.isArray(rawEvent.messages)
246
+ ? rawEvent.messages
247
+ : [];
248
+ return {
249
+ messages: [
250
+ ...messages,
251
+ {
252
+ role: "custom",
253
+ customType: "operator-chat-todo-context",
254
+ content: context,
255
+ display: false,
256
+ details: { todos: options.registry.get(options.sessionId) },
257
+ timestamp: Date.now(),
258
+ },
259
+ ],
260
+ };
261
+ });
262
+ },
263
+ };
264
+ }
265
+ /** Goal survives compaction and Turn boundaries; unlike Todo it is not reset
266
+ * at turn_start. The extension only injects after a successful compaction so
267
+ * ordinary contexts still rely on the model-callable get_goal source. */
268
+ export function createGoalCompactionContextExtension(options) {
269
+ return {
270
+ name: "operator-chat-goal-compaction-context",
271
+ hidden: true,
272
+ factory: (api) => {
273
+ let compacted = false;
274
+ api.on("session_compact", () => {
275
+ compacted = true;
276
+ });
277
+ api.on("context", (rawEvent) => {
278
+ if (!compacted)
279
+ return undefined;
280
+ const goal = options.registry.get(options.sessionId);
281
+ const context = buildGoalContinuationContext(goal);
282
+ if (!context)
283
+ return undefined;
284
+ const messages = Array.isArray(rawEvent.messages) ? rawEvent.messages : [];
285
+ return {
286
+ messages: [
287
+ ...messages,
288
+ {
289
+ role: "custom",
290
+ customType: "operator-chat-goal-context",
291
+ content: context,
292
+ display: false,
293
+ details: { goal },
294
+ timestamp: Date.now(),
295
+ },
296
+ ],
297
+ };
298
+ });
299
+ },
300
+ };
301
+ }
302
+ export function createWizardLocalHeadersExtension(options) {
303
+ return {
304
+ name: "operator-chat-wizard-local-headers",
305
+ hidden: true,
306
+ factory: (api) => {
307
+ api.on("before_provider_headers", async (rawEvent, context) => {
308
+ if (!context || !rawEvent.headers || typeof rawEvent.headers !== "object")
309
+ return;
310
+ await injectWizardLocalHeaders({
311
+ headers: rawEvent.headers,
312
+ context,
313
+ sessionId: options.sessionId,
314
+ service: options.service,
315
+ });
316
+ });
317
+ },
318
+ };
319
+ }
213
320
  /**
214
321
  * Build Pi custom ToolDefinition objects for every whitelisted operator action.
215
322
  * Each tool's execute() routes into the operator action dispatcher (Gate 3).
@@ -289,6 +396,150 @@ async function buildCustomOperatorTools(options) {
289
396
  });
290
397
  });
291
398
  }
399
+ const ASK_USER_QUESTION_DESCRIPTION = "Ask the user concise questions when a confirmation, choice, or missing detail is required before proceeding. " +
400
+ "The tool pauses until the user answers. Use it instead of writing questions as ordinary assistant text. " +
401
+ "Send one or more questions with stable ids; recommended options should be first and end with (Recommended).";
402
+ async function buildAskUserQuestionTool(options) {
403
+ const [{ Type }, { defineTool }] = await Promise.all([
404
+ import("typebox"),
405
+ import("@earendil-works/pi-coding-agent"),
406
+ ]);
407
+ return defineTool({
408
+ name: "ask_user_question",
409
+ label: "Ask user",
410
+ description: ASK_USER_QUESTION_DESCRIPTION,
411
+ promptSnippet: ASK_USER_QUESTION_DESCRIPTION,
412
+ parameters: Type.Object({
413
+ questions: Type.Array(Type.Object({
414
+ id: Type.String({ description: "Stable question id echoed in the answer." }),
415
+ question: Type.String({ description: "Specific user-facing question." }),
416
+ header: Type.Optional(Type.String({ description: "Optional short heading." })),
417
+ detail: Type.Optional(Type.String({ description: "Optional Markdown context shown below the question." })),
418
+ options: Type.Optional(Type.Array(Type.Object({
419
+ label: Type.String({ description: "Short user-facing option label." }),
420
+ description: Type.Optional(Type.String({ description: "One sentence explaining impact or tradeoff." })),
421
+ }, { additionalProperties: false }))),
422
+ multi_select: Type.Optional(Type.Boolean({ description: "Allow more than one option." })),
423
+ }, { additionalProperties: false }), { minItems: 1, maxItems: 20 }),
424
+ }, { additionalProperties: false }),
425
+ async execute(toolCallId, params, signal) {
426
+ const answer = await options.registry.ask({
427
+ sessionId: options.sessionId,
428
+ toolCallId,
429
+ questions: params.questions,
430
+ signal,
431
+ });
432
+ return {
433
+ content: [{ type: "text", text: JSON.stringify(answer) }],
434
+ details: answer,
435
+ };
436
+ },
437
+ });
438
+ }
439
+ const TODO_WRITE_DESCRIPTION = "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (no partial updates, no per-item edits). Before starting multi-step work, add one todo per concrete step. Keep at least one todo `in_progress` while work remains. Mark a todo `completed` immediately when it is done (do not batch completions) and resend the full list as progress or DAG state advances. Skip the list for simple Q&A, read-only lookups, and single-step tasks. Use it for multi-step implementation and whenever you prepare, run, or supervise a DAG — call `todo_write` before entering the DAG tool chain. Phrase DAG todos as user-facing phases users can understand, not copies of internal DAG nodes. Statuses: `pending` / `in_progress` / `completed`.";
440
+ async function buildTodoWriteTool(options) {
441
+ const [{ Type }, { defineTool }] = await Promise.all([
442
+ import("typebox"),
443
+ import("@earendil-works/pi-coding-agent"),
444
+ ]);
445
+ return defineTool({
446
+ name: "todo_write",
447
+ label: "Update todo list",
448
+ description: TODO_WRITE_DESCRIPTION,
449
+ promptSnippet: TODO_WRITE_DESCRIPTION,
450
+ parameters: Type.Object({
451
+ todos: Type.Array(Type.Object({
452
+ content: Type.String({ description: "Short imperative task description." }),
453
+ status: Type.Union([
454
+ Type.Literal("pending"),
455
+ Type.Literal("in_progress"),
456
+ Type.Literal("completed"),
457
+ ]),
458
+ }, { additionalProperties: false })),
459
+ }, { additionalProperties: false }),
460
+ async execute(toolCallId, params) {
461
+ const result = options.registry.write(options.sessionId, toolCallId, params.todos);
462
+ return {
463
+ content: [{ type: "text", text: JSON.stringify(result) }],
464
+ details: result,
465
+ };
466
+ },
467
+ });
468
+ }
469
+ const GET_GOAL_DESCRIPTION = "Read the current session's durable cross-turn Goal, including revision, status, round limit, and whether this Console process is authorized to continue it.";
470
+ const CREATE_GOAL_DESCRIPTION = "Create a durable cross-turn Goal only when the user explicitly asks to start or create a Goal. Never silently upgrade an ordinary request. A session may have only one unfinished Goal.";
471
+ const UPDATE_GOAL_DESCRIPTION = "Finish or block the current durable Goal using its exact goalId and revision. Set complete only when the objective is genuinely achieved and no required work remains. Set blocked only when safe progress cannot continue; include the blocker.";
472
+ async function buildGoalTools(options) {
473
+ const [{ Type }, { defineTool }] = await Promise.all([
474
+ import("typebox"),
475
+ import("@earendil-works/pi-coding-agent"),
476
+ ]);
477
+ const textResult = (value) => ({
478
+ content: [{ type: "text", text: JSON.stringify(value) }],
479
+ details: value,
480
+ });
481
+ return [
482
+ defineTool({
483
+ name: "get_goal",
484
+ label: "Get goal",
485
+ description: GET_GOAL_DESCRIPTION,
486
+ promptSnippet: GET_GOAL_DESCRIPTION,
487
+ parameters: Type.Object({}, { additionalProperties: false }),
488
+ async execute() {
489
+ return textResult({ goal: options.registry.get(options.sessionId) });
490
+ },
491
+ }),
492
+ defineTool({
493
+ name: "create_goal",
494
+ label: "Create goal",
495
+ description: CREATE_GOAL_DESCRIPTION,
496
+ promptSnippet: CREATE_GOAL_DESCRIPTION,
497
+ parameters: Type.Object({
498
+ objective: Type.String({
499
+ description: "Concrete final objective and completion standard explicitly requested by the user.",
500
+ }),
501
+ }, { additionalProperties: false }),
502
+ async execute(_toolCallId, params) {
503
+ if (!options.registry.consumeModelCreateGrant(options.sessionId)) {
504
+ return textResult({
505
+ ok: false,
506
+ code: "GOAL_EXPLICIT_REQUEST_REQUIRED",
507
+ message: "create_goal requires an explicit user request to create or start a Goal",
508
+ });
509
+ }
510
+ return textResult(options.registry.create({
511
+ sessionId: options.sessionId,
512
+ objective: params.objective,
513
+ }));
514
+ },
515
+ }),
516
+ defineTool({
517
+ name: "update_goal",
518
+ label: "Update goal",
519
+ description: UPDATE_GOAL_DESCRIPTION,
520
+ promptSnippet: UPDATE_GOAL_DESCRIPTION,
521
+ parameters: Type.Object({
522
+ goalId: Type.String(),
523
+ revision: Type.Number({ minimum: 1 }),
524
+ status: Type.Union([
525
+ Type.Literal("complete"),
526
+ Type.Literal("blocked"),
527
+ ]),
528
+ blocker: Type.Optional(Type.String()),
529
+ }, { additionalProperties: false }),
530
+ async execute(_toolCallId, params) {
531
+ return textResult(options.registry.update({
532
+ sessionId: options.sessionId,
533
+ goalId: params.goalId,
534
+ expectedRevision: params.revision,
535
+ phase: params.status,
536
+ blocker: params.blocker,
537
+ arm: false,
538
+ }));
539
+ },
540
+ }),
541
+ ];
542
+ }
292
543
  /**
293
544
  * Build the safe explore custom tools (roadmap M0-A / G16): safe-read,
294
545
  * safe-grep, gitStatus, gitDiff. These replace the bare SDK bash/read/grep so
@@ -699,6 +950,44 @@ export class PiSessionInitFailedError extends Error {
699
950
  this.name = "PiSessionInitFailedError";
700
951
  }
701
952
  }
953
+ async function readModelConfigFileVersion(filePath) {
954
+ try {
955
+ const value = await stat(filePath, { bigint: true });
956
+ return {
957
+ exists: true,
958
+ dev: value.dev,
959
+ ino: value.ino,
960
+ size: value.size,
961
+ mtimeNs: value.mtimeNs,
962
+ ctimeNs: value.ctimeNs,
963
+ };
964
+ }
965
+ catch (error) {
966
+ if (error !== null &&
967
+ typeof error === "object" &&
968
+ "code" in error &&
969
+ error.code === "ENOENT") {
970
+ return { exists: false };
971
+ }
972
+ throw new Error("MODEL_CONFIG_CHECK_FAILED");
973
+ }
974
+ }
975
+ function sameModelConfigFileVersion(left, right) {
976
+ if (!left.exists || !right.exists)
977
+ return left.exists === right.exists;
978
+ return (left.dev === right.dev &&
979
+ left.ino === right.ino &&
980
+ left.size === right.size &&
981
+ left.mtimeNs === right.mtimeNs &&
982
+ left.ctimeNs === right.ctimeNs);
983
+ }
984
+ async function captureModelConfigFile(agentDir) {
985
+ const filePath = path.join(agentDir, "models.json");
986
+ return {
987
+ path: filePath,
988
+ version: await readModelConfigFileVersion(filePath),
989
+ };
990
+ }
702
991
  /**
703
992
  * Console Pi runtime — holds Chat sessions and drives prompt() with three-gate
704
993
  * tool enforcement. Session-per-sessionId; cross-request reuse via open().
@@ -708,6 +997,8 @@ export class ConsolePiRuntime {
708
997
  loader;
709
998
  sessions = new Map();
710
999
  modelRuntimes = new Map();
1000
+ /** Non-sensitive models.json metadata used to avoid reparsing unchanged config. */
1001
+ modelConfigFiles = new Map();
711
1002
  sessionManagers = new Map();
712
1003
  /** Per-session SDK service scope (resourceLoader / settingsManager) used by the live runtime snapshot. */
713
1004
  serviceScopes = new Map();
@@ -717,6 +1008,8 @@ export class ConsolePiRuntime {
717
1008
  reloadInFlight = new Set();
718
1009
  /** Synchronous prompt ownership per session (admission before first await). */
719
1010
  promptOwners = new Set();
1011
+ /** Steering requests accepted by the SDK but not yet consumed into Pi context. */
1012
+ pendingSteering = new Map();
720
1013
  /** At most one detached automatic-title task per durable Console session. */
721
1014
  titleInFlight = new Set();
722
1015
  /** Composer thinking selection ("auto" = no explicit override). */
@@ -728,6 +1021,9 @@ export class ConsolePiRuntime {
728
1021
  sessionModels = new Map();
729
1022
  /** SessionIds disposed while materialization was still in flight. */
730
1023
  disposedSessions = new Set();
1024
+ compactionControllers = new Map();
1025
+ siftStates = new Map();
1026
+ /** Session-less tool definition caches (no AgentSession state). */
731
1027
  /** Session-less tool definition caches (no AgentSession state). */
732
1028
  operatorCustomToolsPromise;
733
1029
  exploreCustomToolsPromise;
@@ -765,9 +1061,44 @@ export class ConsolePiRuntime {
765
1061
  * after a PATCH sees the latest resource-preferences.json (not create-time
766
1062
  * closure state).
767
1063
  */
768
- async buildResourceLoaderOptions(base = {}) {
1064
+ async buildResourceLoaderOptions(base = {}, sessionId) {
1065
+ const inheritedFactories = Array.isArray(base.extensionFactories)
1066
+ ? base.extensionFactories
1067
+ : [];
1068
+ const todoContextExtension = sessionId && this.options.todoRegistry
1069
+ ? createTodoCompactionContextExtension({
1070
+ sessionId,
1071
+ registry: this.options.todoRegistry,
1072
+ })
1073
+ : undefined;
1074
+ const pressureExtension = sessionId
1075
+ ? this.createContextPressureInlineExtension(sessionId)
1076
+ : undefined;
1077
+ const goalContextExtension = sessionId && this.options.goalRegistry
1078
+ ? createGoalCompactionContextExtension({
1079
+ sessionId,
1080
+ registry: this.options.goalRegistry,
1081
+ })
1082
+ : undefined;
1083
+ const wizardLocalHeadersExtension = sessionId && this.options.sddDataAlignment
1084
+ ? createWizardLocalHeadersExtension({
1085
+ sessionId,
1086
+ service: this.options.sddDataAlignment,
1087
+ })
1088
+ : undefined;
1089
+ const extraFactories = [
1090
+ todoContextExtension,
1091
+ goalContextExtension,
1092
+ pressureExtension,
1093
+ wizardLocalHeadersExtension,
1094
+ ].filter((item) => Boolean(item));
769
1095
  return {
770
1096
  ...base,
1097
+ ...(extraFactories.length > 0
1098
+ ? {
1099
+ extensionFactories: [...inheritedFactories, ...extraFactories],
1100
+ }
1101
+ : {}),
771
1102
  skillsOverride: (current) => {
772
1103
  // Synchronous override surface: use last-known prefs via a sync
773
1104
  // fail-closed path. Prefer async cache filled by ensurePrefs.
@@ -790,6 +1121,126 @@ export class ConsolePiRuntime {
790
1121
  this.cachedSkillPrefs = prefs;
791
1122
  return prefs;
792
1123
  }
1124
+ getCompactionController(sessionId) {
1125
+ let controller = this.compactionControllers.get(sessionId);
1126
+ if (!controller) {
1127
+ controller = createCompactionController();
1128
+ this.compactionControllers.set(sessionId, controller);
1129
+ }
1130
+ if (this.options.todoRegistry) {
1131
+ controller.todos = this.options.todoRegistry.get(sessionId);
1132
+ }
1133
+ return controller;
1134
+ }
1135
+ createContextPressureInlineExtension(sessionId) {
1136
+ const policy = parseCompactionPolicy();
1137
+ const siftEnabled = isConsoleSiftEnabled();
1138
+ let sift;
1139
+ if (siftEnabled.enabled) {
1140
+ sift = this.siftStates.get(sessionId);
1141
+ if (!sift) {
1142
+ const config = parseSiftBridgeConfig({
1143
+ sessionId,
1144
+ defaultStashRoot: path.join(this.options.sessionDir, "sift-stash"),
1145
+ });
1146
+ sift = createSiftBridgeState(config);
1147
+ sift.counters = this.getCompactionController(sessionId).counters;
1148
+ this.siftStates.set(sessionId, sift);
1149
+ const housekeep = housekeepSiftStash({
1150
+ root: path.dirname(config.stashDir),
1151
+ activeSessionId: sessionId,
1152
+ retentionDays: config.retentionDays,
1153
+ });
1154
+ if (housekeep.failed)
1155
+ sift.diagnostics.add("housekeep-failed");
1156
+ }
1157
+ }
1158
+ return createContextPressureExtension({
1159
+ name: "operator-chat-context-pressure",
1160
+ policy,
1161
+ controller: this.getCompactionController(sessionId),
1162
+ sift,
1163
+ });
1164
+ }
1165
+ applySessionCompactionOverride(sessionId, services, session) {
1166
+ const manager = services?.settingsManager;
1167
+ const window = session?.getSessionStats?.()?.contextUsage?.contextWindow;
1168
+ applyProcessCompactionOverride(manager, {
1169
+ policy: parseCompactionPolicy(),
1170
+ ...(typeof window === "number" ? { contextWindow: window } : {}),
1171
+ });
1172
+ void sessionId;
1173
+ }
1174
+ async runPrePromptCompaction(sessionId, session, promptText, imageCount, onEvent) {
1175
+ const policy = parseCompactionPolicy();
1176
+ if (policy.mode === "off")
1177
+ return;
1178
+ const controller = this.getCompactionController(sessionId);
1179
+ const stats = session.getSessionStats?.();
1180
+ const window = stats?.contextUsage?.contextWindow;
1181
+ const tokens = stats?.contextUsage?.tokens;
1182
+ if (typeof window === "number" && window > 0) {
1183
+ this.applySessionCompactionOverride(sessionId, this.serviceScopes.get(sessionId) ?? {}, session);
1184
+ }
1185
+ const projection = projectPromptPressure({
1186
+ currentContextTokens: tokens,
1187
+ promptText,
1188
+ imageCount,
1189
+ });
1190
+ if (projection.usageUnavailable) {
1191
+ incrementPressureCounter(controller.counters, "usage-unavailable");
1192
+ return;
1193
+ }
1194
+ const effective = typeof window === "number" && window > 0
1195
+ ? deriveEffectiveWindow(window, policy)
1196
+ : undefined;
1197
+ if (!effective || projection.projected < effective.triggerTokens)
1198
+ return;
1199
+ if (typeof session.compact !== "function")
1200
+ return;
1201
+ const compactionId = newCompactionId(sessionId);
1202
+ onEvent({
1203
+ type: "compaction_start",
1204
+ sessionId,
1205
+ compactionId,
1206
+ reason: "threshold",
1207
+ });
1208
+ controller.proactiveCompaction = true;
1209
+ try {
1210
+ incrementPressureCounter(controller.counters, "pre-prompt-threshold");
1211
+ const result = await session.compact();
1212
+ const snapshot = projectCompactSnapshot(result ?? {});
1213
+ onEvent({
1214
+ type: "compaction_end",
1215
+ sessionId,
1216
+ compactionId,
1217
+ reason: "threshold",
1218
+ status: "completed",
1219
+ willRetry: false,
1220
+ summary: snapshot.summary,
1221
+ ...(snapshot.firstKeptEntryId
1222
+ ? { firstKeptEntryId: snapshot.firstKeptEntryId }
1223
+ : {}),
1224
+ ...(snapshot.tokensBefore === undefined
1225
+ ? {}
1226
+ : { tokensBefore: snapshot.tokensBefore }),
1227
+ });
1228
+ }
1229
+ catch {
1230
+ incrementPressureCounter(controller.counters, "l0-compact-failed");
1231
+ onEvent({
1232
+ type: "compaction_end",
1233
+ sessionId,
1234
+ compactionId,
1235
+ reason: "threshold",
1236
+ status: "failed",
1237
+ willRetry: false,
1238
+ });
1239
+ }
1240
+ finally {
1241
+ controller.proactiveCompaction = false;
1242
+ }
1243
+ }
793
1244
  /**
794
1245
  * Resolve a skill in the current session inventory by server-issued resourceId.
795
1246
  * Returns undefined when the id is unknown (caller maps to PI_SKILL_NOT_FOUND).
@@ -880,6 +1331,15 @@ export class ConsolePiRuntime {
880
1331
  if (!sessionFile) {
881
1332
  throw new Error(`chat session shell missing sessionFile for ${sessionId}`);
882
1333
  }
1334
+ // Pi's SessionManager.create deliberately postpones writing a JSONL until
1335
+ // an assistant response. Materialize a valid header now, otherwise Console
1336
+ // could persist a path that disappears on a restart before first reply.
1337
+ await this.bindings.materializeSessionShell({
1338
+ sessionManager,
1339
+ sessionId,
1340
+ sessionFile,
1341
+ cwd: this.options.cwd,
1342
+ });
883
1343
  this.sessionManagers.set(sessionId, sessionManager);
884
1344
  this.thinkingSelections.set(sessionId, "auto");
885
1345
  // Detached single-flight materialization; dependent routes await the same promise.
@@ -958,6 +1418,9 @@ export class ConsolePiRuntime {
958
1418
  if (this.disposedSessions.has(sessionId))
959
1419
  return;
960
1420
  const agentDir = await safeGetAgentDir(this.bindings);
1421
+ // Capture before services parse models.json. A concurrent edit can therefore
1422
+ // cause at most one harmless extra refresh, never a missed next-turn refresh.
1423
+ const modelConfigFile = await captureModelConfigFile(agentDir);
961
1424
  const appendSystemPrompt = [
962
1425
  OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
963
1426
  ...(init.systemPromptSuffix ? [init.systemPromptSuffix] : []),
@@ -969,9 +1432,7 @@ export class ConsolePiRuntime {
969
1432
  const { services } = await this.bindings.createServices({
970
1433
  cwd: this.options.cwd,
971
1434
  agentDir,
972
- resourceLoaderOptions: await this.buildResourceLoaderOptions({
973
- appendSystemPrompt,
974
- }),
1435
+ resourceLoaderOptions: await this.buildResourceLoaderOptions({ appendSystemPrompt }, sessionId),
975
1436
  });
976
1437
  if (this.disposedSessions.has(sessionId))
977
1438
  return;
@@ -988,7 +1449,7 @@ export class ConsolePiRuntime {
988
1449
  }) ?? undefined)
989
1450
  : undefined;
990
1451
  assertNoWriteToolInList(OPERATOR_CHAT_ALLOWED_TOOLS);
991
- const customTools = await this.loadCustomTools();
1452
+ const customTools = await this.loadCustomTools(sessionId);
992
1453
  if (this.disposedSessions.has(sessionId))
993
1454
  return;
994
1455
  // pi-web parity: do NOT pass `tools`. A closed allowlist becomes
@@ -1019,11 +1480,13 @@ export class ConsolePiRuntime {
1019
1480
  this.sessions.set(sessionId, session);
1020
1481
  this.sessionManagers.set(sessionId, init.sessionManager);
1021
1482
  this.modelRuntimes.set(sessionId, modelRuntime);
1483
+ this.modelConfigFiles.set(sessionId, modelConfigFile);
1022
1484
  this.sessionModels.set(sessionId, model);
1023
1485
  this.serviceScopes.set(sessionId, {
1024
1486
  resourceLoader: services.resourceLoader,
1025
1487
  settingsManager: services.settingsManager,
1026
1488
  });
1489
+ this.applySessionCompactionOverride(sessionId, services, session);
1027
1490
  this.revisions.set(sessionId, 1);
1028
1491
  if (!this.thinkingSelections.has(sessionId)) {
1029
1492
  this.thinkingSelections.set(sessionId, "auto");
@@ -1038,6 +1501,7 @@ export class ConsolePiRuntime {
1038
1501
  this.sessions.delete(sessionId);
1039
1502
  this.sessionManagers.delete(sessionId);
1040
1503
  this.modelRuntimes.delete(sessionId);
1504
+ this.modelConfigFiles.delete(sessionId);
1041
1505
  this.sessionModels.delete(sessionId);
1042
1506
  this.serviceScopes.delete(sessionId);
1043
1507
  this.revisions.delete(sessionId);
@@ -1045,12 +1509,30 @@ export class ConsolePiRuntime {
1045
1509
  }
1046
1510
  }
1047
1511
  /** Cached session-less custom tool definitions (operator + explore). */
1048
- async loadCustomTools() {
1512
+ async loadCustomTools(sessionId) {
1049
1513
  const [operatorCustomTools, exploreCustomTools] = await Promise.all([
1050
1514
  this.loadOperatorCustomTools(),
1051
1515
  this.loadExploreCustomTools(),
1052
1516
  ]);
1053
- return [...operatorCustomTools, ...exploreCustomTools];
1517
+ const questionTool = this.options.questionRegistry
1518
+ ? await buildAskUserQuestionTool({
1519
+ sessionId,
1520
+ registry: this.options.questionRegistry,
1521
+ })
1522
+ : undefined;
1523
+ const todoTool = this.options.todoRegistry
1524
+ ? await buildTodoWriteTool({ sessionId, registry: this.options.todoRegistry })
1525
+ : undefined;
1526
+ const goalTools = this.options.goalRegistry
1527
+ ? await buildGoalTools({ sessionId, registry: this.options.goalRegistry })
1528
+ : [];
1529
+ return [
1530
+ ...operatorCustomTools,
1531
+ ...exploreCustomTools,
1532
+ ...(questionTool ? [questionTool] : []),
1533
+ ...(todoTool ? [todoTool] : []),
1534
+ ...goalTools,
1535
+ ];
1054
1536
  }
1055
1537
  loadOperatorCustomTools() {
1056
1538
  if (!this.options.actionContext)
@@ -1090,6 +1572,7 @@ export class ConsolePiRuntime {
1090
1572
  targetSessionId: sessionId,
1091
1573
  });
1092
1574
  const built = await this.buildSessionWithServices({
1575
+ sessionId,
1093
1576
  sessionManager,
1094
1577
  model: init.model,
1095
1578
  });
@@ -1097,6 +1580,7 @@ export class ConsolePiRuntime {
1097
1580
  this.sessions.set(sessionId, built.session);
1098
1581
  this.sessionManagers.set(sessionId, sessionManager);
1099
1582
  this.modelRuntimes.set(sessionId, built.modelRuntime);
1583
+ this.modelConfigFiles.set(sessionId, built.modelConfigFile);
1100
1584
  this.sessionModels.set(sessionId, init.model);
1101
1585
  this.serviceScopes.set(sessionId, built.services);
1102
1586
  this.revisions.set(sessionId, 1);
@@ -1168,11 +1652,69 @@ export class ConsolePiRuntime {
1168
1652
  if (!resolved)
1169
1653
  throw new Error("MODEL_NOT_AVAILABLE");
1170
1654
  await session.setModel(resolved);
1171
- this.bumpRevision(sessionId);
1172
- return {
1655
+ const applied = {
1173
1656
  provider: session.model?.provider ?? model.provider,
1174
1657
  modelId: session.model?.id ?? session.model?.modelId ?? model.modelId,
1175
1658
  };
1659
+ this.sessionModels.set(sessionId, applied);
1660
+ this.bumpRevision(sessionId);
1661
+ return applied;
1662
+ }
1663
+ async refreshModelConfiguration(sessionId, mode) {
1664
+ const session = this.sessions.get(sessionId);
1665
+ const modelRuntime = this.modelRuntimes.get(sessionId);
1666
+ const configFile = this.modelConfigFiles.get(sessionId);
1667
+ if (!session || !modelRuntime || !configFile) {
1668
+ throw new Error(`chat session not active: ${sessionId}`);
1669
+ }
1670
+ const nextVersion = await readModelConfigFileVersion(configFile.path);
1671
+ if (mode === "if-changed" &&
1672
+ sameModelConfigFileVersion(configFile.version, nextVersion)) {
1673
+ return false;
1674
+ }
1675
+ if (typeof modelRuntime.refresh !== "function") {
1676
+ throw new Error("MODEL_CONFIG_REFRESH_UNSUPPORTED");
1677
+ }
1678
+ const stored = this.sessionModels.get(sessionId);
1679
+ const provider = session.model?.provider ?? stored?.provider;
1680
+ const modelId = session.model?.id ?? session.model?.modelId ?? stored?.modelId;
1681
+ try {
1682
+ await modelRuntime.refresh({ allowNetwork: false });
1683
+ if (typeof modelRuntime.getError === "function" && modelRuntime.getError()) {
1684
+ throw new Error("MODEL_CONFIG_REFRESH_FAILED");
1685
+ }
1686
+ if (provider && modelId) {
1687
+ if (typeof session.setModel !== "function") {
1688
+ throw new Error("MODEL_CONFIG_REBIND_UNSUPPORTED");
1689
+ }
1690
+ const resolved = this.bindings.resolveModel({
1691
+ modelRuntime,
1692
+ provider,
1693
+ modelId,
1694
+ });
1695
+ if (!resolved) {
1696
+ throw new Error("MODEL_NOT_AVAILABLE_AFTER_CONFIG_REFRESH");
1697
+ }
1698
+ await session.setModel(resolved);
1699
+ this.sessionModels.set(sessionId, { provider, modelId });
1700
+ }
1701
+ }
1702
+ catch (error) {
1703
+ if (error instanceof Error &&
1704
+ (error.message === "MODEL_CONFIG_REBIND_UNSUPPORTED" ||
1705
+ error.message === "MODEL_NOT_AVAILABLE_AFTER_CONFIG_REFRESH")) {
1706
+ throw error;
1707
+ }
1708
+ // Do not surface SDK/config error text: it may contain credential material.
1709
+ throw new Error("MODEL_CONFIG_REFRESH_FAILED");
1710
+ }
1711
+ if (this.disposedSessions.has(sessionId) ||
1712
+ this.sessions.get(sessionId) !== session) {
1713
+ throw new Error(`chat session not active: ${sessionId}`);
1714
+ }
1715
+ configFile.version = nextVersion;
1716
+ this.bumpRevision(sessionId);
1717
+ return true;
1176
1718
  }
1177
1719
  /**
1178
1720
  * Apply a thinking-level selection. `auto` records the selection WITHOUT
@@ -1295,6 +1837,8 @@ export class ConsolePiRuntime {
1295
1837
  };
1296
1838
  }
1297
1839
  const busyReasons = [];
1840
+ if (this.promptOwners.has(sessionId))
1841
+ busyReasons.push("prompt in flight");
1298
1842
  if (session.isStreaming === true || session.isIdle === false)
1299
1843
  busyReasons.push("streaming");
1300
1844
  if (session.isCompacting === true)
@@ -1323,6 +1867,10 @@ export class ConsolePiRuntime {
1323
1867
  // the latest resource-preferences.json written by PATCH.
1324
1868
  await this.refreshSkillPrefsCache().catch(() => undefined);
1325
1869
  await session.reload();
1870
+ const services = this.serviceScopes.get(sessionId);
1871
+ if (services)
1872
+ this.applySessionCompactionOverride(sessionId, services, session);
1873
+ await this.refreshModelConfiguration(sessionId, "force");
1326
1874
  }
1327
1875
  catch (error) {
1328
1876
  return {
@@ -1334,7 +1882,9 @@ export class ConsolePiRuntime {
1334
1882
  finally {
1335
1883
  this.reloadInFlight.delete(sessionId);
1336
1884
  }
1337
- this.bumpRevision(sessionId);
1885
+ // Reload replaces the effective resource/session context. Persisted Goal
1886
+ // remains visible, but continuation authorization must be renewed by user.
1887
+ this.options.goalRegistry?.disarm(sessionId);
1338
1888
  return { ok: true, revision: this.revisions.get(sessionId) ?? 0 };
1339
1889
  }
1340
1890
  /**
@@ -1780,6 +2330,9 @@ export class ConsolePiRuntime {
1780
2330
  if (this.sessions.has(sessionId)) {
1781
2331
  return { ok: true, handle: await this.snapshotActive(sessionId) };
1782
2332
  }
2333
+ // A newly materialized Pi session must never inherit process-local Goal
2334
+ // activation from an earlier disposed runtime instance.
2335
+ this.options.goalRegistry?.disarm(sessionId);
1783
2336
  if (!init.sessionFile) {
1784
2337
  return {
1785
2338
  ok: false,
@@ -1794,6 +2347,16 @@ export class ConsolePiRuntime {
1794
2347
  });
1795
2348
  }
1796
2349
  catch (error) {
2350
+ const code = error && typeof error === "object" && "code" in error
2351
+ ? String(error.code ?? "")
2352
+ : "";
2353
+ if (code === "SESSION_FILE_MISSING" || code === "ENOENT") {
2354
+ return {
2355
+ ok: false,
2356
+ code: "NO_SESSION_FILE",
2357
+ message: `Pi session file missing or not openable: ${init.sessionFile}`,
2358
+ };
2359
+ }
1797
2360
  return {
1798
2361
  ok: false,
1799
2362
  code: "REOPEN_FAILED",
@@ -1817,6 +2380,7 @@ export class ConsolePiRuntime {
1817
2380
  }
1818
2381
  try {
1819
2382
  const built = await this.buildSessionWithServices({
2383
+ sessionId,
1820
2384
  sessionManager,
1821
2385
  model: init.model,
1822
2386
  systemPromptSuffix: init.systemPromptSuffix,
@@ -1846,6 +2410,7 @@ export class ConsolePiRuntime {
1846
2410
  this.sessions.set(sessionId, session);
1847
2411
  this.sessionManagers.set(sessionId, sessionManager);
1848
2412
  this.modelRuntimes.set(sessionId, built.modelRuntime);
2413
+ this.modelConfigFiles.set(sessionId, built.modelConfigFile);
1849
2414
  this.sessionModels.set(sessionId, init.model);
1850
2415
  this.serviceScopes.set(sessionId, built.services);
1851
2416
  this.revisions.set(sessionId, 1);
@@ -1899,6 +2464,7 @@ export class ConsolePiRuntime {
1899
2464
  */
1900
2465
  async buildSessionWithServices(init) {
1901
2466
  const agentDir = await safeGetAgentDir(this.bindings);
2467
+ const modelConfigFile = await captureModelConfigFile(agentDir);
1902
2468
  const appendSystemPrompt = [
1903
2469
  OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
1904
2470
  ...(init.systemPromptSuffix ? [init.systemPromptSuffix] : []),
@@ -1907,9 +2473,7 @@ export class ConsolePiRuntime {
1907
2473
  const { services } = await this.bindings.createServices({
1908
2474
  cwd: this.options.cwd,
1909
2475
  agentDir,
1910
- resourceLoaderOptions: await this.buildResourceLoaderOptions({
1911
- appendSystemPrompt,
1912
- }),
2476
+ resourceLoaderOptions: await this.buildResourceLoaderOptions({ appendSystemPrompt }, init.sessionId),
1913
2477
  });
1914
2478
  const modelRuntime = services.modelRuntime;
1915
2479
  const resolvedModel = init.model
@@ -1920,7 +2484,7 @@ export class ConsolePiRuntime {
1920
2484
  }) ?? undefined)
1921
2485
  : undefined;
1922
2486
  assertNoWriteToolInList(OPERATOR_CHAT_ALLOWED_TOOLS);
1923
- const customTools = await this.loadCustomTools();
2487
+ const customTools = await this.loadCustomTools(init.sessionId);
1924
2488
  const { session } = await this.bindings.createSessionFromServices({
1925
2489
  services,
1926
2490
  sessionManager: init.sessionManager,
@@ -1930,9 +2494,11 @@ export class ConsolePiRuntime {
1930
2494
  });
1931
2495
  await bindSessionExtensions(session);
1932
2496
  pinOperatorChatTools(session);
2497
+ this.applySessionCompactionOverride(init.sessionId, services, session);
1933
2498
  return {
1934
2499
  session,
1935
2500
  modelRuntime,
2501
+ modelConfigFile,
1936
2502
  services: {
1937
2503
  resourceLoader: services.resourceLoader,
1938
2504
  settingsManager: services.settingsManager,
@@ -1943,6 +2509,33 @@ export class ConsolePiRuntime {
1943
2509
  open(sessionId) {
1944
2510
  return this.sessions.get(sessionId);
1945
2511
  }
2512
+ /** Inject one queued message into the currently running Pi turn. */
2513
+ async steer(sessionId, clientRequestId, text, images) {
2514
+ const session = this.sessions.get(sessionId);
2515
+ if (!session || !this.promptOwners.has(sessionId) || session.isStreaming === false) {
2516
+ throw new Error("CHAT_TURN_NOT_ACTIVE");
2517
+ }
2518
+ if (typeof session.steer !== "function")
2519
+ throw new Error("CHAT_STEER_UNAVAILABLE");
2520
+ const pending = this.pendingSteering.get(sessionId) ?? [];
2521
+ const identity = { clientRequestId, text };
2522
+ pending.push(identity);
2523
+ this.pendingSteering.set(sessionId, pending);
2524
+ try {
2525
+ await session.steer(text, images);
2526
+ }
2527
+ catch (error) {
2528
+ const current = this.pendingSteering.get(sessionId);
2529
+ if (current) {
2530
+ const index = current.indexOf(identity);
2531
+ if (index >= 0)
2532
+ current.splice(index, 1);
2533
+ if (current.length === 0)
2534
+ this.pendingSteering.delete(sessionId);
2535
+ }
2536
+ throw error;
2537
+ }
2538
+ }
1946
2539
  hasSession(sessionId) {
1947
2540
  return this.sessions.has(sessionId);
1948
2541
  }
@@ -1961,6 +2554,12 @@ export class ConsolePiRuntime {
1961
2554
  session?.hasPendingBashMessages === true,
1962
2555
  };
1963
2556
  }
2557
+ /** Low-cardinality context-pressure counters; never includes payload text. */
2558
+ getContextPressureTelemetry(sessionId) {
2559
+ const counters = this.compactionControllers.get(sessionId)?.counters ??
2560
+ this.siftStates.get(sessionId)?.counters;
2561
+ return projectSafeTelemetry(counters ?? emptyContextPressureCounters());
2562
+ }
1964
2563
  /**
1965
2564
  * Send a prompt and stream events. Gate 3: each tool invocation is
1966
2565
  * re-authorized by authorizeOperatorChatTool before the dispatcher runs it
@@ -1971,12 +2570,13 @@ export class ConsolePiRuntime {
1971
2570
  */
1972
2571
  async prompt(sessionId, text, onEvent, options) {
1973
2572
  // Synchronous admission fence — before any await.
1974
- if (this.promptOwners.has(sessionId)) {
2573
+ if (this.promptOwners.has(sessionId) || this.reloadInFlight.has(sessionId)) {
1975
2574
  throw new Error("CHAT_TURN_ACTIVE");
1976
2575
  }
1977
2576
  this.promptOwners.add(sessionId);
1978
2577
  let unsub;
1979
2578
  let abortPromise;
2579
+ let initialUserMessageStarted = false;
1980
2580
  const onAbort = () => {
1981
2581
  // M1 T08 / AC-R3-003: Stop must abort only the current turn, NEVER
1982
2582
  // dispose the session. Await session.abort() so ownership settles
@@ -1997,6 +2597,15 @@ export class ConsolePiRuntime {
1997
2597
  }
1998
2598
  };
1999
2599
  try {
2600
+ if (options?.turnId && this.options.questionRegistry) {
2601
+ this.options.questionRegistry.setTurn(sessionId, options.turnId);
2602
+ }
2603
+ if (options?.turnId && this.options.todoRegistry) {
2604
+ this.options.todoRegistry.startTurn(sessionId, options.turnId);
2605
+ }
2606
+ if (this.options.goalRegistry) {
2607
+ this.options.goalRegistry.startTurn(sessionId, text);
2608
+ }
2000
2609
  // AC-FIX-002: if Stop already fired before readiness, never start model work.
2001
2610
  if (options?.signal?.aborted) {
2002
2611
  return;
@@ -2024,6 +2633,11 @@ export class ConsolePiRuntime {
2024
2633
  if (options?.signal?.aborted) {
2025
2634
  return;
2026
2635
  }
2636
+ await this.refreshModelConfiguration(sessionId, "if-changed");
2637
+ // Stop may arrive while stat/refresh/rebind is in flight.
2638
+ if (options?.signal?.aborted) {
2639
+ return;
2640
+ }
2027
2641
  const emitContextUsage = () => {
2028
2642
  try {
2029
2643
  const contextUsage = session.getSessionStats?.()?.contextUsage;
@@ -2050,19 +2664,118 @@ export class ConsolePiRuntime {
2050
2664
  }
2051
2665
  };
2052
2666
  emitContextUsage();
2667
+ await this.runPrePromptCompaction(sessionId, session, text, options?.images?.length ?? 0, onEvent);
2668
+ let stepStartedAt;
2669
+ let firstTokenAt;
2670
+ let pendingProviderError;
2671
+ let providerErrorEmitted = false;
2672
+ let activeCompaction;
2673
+ const emitPendingProviderError = () => {
2674
+ if (!pendingProviderError)
2675
+ return;
2676
+ onEvent(pendingProviderError);
2677
+ pendingProviderError = undefined;
2678
+ providerErrorEmitted = true;
2679
+ };
2053
2680
  unsub = session.subscribe((event) => {
2054
- const mapped = mapSdkEvent(sessionId, event);
2055
- if (mapped)
2056
- onEvent(mapped);
2681
+ const observedAt = Date.now();
2682
+ if (event.type === "message_start" && isUserSdkMessage(event.message)) {
2683
+ if (!initialUserMessageStarted) {
2684
+ // The first user message_start belongs to session.prompt(text), not
2685
+ // to a steering request that may have raced with prompt startup.
2686
+ initialUserMessageStarted = true;
2687
+ }
2688
+ else {
2689
+ const pending = this.pendingSteering.get(sessionId);
2690
+ const accepted = pending?.shift();
2691
+ if (pending?.length === 0)
2692
+ this.pendingSteering.delete(sessionId);
2693
+ if (accepted) {
2694
+ onEvent({
2695
+ type: "steering_accepted",
2696
+ sessionId,
2697
+ clientRequestId: accepted.clientRequestId,
2698
+ text: accepted.text,
2699
+ });
2700
+ }
2701
+ }
2702
+ }
2703
+ if (event.type === "compaction_start") {
2704
+ activeCompaction = {
2705
+ compactionId: newCompactionId(sessionId),
2706
+ reason: event.reason,
2707
+ };
2708
+ }
2709
+ const compactionId = event.type === "compaction_start" || event.type === "compaction_end"
2710
+ ? activeCompaction?.compactionId ?? newCompactionId(sessionId)
2711
+ : undefined;
2712
+ const mapped = mapSdkEvent(sessionId, event, compactionId);
2713
+ if (event.type === "compaction_end")
2714
+ activeCompaction = undefined;
2715
+ if (mapped?.type === "error") {
2716
+ // Pi represents provider failures as an assistant message_end and may
2717
+ // retry internally. Hold the candidate until the SDK says the attempt
2718
+ // is terminal; a later successful message_end supersedes it.
2719
+ pendingProviderError = mapped;
2720
+ stepStartedAt = undefined;
2721
+ firstTokenAt = undefined;
2722
+ return;
2723
+ }
2724
+ if (mapped?.type === "message_end")
2725
+ pendingProviderError = undefined;
2726
+ if (mapped?.type === "compaction_end" &&
2727
+ mapped.reason === "overflow" &&
2728
+ mapped.status === "completed" &&
2729
+ mapped.willRetry) {
2730
+ // The overflow error was a recoverable attempt fact. Pi has already
2731
+ // committed the compacted session and scheduled the continuation.
2732
+ pendingProviderError = undefined;
2733
+ }
2734
+ if (mapped?.type === "agent_settled") {
2735
+ emitPendingProviderError();
2736
+ }
2737
+ if (mapped?.type === "agent_start") {
2738
+ stepStartedAt = observedAt;
2739
+ firstTokenAt = undefined;
2740
+ }
2741
+ if (mapped?.type === "message_update" && firstTokenAt === undefined) {
2742
+ firstTokenAt = observedAt;
2743
+ }
2057
2744
  // Pi puts per-assistant-message usage on `message.usage` ({ input, output,
2058
2745
  // cacheRead, cacheWrite, totalTokens, cost }). Emit on message_end so
2059
2746
  // multi-step tool turns accumulate like pi-web SessionInfoBar; turn_end
2060
2747
  // repeats the final message and must not double-count.
2061
- if (event.type === "message_end") {
2748
+ if (mapped?.type === "message_end") {
2062
2749
  const usage = extractUsageSample(event);
2750
+ const timing = stepStartedAt === undefined
2751
+ ? undefined
2752
+ : {
2753
+ llmMs: Math.max(0, observedAt - stepStartedAt),
2754
+ ...(firstTokenAt === undefined
2755
+ ? {}
2756
+ : {
2757
+ ttftMs: Math.max(0, firstTokenAt - stepStartedAt),
2758
+ decodeMs: Math.max(0, observedAt - firstTokenAt),
2759
+ }),
2760
+ ...(usage?.outputTokens === undefined
2761
+ ? {}
2762
+ : { outputTokens: usage.outputTokens }),
2763
+ };
2764
+ onEvent({ ...mapped, ...(timing ? { timing } : {}) });
2063
2765
  if (usage)
2064
2766
  onEvent({ type: "usage", sessionId, usage });
2065
2767
  emitContextUsage();
2768
+ stepStartedAt = undefined;
2769
+ firstTokenAt = undefined;
2770
+ }
2771
+ else if (mapped) {
2772
+ onEvent(mapped);
2773
+ if (mapped.type === "tool_result") {
2774
+ // The next model request starts after the final completed tool. If
2775
+ // tools run concurrently, the last result naturally wins.
2776
+ stepStartedAt = observedAt;
2777
+ firstTokenAt = undefined;
2778
+ }
2066
2779
  }
2067
2780
  // Keep the context fill bar live through the turn (pi-web SessionInfoBar).
2068
2781
  if (event.type === "agent_start" ||
@@ -2094,6 +2807,7 @@ export class ConsolePiRuntime {
2094
2807
  // User abort is closed out as Turn state `aborted`; do not publish a
2095
2808
  // red ordinary error event for intentional Stop.
2096
2809
  if (!options?.signal?.aborted) {
2810
+ emitPendingProviderError();
2097
2811
  onEvent({ type: "agent_settled", sessionId });
2098
2812
  }
2099
2813
  }
@@ -2104,8 +2818,16 @@ export class ConsolePiRuntime {
2104
2818
  // User abort: swallow ordinary error publication (AC-FIX-003).
2105
2819
  return;
2106
2820
  }
2107
- const message = error instanceof Error ? error.message : String(error);
2108
- onEvent({ type: "error", sessionId, message });
2821
+ emitPendingProviderError();
2822
+ if (!providerErrorEmitted) {
2823
+ const providerError = parseProviderError(error);
2824
+ onEvent({
2825
+ type: "error",
2826
+ sessionId,
2827
+ message: providerError.message,
2828
+ providerError,
2829
+ });
2830
+ }
2109
2831
  throw error;
2110
2832
  }
2111
2833
  finally {
@@ -2114,6 +2836,12 @@ export class ConsolePiRuntime {
2114
2836
  }
2115
2837
  }
2116
2838
  finally {
2839
+ if (this.options.questionRegistry)
2840
+ this.options.questionRegistry.clearTurn(sessionId);
2841
+ // Unconsumed durable DeferredTurns remain dispatching and are recovered by
2842
+ // the route layer after this active Turn closes. Never carry their volatile
2843
+ // identities into a later prompt.
2844
+ this.pendingSteering.delete(sessionId);
2117
2845
  this.promptOwners.delete(sessionId);
2118
2846
  }
2119
2847
  }
@@ -2211,13 +2939,17 @@ export class ConsolePiRuntime {
2211
2939
  throw new Error("CHAT_TURN_ACTIVE");
2212
2940
  if (typeof session.compact !== "function")
2213
2941
  throw new Error("COMPACTION_UNSUPPORTED");
2942
+ incrementPressureCounter(this.getCompactionController(sessionId).counters, "manual");
2214
2943
  const result = await session.compact(customInstructions);
2215
2944
  return projectCompactSnapshot(result ?? {});
2216
2945
  }
2217
2946
  dispose(sessionId) {
2218
2947
  // Mark disposed first so a late materialization never registers ready.
2219
2948
  this.disposedSessions.add(sessionId);
2949
+ this.options.goalRegistry?.disarm(sessionId);
2220
2950
  this.sessionInit.delete(sessionId);
2951
+ this.compactionControllers.delete(sessionId);
2952
+ this.siftStates.delete(sessionId);
2221
2953
  const session = this.sessions.get(sessionId);
2222
2954
  if (session) {
2223
2955
  try {
@@ -2231,11 +2963,13 @@ export class ConsolePiRuntime {
2231
2963
  this.sessionManagers.delete(sessionId);
2232
2964
  this.mainlineLeaves.delete(sessionId);
2233
2965
  this.modelRuntimes.delete(sessionId);
2966
+ this.modelConfigFiles.delete(sessionId);
2234
2967
  this.sessionModels.delete(sessionId);
2235
2968
  this.serviceScopes.delete(sessionId);
2236
2969
  this.revisions.delete(sessionId);
2237
2970
  this.thinkingSelections.delete(sessionId);
2238
2971
  this.reloadInFlight.delete(sessionId);
2972
+ this.pendingSteering.delete(sessionId);
2239
2973
  }
2240
2974
  disposeAll() {
2241
2975
  for (const id of [...this.sessions.keys()])
@@ -2243,6 +2977,23 @@ export class ConsolePiRuntime {
2243
2977
  }
2244
2978
  }
2245
2979
  function mapAssistantMessageEvent(type, sessionId, message) {
2980
+ const record = message !== null && typeof message === "object"
2981
+ ? message
2982
+ : undefined;
2983
+ if (type === "message_end" &&
2984
+ record?.stopReason === "error") {
2985
+ const content = extractAssistantContentBlocks(message);
2986
+ const providerError = parseProviderError(typeof record.errorMessage === "string"
2987
+ ? record.errorMessage
2988
+ : "Provider request failed");
2989
+ return {
2990
+ type: "error",
2991
+ sessionId,
2992
+ message: providerError.message,
2993
+ providerError,
2994
+ ...(content.length > 0 ? { content } : {}),
2995
+ };
2996
+ }
2246
2997
  const content = extractAssistantContentBlocks(message);
2247
2998
  return {
2248
2999
  type,
@@ -2251,7 +3002,12 @@ function mapAssistantMessageEvent(type, sessionId, message) {
2251
3002
  ...(content.length > 0 ? { content } : {}),
2252
3003
  };
2253
3004
  }
2254
- function mapSdkEvent(sessionId, event) {
3005
+ function isUserSdkMessage(message) {
3006
+ return Boolean(message &&
3007
+ typeof message === "object" &&
3008
+ message.role === "user");
3009
+ }
3010
+ function mapSdkEvent(sessionId, event, compactionId) {
2255
3011
  switch (event.type) {
2256
3012
  case "agent_start":
2257
3013
  return { type: "agent_start", sessionId };
@@ -2292,10 +3048,56 @@ function mapSdkEvent(sessionId, event) {
2292
3048
  };
2293
3049
  case "agent_settled":
2294
3050
  return { type: "agent_settled", sessionId };
3051
+ case "compaction_start":
3052
+ return {
3053
+ type: "compaction_start",
3054
+ sessionId,
3055
+ compactionId: compactionId ?? newCompactionId(sessionId),
3056
+ reason: event.reason,
3057
+ };
3058
+ case "compaction_end": {
3059
+ const snapshot = event.result
3060
+ ? projectCompactSnapshot(event.result)
3061
+ : undefined;
3062
+ return {
3063
+ type: "compaction_end",
3064
+ sessionId,
3065
+ compactionId: compactionId ?? newCompactionId(sessionId),
3066
+ reason: event.reason,
3067
+ status: event.aborted
3068
+ ? "aborted"
3069
+ : snapshot
3070
+ ? "completed"
3071
+ : "failed",
3072
+ ...(snapshot
3073
+ ? {
3074
+ summary: snapshot.summary,
3075
+ ...(snapshot.firstKeptEntryId
3076
+ ? { firstKeptEntryId: snapshot.firstKeptEntryId }
3077
+ : {}),
3078
+ ...(snapshot.tokensBefore === undefined
3079
+ ? {}
3080
+ : { tokensBefore: snapshot.tokensBefore }),
3081
+ ...(snapshot.estimatedTokensAfter === undefined
3082
+ ? {}
3083
+ : {
3084
+ estimatedTokensAfter: snapshot.estimatedTokensAfter,
3085
+ }),
3086
+ }
3087
+ : {}),
3088
+ willRetry: Boolean(event.willRetry),
3089
+ ...(event.errorMessage
3090
+ ? { errorMessage: redactRuntimeText(event.errorMessage, 600) }
3091
+ : {}),
3092
+ };
3093
+ }
2295
3094
  default:
2296
3095
  return undefined;
2297
3096
  }
2298
3097
  }
3098
+ function newCompactionId(sessionId) {
3099
+ return `${sessionId}:compaction:${randomBytes(8).toString("hex")}`;
3100
+ }
2299
3101
  async function waitForIdle(session, options) {
2300
3102
  // Default 45s — shorter than the previous 120s so a stuck SDK session does
2301
3103
  // not pin an HTTP connection for two full minutes. The SDK agent turn
@@ -2390,6 +3192,36 @@ export function createDefaultPiSdkBindings() {
2390
3192
  id: opts.sessionId,
2391
3193
  });
2392
3194
  },
3195
+ materializeSessionShell: async (opts) => {
3196
+ const sdk = (await loadSdk());
3197
+ const manager = opts.sessionManager;
3198
+ if (typeof manager.setSessionFile !== "function") {
3199
+ throw new Error("Pi SessionManager cannot materialize a session file");
3200
+ }
3201
+ let created = false;
3202
+ try {
3203
+ await mkdir(path.dirname(opts.sessionFile), { recursive: true });
3204
+ // Match Pi's documented session header. Rebinding through the public
3205
+ // SessionManager API marks it flushed, so Pi appends the first user
3206
+ // entry instead of trying to create the already-present file later.
3207
+ await writeFile(opts.sessionFile, `${JSON.stringify({
3208
+ type: "session",
3209
+ version: typeof sdk.CURRENT_SESSION_VERSION === "number"
3210
+ ? sdk.CURRENT_SESSION_VERSION
3211
+ : 3,
3212
+ id: opts.sessionId,
3213
+ timestamp: new Date().toISOString(),
3214
+ cwd: opts.cwd,
3215
+ })}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
3216
+ created = true;
3217
+ manager.setSessionFile(opts.sessionFile);
3218
+ }
3219
+ catch (error) {
3220
+ if (created)
3221
+ await rm(opts.sessionFile, { force: true }).catch(() => undefined);
3222
+ throw error;
3223
+ }
3224
+ },
2393
3225
  createInMemorySessionManager: async (opts) => {
2394
3226
  const sdk = (await loadSdk());
2395
3227
  return sdk.SessionManager.inMemory(opts.cwd);
@@ -2406,13 +3238,19 @@ export function createDefaultPiSdkBindings() {
2406
3238
  // wrong conversation under the durable Console sessionId. Fail closed
2407
3239
  // before open when the persisted file is absent.
2408
3240
  await access(opts.sessionFile);
2409
- return sdk.SessionManager.open(opts.sessionFile);
2410
3241
  }
2411
- catch {
2412
- // Missing/corrupt session file — caller fails closed rather than
2413
- // silently creating a fresh session and losing prior context.
3242
+ catch (error) {
3243
+ const code = error && typeof error === "object" && "code" in error
3244
+ ? String(error.code ?? "")
3245
+ : "";
3246
+ if (code === "ENOENT") {
3247
+ throw Object.assign(new Error(`SESSION_FILE_MISSING: ${opts.sessionFile}`), { code: "SESSION_FILE_MISSING", cause: error });
3248
+ }
3249
+ // File exists but is unreadable (permissions / I/O) — caller maps
3250
+ // undefined to 503 rather than silently creating a fresh session.
2414
3251
  return undefined;
2415
3252
  }
3253
+ return sdk.SessionManager.open(opts.sessionFile);
2416
3254
  },
2417
3255
  resolveModel: (opts) => {
2418
3256
  const rt = opts.modelRuntime;