@agimon-ai/po-cloudflare 0.0.2-alpha.7 → 0.0.2-alpha.71

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 (355) hide show
  1. package/README.md +64 -241
  2. package/container/Dockerfile +27 -0
  3. package/dist/{BrowserWebSocketTransport-C2SC2VeJ.js → BrowserWebSocketTransport-B4heNdrp.js} +1 -1
  4. package/dist/{NodeWebSocketTransport-CKilJesa.js → NodeWebSocketTransport-BCiOXUEz.js} +2 -2
  5. package/dist/{abort-signals-Bkmp_euQ.js → abort-signals-C8CttjsR.js} +1 -1
  6. package/dist/agent-CEqvgRl6.js +3878 -0
  7. package/dist/{anthropic-messages-CkYm8M3V.js → anthropic-messages-DCLLLNuM.js} +292 -64
  8. package/dist/apiContracts-DaOpUHnu.js +1719 -0
  9. package/dist/{approval-CQ3ZuoTy.js → approval-DXPV7Vm5.js} +15 -2
  10. package/dist/{approvalPrompt-CylV3C84.js → approvalPrompt-CBaxjb_g.js} +1 -2
  11. package/dist/approvalSession-C9bg7tPo.js +132 -0
  12. package/dist/artifactFiles-5KwXIxYf.js +1 -0
  13. package/dist/artifactsApi-bg2wMYWg.js +200 -0
  14. package/dist/assets/assets/{CodeEditorView-D4q94XH-.js → CodeEditorView-CfrVwzvL.js} +2 -2
  15. package/dist/assets/assets/{abnfDiagram-WEYOIA3C-C85p4OYZ.js → abnfDiagram-WEYOIA3C-B80H4Cm4.js} +2 -2
  16. package/dist/assets/assets/{architecture-WOLXFQ4H-Bt_NOdwE.js → architecture-WOLXFQ4H-Dr4hXaql.js} +1 -1
  17. package/dist/assets/assets/{architectureDiagram-ZHVYKT53-DzH1GKMm.js → architectureDiagram-ZHVYKT53-DWyt7oXu.js} +2 -2
  18. package/dist/assets/assets/{blockDiagram-RJAE7QA3-BmWU34j3.js → blockDiagram-RJAE7QA3-OxNTLdmi.js} +2 -2
  19. package/dist/assets/assets/{c4Diagram-XDPPPE54-BpGOdOuo.js → c4Diagram-XDPPPE54-B4YtcH0s.js} +2 -2
  20. package/dist/assets/assets/channel-bXj00dGj.js +2 -0
  21. package/dist/assets/assets/{chunk-2E7WHVMD-AycP1cXU.js → chunk-2E7WHVMD-CD6FFMOX.js} +2 -2
  22. package/dist/assets/assets/{chunk-4EMNKR2T-DX-DrZzc.js → chunk-4EMNKR2T-CEIoX5oo.js} +2 -2
  23. package/dist/assets/assets/{chunk-55XCU76K-BdwnLWzI.js → chunk-55XCU76K-CD3t0IJi.js} +2 -2
  24. package/dist/assets/assets/{chunk-7S6XSTFO-D-RBAwAn.js → chunk-7S6XSTFO-Cyt75UCF.js} +2 -2
  25. package/dist/assets/assets/{chunk-AQDTSKZB-CCxNNhKs.js → chunk-AQDTSKZB-DRtqYBj9.js} +2 -2
  26. package/dist/assets/assets/{chunk-DSNLSHJZ-D2hGwWm1.js → chunk-DSNLSHJZ-C8Fx2F8s.js} +2 -2
  27. package/dist/assets/assets/{chunk-HAGFOTED-BPi-cqGh.js → chunk-HAGFOTED-wOLWRRnd.js} +2 -2
  28. package/dist/assets/assets/{chunk-HNE4Q36P-D-r1ChHT.js → chunk-HNE4Q36P-CurJg4Hf.js} +2 -2
  29. package/dist/assets/assets/{chunk-NQOKRVIF-RgmZCAdn.js → chunk-NQOKRVIF-Dzcc5nOG.js} +2 -2
  30. package/dist/assets/assets/{chunk-UHW7PFBP-B-Hul-rZ.js → chunk-UHW7PFBP-B_ULFf2h.js} +2 -2
  31. package/dist/assets/assets/{chunk-VQ5W62QI-D1zlXCt8.js → chunk-VQ5W62QI-DH0VY4_p.js} +2 -2
  32. package/dist/assets/assets/{chunk-WQQL4CDK-CtjIbVJn.js → chunk-WQQL4CDK-DNxfLyXM.js} +2 -2
  33. package/dist/assets/assets/chunk-XXDRQBXY-B2bMWgN9.js +2 -0
  34. package/dist/assets/assets/{chunk-YZO67HFG-BQOgXG99.js → chunk-YZO67HFG-COuMUh9U.js} +2 -2
  35. package/dist/assets/assets/{chunk-ZAUX2LTX-CsDDxmqv.js → chunk-ZAUX2LTX-BJrCnubF.js} +2 -2
  36. package/dist/assets/assets/{chunk-ZCHMQSOR-deyEYMjx.js → chunk-ZCHMQSOR-D1lFKPtk.js} +2 -2
  37. package/dist/assets/assets/{classDiagram-v2-4MYWR3UA-DVJHeFlq.js → classDiagram-v2-4MYWR3UA-DfZIbyVL.js} +2 -2
  38. package/dist/assets/assets/{cose-bilkent-JH36ORCC-ipcN28Fw.js → cose-bilkent-JH36ORCC-CpGhv9_S.js} +2 -2
  39. package/dist/assets/assets/{cynefin-EF2NZ3EQ-s9ZkPF55.js → cynefin-EF2NZ3EQ-Cxdc6nQl.js} +1 -1
  40. package/dist/assets/assets/{cynefinDiagram-WF24UDRP-Ksr2qjsS.js → cynefinDiagram-WF24UDRP-qoj0w3lp.js} +2 -2
  41. package/dist/assets/assets/{dagre-NK4GIZVX-2_Wl-XEW.js → dagre-NK4GIZVX-DL6QbNDS.js} +2 -2
  42. package/dist/assets/assets/{diagram-CBK3MWTC-C7PeyT7l.js → diagram-CBK3MWTC-CJB3jq1_.js} +2 -2
  43. package/dist/assets/assets/{diagram-I5XIIV2D-DPYzeKdj.js → diagram-I5XIIV2D-4cPOxCxF.js} +2 -2
  44. package/dist/assets/assets/{diagram-ODIL2UCW-DHw1cAmn.js → diagram-ODIL2UCW-BG3-jAxE.js} +2 -2
  45. package/dist/assets/assets/{diagram-PFBEJUXE-C2wA8i-1.js → diagram-PFBEJUXE-Bx8dFaXj.js} +2 -2
  46. package/dist/assets/assets/{diagram-RJA3I4VV-tM3moCIs.js → diagram-RJA3I4VV-CUUHND91.js} +2 -2
  47. package/dist/assets/assets/{diagram-TYUNFSNR-CInyJxF7.js → diagram-TYUNFSNR-BDMoN-kr.js} +2 -2
  48. package/dist/assets/assets/{dist-BDqjNLTC.js → dist-5AxNm-uy.js} +2 -2
  49. package/dist/assets/assets/{dist-hpZIQBl4.js → dist-9_Rmyj2I.js} +2 -2
  50. package/dist/assets/assets/{dist-DSLprmec.js → dist-BE3CLKv4.js} +2 -2
  51. package/dist/assets/assets/{dist-BASEd5LC.js → dist-BfNCu-7x.js} +2 -2
  52. package/dist/assets/assets/{dist-BuYBvf4F.js → dist-BjI0b36Z.js} +2 -2
  53. package/dist/assets/assets/{dist-DUS0U_ge.js → dist-CM7b5P9a.js} +2 -2
  54. package/dist/assets/assets/{dist-CeOy6PjJ.js → dist-Ccxb9U1G.js} +2 -2
  55. package/dist/assets/assets/{dist-ChXoRSS6.js → dist-CjCWP21A.js} +2 -2
  56. package/dist/assets/assets/{dist-07dRlnp1.js → dist-DSTAktnR.js} +2 -2
  57. package/dist/assets/assets/{ebnfDiagram-V4P3TTPT-4nZgqaSt.js → ebnfDiagram-V4P3TTPT-BivOMXZb.js} +2 -2
  58. package/dist/assets/assets/{elk-QONTBCTQ-nFh54c1Q.js → elk-QONTBCTQ-CrJ1Qpy_.js} +2 -2
  59. package/dist/assets/assets/{erDiagram-KYQIGQAA-CIQ0_IgZ.js → erDiagram-KYQIGQAA-w9Bqp4sV.js} +2 -2
  60. package/dist/assets/assets/{eventmodeling-K75KTNOO-Cw4BlbYP.js → eventmodeling-K75KTNOO-CBjFM3kV.js} +1 -1
  61. package/dist/assets/assets/flowDiagram-IUGLLWBU-C6Fnfgm0.js +1 -0
  62. package/dist/assets/assets/{ganttDiagram-R7GPNTJY-C97qoUpX.js → ganttDiagram-R7GPNTJY-CsWtGaqD.js} +2 -2
  63. package/dist/assets/assets/{gitGraph-VSP46ZUC-B8HWVkEX.js → gitGraph-VSP46ZUC-DsBSV9_h.js} +1 -1
  64. package/dist/assets/assets/{gitGraphDiagram-PDYL7XHY-B4Js56_8.js → gitGraphDiagram-PDYL7XHY-D5GxuYHW.js} +2 -2
  65. package/dist/assets/assets/index-CNDyKUDF.css +1 -0
  66. package/dist/assets/assets/index-DWDYnZsq.js +256 -0
  67. package/dist/assets/assets/{info-OHQRW6UA-A4qythhA.js → info-OHQRW6UA-C7x5dSJu.js} +1 -1
  68. package/dist/assets/assets/{infoDiagram-MVDRKAX5-BSNwG9yI.js → infoDiagram-MVDRKAX5-CwpI-uAa.js} +2 -2
  69. package/dist/assets/assets/{ishikawaDiagram-HPEHV2GE-D4gU-3RA.js → ishikawaDiagram-HPEHV2GE-DAa7J5G6.js} +2 -2
  70. package/dist/assets/assets/{journeyDiagram-BOSHW7O7-CxxDrw7o.js → journeyDiagram-BOSHW7O7-BmiZnxE_.js} +2 -2
  71. package/dist/assets/assets/{kanban-definition-FNSA4HC5-DUxQv3v0.js → kanban-definition-FNSA4HC5-DUR_mA3L.js} +2 -2
  72. package/dist/assets/assets/{line-BKODXUmk.js → line-DHY49wSg.js} +2 -2
  73. package/dist/assets/assets/{linear-Cm5uyUun.js → linear-pTo-a9xT.js} +2 -2
  74. package/dist/assets/assets/{mermaid-parser.core-CYst2kCg.js → mermaid-parser.core-DMg3hN3T.js} +4 -4
  75. package/dist/assets/assets/{mermaid.core-B4Qq8SMa.js → mermaid.core-DKtPCltA.js} +5 -5
  76. package/dist/assets/assets/{mindmap-definition-6OY57UG3-CZFvUTIM.js → mindmap-definition-6OY57UG3-DwTkFbnV.js} +2 -2
  77. package/dist/assets/assets/{packet-JDAUHWVQ-DZMlaiuy.js → packet-JDAUHWVQ-Tu9TrQ1x.js} +1 -1
  78. package/dist/assets/assets/{pegDiagram-ECIUJNBX-BjM668dT.js → pegDiagram-ECIUJNBX-B7My4tsz.js} +2 -2
  79. package/dist/assets/assets/{pie-XZMESJXO-CmpJ6vb8.js → pie-XZMESJXO-QPQm5Gdx.js} +1 -1
  80. package/dist/assets/assets/{pieDiagram-GNMPY74T-BCA9DCDe.js → pieDiagram-GNMPY74T-Bv-zAD_z.js} +2 -2
  81. package/dist/assets/assets/{quadrantDiagram-D57K4MC3-CUnpC-Rl.js → quadrantDiagram-D57K4MC3-HTjoGQPd.js} +2 -2
  82. package/dist/assets/assets/{radar-ABXABTNO-C9x42-KP.js → radar-ABXABTNO-LDBlEoFo.js} +1 -1
  83. package/dist/assets/assets/{railroad-I3PHUGI6-CLvHKrsC.js → railroad-I3PHUGI6-Dy3_ymgZ.js} +1 -1
  84. package/dist/assets/assets/{railroad-abnf-LNEFI6M7-B0LGF3gx.js → railroad-abnf-LNEFI6M7-QLVvYs6e.js} +1 -1
  85. package/dist/assets/assets/{railroad-ebnf-DWYD2UWJ-SKnYapAj.js → railroad-ebnf-DWYD2UWJ-CFRlv9a8.js} +1 -1
  86. package/dist/assets/assets/{railroad-peg-JR7BVNR7-wsUpPloN.js → railroad-peg-JR7BVNR7-BOlq3d9c.js} +1 -1
  87. package/dist/assets/assets/{railroadDiagram-Y72NRBL7-BYJtosKO.js → railroadDiagram-Y72NRBL7-Chg32HoU.js} +2 -2
  88. package/dist/assets/assets/{requirementDiagram-EQYSW5RA-YYdoWMnl.js → requirementDiagram-EQYSW5RA-VenIs_eg.js} +2 -2
  89. package/dist/assets/assets/{sankeyDiagram-SY24JHO5-DtZyCTdM.js → sankeyDiagram-SY24JHO5-BdByqMKF.js} +2 -2
  90. package/dist/assets/assets/{sequenceDiagram-BLEHNHQU-BPE8f413.js → sequenceDiagram-BLEHNHQU-D3Do4GJE.js} +2 -2
  91. package/dist/assets/assets/{src-BNTOLq2G.js → src-DmfN-DA-.js} +2 -2
  92. package/dist/assets/assets/{stateDiagram-v2-A6IESKWZ-9f8Ow4Fl.js → stateDiagram-v2-A6IESKWZ-CZkRbPlf.js} +2 -2
  93. package/dist/assets/assets/{swimlanes-B3ENRKFQ-DdAEbxGp.js → swimlanes-B3ENRKFQ-DRTdF9AF.js} +2 -2
  94. package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-BYr_4JUb.js +9 -0
  95. package/dist/assets/assets/{timeline-definition-JXYKGLGB-DJNGd2mU.js → timeline-definition-JXYKGLGB-BVcuws_M.js} +2 -2
  96. package/dist/assets/assets/{treeView-D4JQ5SDB-BHONoCCw.js → treeView-D4JQ5SDB-BLtOJGqO.js} +1 -1
  97. package/dist/assets/assets/{treemap-SAJKECNS-pOaYkxq7.js → treemap-SAJKECNS-Dn3BWJ4v.js} +1 -1
  98. package/dist/assets/assets/{usecaseDiagram-WPOLBNNX-C3eDYL9v.js → usecaseDiagram-WPOLBNNX-CBExIKDY.js} +2 -2
  99. package/dist/assets/assets/{vennDiagram-Q3Y3IDCW-CJi1xfsR.js → vennDiagram-Q3Y3IDCW-C6FIx2L4.js} +2 -2
  100. package/dist/assets/assets/{wardley-7MLQ67FV-CEy4w7Ir.js → wardley-7MLQ67FV-Cjj2xSBp.js} +1 -1
  101. package/dist/assets/assets/{wardleyDiagram-IVAIDKWA-DfdLMMpN.js → wardleyDiagram-IVAIDKWA-sQPCBCFK.js} +2 -2
  102. package/dist/assets/assets/{webpack-v8XGbQTa.js → webpack-DDCA0aDL.js} +2 -2
  103. package/dist/assets/assets/{xychartDiagram-4URNHDU4-Aw-Ix4uC.js → xychartDiagram-4URNHDU4-bZ4rifSw.js} +2 -2
  104. package/dist/assets/bundle-asset-policy.json +1 -1
  105. package/dist/assets/index.html +8 -2
  106. package/dist/assets/mascot/cta-provider.png +0 -0
  107. package/dist/assets/mascot/cta-sign-in.png +0 -0
  108. package/dist/assets/plugins/assets/base-GzIOAd-t.css +2 -0
  109. package/dist/assets/plugins/assets/browserCaptureWorklet-Droj0fW0-Droj0fW0.js +13 -0
  110. package/dist/assets/plugins/assets/day-bottom-left-5um-x02r-5um-x02r.webp +0 -0
  111. package/dist/assets/plugins/assets/day-grain-CvEuNhlI-CvEuNhlI.webp +0 -0
  112. package/dist/assets/plugins/assets/day-right-C9W-XtjV-C9W-XtjV.webp +0 -0
  113. package/dist/assets/plugins/assets/day-top-left-B544Eq9J-B544Eq9J.webp +0 -0
  114. package/dist/assets/plugins/assets/night-bottom-left-N03ST5Uz-N03ST5Uz.webp +0 -0
  115. package/dist/assets/plugins/assets/night-grain-BY9q-tNN-BY9q-tNN.webp +0 -0
  116. package/dist/assets/plugins/assets/night-right-C6Denrqj-C6Denrqj.webp +0 -0
  117. package/dist/assets/plugins/assets/night-top-left-KOou6UxY-KOou6UxY.webp +0 -0
  118. package/dist/assets/plugins/assets/sileroVadWorker-D894njUe-DjN_BMWf.mjs +110 -0
  119. package/dist/assets/plugins/assets/silero_vad_v6.2.1-SjbCxFXk-SjbCxFXk.onnx +0 -0
  120. package/dist/assets/plugins/chunks/po-web-runtime-D8FIos2q.js +1 -0
  121. package/dist/assets/plugins/chunks/schemas-DVQ8BvvP.js +55 -0
  122. package/dist/assets/plugins/compositions.json +1 -1
  123. package/dist/assets/plugins/slots/approval.09e72f36-DxS_uibk.js +2 -0
  124. package/dist/assets/plugins/slots/artifacts.50b639bb-Cp37TAkd.js +1 -0
  125. package/dist/assets/plugins/slots/author.ea449ace-Ds9Y-tjN.js +93 -0
  126. package/dist/assets/plugins/slots/autocompact.6f428144-CDZpN7I7.js +1 -0
  127. package/dist/assets/plugins/slots/backdrop-bamboo.6e4c928d-qbifuMc6.js +1 -0
  128. package/dist/assets/plugins/slots/browse.fa1f1a50-CVYvo1M5.js +1 -0
  129. package/dist/assets/plugins/slots/builtin-tools.75108f21-Cq1ljoL-.js +7 -0
  130. package/dist/assets/plugins/slots/calendar.d8b70190-BBjpOs1v.js +2 -0
  131. package/dist/assets/plugins/slots/codemode.c58fb583-DOR6OR7R.js +11 -0
  132. package/dist/assets/plugins/slots/domain.753f9f92-CJrXxig9.js +1 -0
  133. package/dist/assets/plugins/slots/edit.804fec90-BFF7_xN9.js +7 -0
  134. package/dist/assets/plugins/slots/files.66ffc636-CzOlZrRm.js +2 -0
  135. package/dist/assets/plugins/slots/goal.45dffa01-BtQBp3sw.js +1 -0
  136. package/dist/assets/plugins/slots/grep.98262cff-9bUDfjyT.js +1 -0
  137. package/dist/assets/plugins/slots/help.5fbd20f7-B4-y6gYK.js +3 -0
  138. package/dist/assets/plugins/slots/log.cb964209-BRPa3cVs.js +4 -0
  139. package/dist/assets/plugins/slots/mcp.82cc1ff5-CFtzPkPC.js +55 -0
  140. package/dist/assets/plugins/slots/plan.3852ba52-CH59Ff49.js +3 -0
  141. package/dist/assets/plugins/slots/profile.ab16dcec-0e9fWWyE.js +1 -0
  142. package/dist/assets/plugins/slots/prompts.ae48c07a-BTqYnBX5.js +38 -0
  143. package/dist/assets/plugins/slots/read.4560591a-C7fMXDEH.js +1 -0
  144. package/dist/assets/plugins/slots/runner.6e494d59-CqrpqhW9.js +9 -0
  145. package/dist/assets/plugins/slots/scaffold.d87a6ee0-9qY5gkYW.js +1 -0
  146. package/dist/assets/plugins/slots/session-mcp.2be84084-Cf0cqopp.js +2 -0
  147. package/dist/assets/plugins/slots/sessions.6f47cb4c-B1_eqPJQ.js +1 -0
  148. package/dist/assets/plugins/slots/skill.62a0a1b3-D-SKX8iw.js +4 -0
  149. package/dist/assets/plugins/slots/space.65a27e5a-fbLHc-DX.js +1 -0
  150. package/dist/assets/plugins/slots/subagents.8bb9992c-Cm_YMEnn.js +7 -0
  151. package/dist/assets/plugins/slots/template-advanced.59f3f98a-L0WOM4JT.js +1 -0
  152. package/dist/assets/plugins/slots/template-desktop.0f0b8491-By9BZlaL.js +7 -0
  153. package/dist/assets/plugins/slots/template-elegant.0e3b0acf-El05x7HK.js +1 -0
  154. package/dist/assets/plugins/slots/vault.3cbfcdc3-DpU_65Wy.js +1 -0
  155. package/dist/assets/plugins/slots/voice.a952113d-CvcuL__m.js +1 -0
  156. package/dist/assets/plugins/slots/web-search.65013836-NVh9fdvE.js +1 -0
  157. package/dist/assets/plugins/slots/workflows.cbc5c5c0-OLKSY9PE.js +16 -0
  158. package/dist/assets/pwa/pwa.js +12 -12
  159. package/dist/assets/pwa/sw.js +58 -4
  160. package/dist/{atomicJson-wczZBXQP.js → atomicJson-XYtxz032.js} +2 -3
  161. package/dist/{azure-openai-config-DHMgdIa-.js → azure-openai-config-S-quxzTC.js} +2 -2
  162. package/dist/{azure-openai-responses-CTgRdQ4m.js → azure-openai-responses-DdpV5zh7.js} +13 -13
  163. package/dist/backgroundWork-Bv0ib_lY.js +49 -0
  164. package/dist/{layeredConfig-xmTHGrw8.js → browser-DwY5dXHX.js} +21 -983
  165. package/dist/{browser-EJ5_ffnN.js → browser-IsHIcvFg.js} +1 -1
  166. package/dist/browser-ks_k-6KA.js +36 -0
  167. package/dist/calendarSetup-CI3AACVo.js +3892 -0
  168. package/dist/childProcess-Cv8rJuUf.js +32 -0
  169. package/dist/childSession-BrDCrNtL.js +25 -0
  170. package/dist/{classifier-shared-jXm-plIK.js → classifier-shared-DFprgrML.js} +5 -5
  171. package/dist/{cloudflare-workers-ai-system-one-B0wH6HU5.js → cloudflare-workers-ai-system-one-B0MD19yZ.js} +3 -3
  172. package/dist/{codemode-CFVDmyGm.js → codemode-LpcMFMYM.js} +1 -1
  173. package/dist/coerce-DM9YrILC.js +13 -0
  174. package/dist/config-DeWkdjj7.js +1372 -0
  175. package/dist/contextContributions-C1bsEJef.js +13 -0
  176. package/dist/contracts-CW8o6Xyi.js +19 -0
  177. package/dist/contracts-WRa9e98H.js +40 -0
  178. package/dist/cordisHost-_-jtkneB.js +25 -0
  179. package/dist/delegation-B2rBgv8A.js +100 -0
  180. package/dist/{diagnostics-DPTP-yrt.js → diagnostics-BY5LXbHJ.js} +2 -2
  181. package/dist/{dist-BVBi6VMV.js → dist-B2ArMqge.js} +1 -1
  182. package/dist/{server-Cg07O2W6.js → dist-C6IqjC-m.js} +1 -546
  183. package/dist/{dist-PDDFdqDX.js → dist-CDz5dYMj.js} +1 -1
  184. package/dist/{dist-Dvx5mlIR.js → dist-kgi2Ix1y.js} +16 -3
  185. package/dist/{emscripten-module.cloudflare-D4Bc9Ykz.js → emscripten-module.cloudflare-B4fhfquU.js} +1 -1
  186. package/dist/{env-api-keys-CAnjjnsR.js → env-api-keys-BgCPpU9t.js} +1 -1
  187. package/dist/{error-body-DQZRsyL5.js → error-body-CeumezyR.js} +26 -4
  188. package/dist/esm-BKJy3O9-.js +1553 -0
  189. package/dist/{remoteMcp-DqE2xFWS.js → exports-BEEgtkya.js} +1588 -714
  190. package/dist/{exports-LjvSY7Y6.js → exports-CBp_9dVk.js} +47 -28
  191. package/dist/exports-CRjRvvX0.js +34 -0
  192. package/dist/exports-Cg0wxflf.js +1 -0
  193. package/dist/exports-Ct56PRB9.js +46 -0
  194. package/dist/extensionFile-B940JOEn.js +121 -0
  195. package/dist/{factory-Cs8iaUtc.js → factory-BU0cZY0I.js} +1 -1
  196. package/dist/{github-copilot-headers-DpQQAh-s.js → github-copilot-headers-Cq9pnpl2.js} +1 -1
  197. package/dist/{google-generative-ai-BTTOo5RQ.js → google-generative-ai-DmbUlCGv.js} +9 -9
  198. package/dist/{google-shared-S7bqOccz.js → google-shared-Diz2uk39.js} +6 -6
  199. package/dist/{google-vertex-BcMU_DMb.js → google-vertex-CGCpI9Po.js} +10 -10
  200. package/dist/{domains-B6Ae4swm.js → harnessState-Df--jB5z.js} +162 -42
  201. package/dist/{harnessStore-Ccbia9_u.js → harnessStore-DInwiLYb.js} +4 -5
  202. package/dist/{hash-B3RRpLS2.js → hash-IQBoLxOB.js} +1 -1
  203. package/dist/{headers-BEuxFxDI.js → headers-Dkgiqogr.js} +1 -1
  204. package/dist/help-C9UGKetC.js +100 -0
  205. package/dist/home-kwZFHqOx.js +60 -0
  206. package/dist/http-BekstF5S.js +64 -0
  207. package/dist/hubChannel-Dldv3EEb.js +32 -0
  208. package/dist/hubRevisions-BPoC6quI.js +364 -0
  209. package/dist/{identity-BIeAyilV.js → identity-BzB1N-Sn.js} +3 -3
  210. package/dist/index.edge-BiVQ9LoZ.js +198 -0
  211. package/dist/index.edge-CSGx6QOL.js +56 -0
  212. package/dist/index.edge-ClLTmPFz.js +191 -0
  213. package/dist/index.edge-CzoLWbyl.js +238 -0
  214. package/dist/index.edge-D1biKw71.js +946 -0
  215. package/dist/index.edge-D2RirEwK.js +14 -0
  216. package/dist/iso-BGFmgtky.js +27 -0
  217. package/dist/{kysely-adapter-D51abb3q.js → kysely-adapter-D8KUrWxm.js} +1 -1
  218. package/dist/liquid.browser-1BcykmIN.js +4596 -0
  219. package/dist/manualTranscription-DN56fzgj.js +96 -0
  220. package/dist/{mcpProjection-BXiECnW0.js → mcpProjection-D2U50Pel.js} +1 -2
  221. package/dist/meta-CVgfTHQP.js +1030 -0
  222. package/dist/migrations-DJBPDwSR.js +32 -0
  223. package/dist/{mistral-conversations-DN8VSERk.js → mistral-conversations-Bv_m1MRF.js} +12 -12
  224. package/dist/modeDefinition-Di95_IiU.js +44 -0
  225. package/dist/{models-D6d73jcW.js → models-D50yN8Ag.js} +41 -46
  226. package/dist/{node-UuMT2C3q.js → node-B4kSjHeD.js} +2 -2
  227. package/dist/{node-DytJOfYf.js → node-CBLSc-YH.js} +1 -1
  228. package/dist/notification-DjxbNoMR.js +143 -0
  229. package/dist/{openai-bt3ZRBZv.js → openai-D6Q-l6hT.js} +187 -187
  230. package/dist/{openai-codex-responses-cL36x0ml.js → openai-codex-responses-BnoiTqYV.js} +21 -25
  231. package/dist/{openai-completions-BWsTNYyT.js → openai-completions-C68qs5rI.js} +26 -19
  232. package/dist/{openai-decisions-Dfn_KgQd.js → openai-decisions-BSxU_aoV.js} +3 -3
  233. package/dist/{openai-responses-aa0LoyCJ.js → openai-responses-D6hXen-k.js} +17 -15
  234. package/dist/{openai-responses-shared-H-jH5SlM.js → openai-responses-shared-BD8K7FAC.js} +7 -7
  235. package/dist/{openrouter-cost-D99Qqcs6.js → openrouter-cost-BPam8wyW.js} +1 -1
  236. package/dist/{openrouter-images-BpwVpALC.js → openrouter-images-DylXiHy7.js} +7 -7
  237. package/dist/{hubChannel-Dn5NMpvu.js → packageApi-DYkaxP59.js} +33 -42
  238. package/dist/photon_rs_bg.wasm +0 -0
  239. package/dist/{pi-messages-BHAIkYBj.js → pi-messages-DaIlYYlO.js} +6 -6
  240. package/dist/piConfig-5tRPD0ov.js +126 -0
  241. package/dist/piSettings-ekBG5OeF.js +1 -0
  242. package/dist/platform-CQahdzpG.js +138 -0
  243. package/dist/pluginCatalog-BAALyedS.js +30 -0
  244. package/dist/pluginContributions-Be9EnCAW.js +16 -0
  245. package/dist/pluginProtocol-7_gVUeM9.js +1 -0
  246. package/dist/pluginProtocol-DVIfJnav.js +135 -0
  247. package/dist/portableConfig-0tnk9anb.js +49 -0
  248. package/dist/presetConfig-n-oiNd3h.js +541 -0
  249. package/dist/profileSources-D1rymC97.js +537 -0
  250. package/dist/{protocol-DUeE0Q8z.js → protocol-Cri0GpZR.js} +1 -2
  251. package/dist/{provider-env-DgfpjgTa.js → provider-env-DJb40UF7.js} +2 -2
  252. package/dist/{provider-retry-ChD-K2Gv.js → provider-retry-jpvs7ixx.js} +1 -1
  253. package/dist/{puppeteer-cloudflare-B-GHrPGO.js → puppeteer-cloudflare-D4l8smMS.js} +3 -3
  254. package/dist/{server-BWJmxCrm.js → readiness-Ydw5zrKy.js} +4 -169
  255. package/dist/{rolldown-runtime-B-lAHAz2.js → rolldown-runtime-DbVrKiKs.js} +1 -1
  256. package/dist/{sanitize-unicode-Dl4ROF7y.js → sanitize-unicode-B1ZFaEtf.js} +1 -1
  257. package/dist/scaffoldRegistry-CeFe3Pf0.js +1240 -0
  258. package/dist/{schemas-Vj8-rCR4.js → schemas-D2dRon18.js} +1901 -53
  259. package/dist/server-AKM07WcM.js +466 -0
  260. package/dist/server-B0tM5Ygf.js +1300 -0
  261. package/dist/server-B8-vStCx.js +1116 -0
  262. package/dist/server-BAbdiL38.js +15108 -0
  263. package/dist/server-BCZ_R3kX.js +3326 -0
  264. package/dist/server-BGKAeB3M.js +492 -0
  265. package/dist/server-BIQhg1jS.js +26985 -0
  266. package/dist/server-BcPD_6a2.js +1533 -0
  267. package/dist/server-BeoA0QB-.js +580 -0
  268. package/dist/server-BsgvOpBF.js +24 -0
  269. package/dist/server-BtnOqSB5.js +156 -0
  270. package/dist/server-C-HBjWRo.js +2800 -0
  271. package/dist/{server-CWg0m_wq.js → server-C0Lt6nTt.js} +269 -1062
  272. package/dist/server-C8NPfG1H.js +148 -0
  273. package/dist/server-CKkaxOc0.js +978 -0
  274. package/dist/server-CMaWF5UA.js +1379 -0
  275. package/dist/server-CQPI6jIa.js +295 -0
  276. package/dist/{server-BhYE7Vqk.js → server-CQmb0lYL.js} +114 -176
  277. package/dist/server-CWR34Vx6.js +1884 -0
  278. package/dist/server-CZiAy2v5.js +641 -0
  279. package/dist/server-Cjtr0oVJ.js +584 -0
  280. package/dist/server-CkJQJ3Oo.js +571 -0
  281. package/dist/server-ClQQGtsI.js +679 -0
  282. package/dist/server-Cy2FhGBm.js +1744 -0
  283. package/dist/server-D8yEblCB.js +24 -0
  284. package/dist/server-DF0YIUeI.js +9603 -0
  285. package/dist/server-DRFESCq1.js +1527 -0
  286. package/dist/{server-zkcrP99W.js → server-Df1defzp.js} +89 -87
  287. package/dist/server-DgZd_TuT.js +189 -0
  288. package/dist/server-Dkc9Kth2.js +1830 -0
  289. package/dist/server-DlRePYOB.js +343 -0
  290. package/dist/{server-BpPEzRes.js → server-_HZm8wEC.js} +654 -745
  291. package/dist/{server-yABhJa2K.js → server-_jWkMESg.js} +60 -39
  292. package/dist/server-lgV6liTt.js +140 -0
  293. package/dist/server-nHPXbRDA.js +742 -0
  294. package/dist/server-p7qANgrf.js +877 -0
  295. package/dist/server-vhmQi3co.js +112 -0
  296. package/dist/{server-SA0dsIJ2.js → server-w1aKMZOs.js} +3 -10
  297. package/dist/serverPlugin-4nI5J6Zt.js +39622 -0
  298. package/dist/session-resources-BvR3cwiH.js +10 -0
  299. package/dist/{sessionConfig-DgnPcGBu.js → sessionConfig-UMlgu98q.js} +926 -844
  300. package/dist/{simple-options-DWrW31_K.js → simple-options-Cp5p46f9.js} +13 -6
  301. package/dist/space-C3Wnli1l.js +92 -0
  302. package/dist/sse-XlzXs1es.js +151 -0
  303. package/dist/{streaming-json-t4rzNHEp.js → streaming-json-CZyrX_Ux.js} +6 -6
  304. package/dist/{system-one-shared-DLVLdzYL.js → system-one-shared-Du6bka0h.js} +3 -3
  305. package/dist/{notification-valMY1zH.js → telemetry-CrTcxeA5.js} +2 -93
  306. package/dist/{transform-messages-CjTSwW9q.js → transform-messages-CBj9g2mx.js} +3 -16
  307. package/dist/truncate-M3KbFyVj.js +89 -0
  308. package/dist/{server-BXjfQYeU.js → type-DppaYz6F.js} +955 -1187
  309. package/dist/type-yokaDI_F.js +7 -0
  310. package/dist/{typesafe-system-one-DBVcjcUQ.js → typesafe-system-one-C7YFgvrX.js} +3 -3
  311. package/dist/{uuid-mkNGilLv.js → uuid-BVI0BZsx.js} +1 -1
  312. package/dist/{validation-BLnxgJU_.js → validation-QWuk6kwJ.js} +79 -74
  313. package/dist/vaultSettings-Bq8wkbDv.js +292 -0
  314. package/dist/voiceTools-BdJyfzwB.js +246 -0
  315. package/dist/web-B2sdV-F2.js +4 -0
  316. package/dist/worker.js +97821 -72579
  317. package/dist/workflow-DTCt4n6k.js +171 -0
  318. package/dist/workflowServices-RlswfHWp.js +300 -0
  319. package/package.json +55 -25
  320. package/wrangler.jsonc +16 -3
  321. package/dist/apiContracts-sG5b90Qa.js +0 -4451
  322. package/dist/assets/assets/channel-BOT7In0s.js +0 -2
  323. package/dist/assets/assets/chunk-XXDRQBXY-Dp9-QbR6.js +0 -2
  324. package/dist/assets/assets/flowDiagram-IUGLLWBU-B9D9uWwn.js +0 -1
  325. package/dist/assets/assets/index-BlPEYpuN.css +0 -1
  326. package/dist/assets/assets/index-DS9w_Q1B.js +0 -155
  327. package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-CyUKtW7v.js +0 -9
  328. package/dist/assets/plugins/assets/base-DyDpY0zD.css +0 -2
  329. package/dist/assets/plugins/chunks/po-web-runtime-4JiBsb_c.js +0 -1
  330. package/dist/assets/plugins/slots/approval.09e72f36-DwFz-UMh.js +0 -2
  331. package/dist/assets/plugins/slots/artifacts.50b639bb-CUtFC806.js +0 -1
  332. package/dist/assets/plugins/slots/builtin-tools.75108f21-B69GLfY_.js +0 -7
  333. package/dist/assets/plugins/slots/codemode.c58fb583-C0Gmb7_s.js +0 -9
  334. package/dist/assets/plugins/slots/domain.753f9f92-BTBYRLkE.js +0 -1
  335. package/dist/assets/plugins/slots/mcp.82cc1ff5-Ecacjn0a.js +0 -109
  336. package/dist/assets/plugins/slots/profile.ab16dcec-DIVXNHmh.js +0 -1
  337. package/dist/assets/plugins/slots/skill.62a0a1b3-BNr7DmPH.js +0 -4
  338. package/dist/backgroundWork-CSpsJ-Rg.js +0 -25
  339. package/dist/contextProjection-DDIQRgN4.js +0 -188
  340. package/dist/extensionFile-CacKVegY.js +0 -409
  341. package/dist/harnessState-gmzJcPGt.js +0 -88
  342. package/dist/harnessStore-Ch6hdYYe.js +0 -1
  343. package/dist/index.edge-BgSx_gRO.js +0 -45
  344. package/dist/majorModes-CCnwAjfF.js +0 -333
  345. package/dist/majorModes-DNQbxkpt.js +0 -1
  346. package/dist/piSettings-B6fsgIBA.js +0 -1
  347. package/dist/platform-Bs2_X_dK.js +0 -16
  348. package/dist/platformFiles-CCGujP9o.js +0 -39
  349. package/dist/server-5hLs7M43.js +0 -656
  350. package/dist/server-B3iqBHOP.js +0 -118
  351. package/dist/server-Dv0EKLwc.js +0 -108
  352. package/dist/server-Y5A21sJf.js +0 -591
  353. package/dist/server-a1K226XK.js +0 -279
  354. package/dist/serverPlugin-DUc4gGep.js +0 -7279
  355. package/dist/value-Bd477RDX.js +0 -2247
@@ -0,0 +1,1533 @@
1
+ import { Et as composeServerProviderOverrides, Ht as PO_CONFIG_SERVICE, t as defineServerPlugin } from "./serverPlugin-4nI5J6Zt.js";
2
+ import { n as DEFAULT_COMPACTION_POLICY } from "./agent-CEqvgRl6.js";
3
+ import { a as openArtifact, c as writeArtifactText, h as COMPACTION_ARTIFACT_DIRECTORY, l as ArtifactAccessError, o as readArtifactBytes, r as listArtifacts, s as removeArtifact, u as artifactRoot } from "./index.edge-CzoLWbyl.js";
4
+ import "./artifactFiles-5KwXIxYf.js";
5
+ import { a as defineHook, c as defineRoot, n as composeRootInjects, t as composeRootHooks } from "./extensionFile-B940JOEn.js";
6
+ import { f as loadPoConfig } from "./sessionConfig-UMlgu98q.js";
7
+ import "./exports-CBp_9dVk.js";
8
+ import { r as requirePoContextContributions, t as PO_CONTEXT_CONTRIBUTIONS_SERVICE } from "./contextContributions-C1bsEJef.js";
9
+ import { t as createPoTelemetry } from "./index.edge-D2RirEwK.js";
10
+ import { t as minimatch } from "./esm-BKJy3O9-.js";
11
+ //#region ../../default/po-autocompact/src/services/admittedModes/index.edge.ts
12
+ /**
13
+ * An edge host has no config files for autocompact to read, so its settings come from the snapshot the host
14
+ * admitted as `po/config`. Each call reads the service's current snapshot, because a settings save replaces it,
15
+ * and throws while the host has admitted none or after its provider unloads.
16
+ */
17
+ function admittedModes(context) {
18
+ let settings;
19
+ context.inject([PO_CONFIG_SERVICE], (scoped) => {
20
+ const config = scoped.get(PO_CONFIG_SERVICE);
21
+ settings = config ? () => config.getSnapshot().settings : void 0;
22
+ return () => {
23
+ settings = void 0;
24
+ };
25
+ });
26
+ return () => {
27
+ if (!settings) throw new Error("Autocompact requires injected session configuration.");
28
+ return settings().modes;
29
+ };
30
+ }
31
+ //#endregion
32
+ //#region ../../default/po-autocompact/src/services/autocompactTelemetry/index.ts
33
+ const SERVICE_NAME = "po-autocompact";
34
+ const PACKAGE_NAME = "@agimon-ai/po-autocompact";
35
+ const AUTOCOMPACT_EVENT = {
36
+ checkpointStarted: "po_autocompact.checkpoint_started",
37
+ checkpointCompleted: "po_autocompact.checkpoint_completed",
38
+ checkpointFailed: "po_autocompact.checkpoint_failed",
39
+ checkpointInvalid: "po_autocompact.checkpoint_invalid",
40
+ configurationLoadFailed: "po_autocompact.configuration_load_failed",
41
+ contextContributionDegraded: "po_autocompact.context_contribution_degraded",
42
+ contextCommitted: "po_autocompact.context_committed",
43
+ contextApplied: "po_autocompact.context_applied",
44
+ contextMarkerInvalid: "po_autocompact.context_marker_invalid",
45
+ contextHookSlow: "po_autocompact.context_hook_slow",
46
+ nativeCompactionCompleted: "po_autocompact.native_compaction_completed",
47
+ historyWriteFailed: "po_autocompact.history_write_failed"
48
+ };
49
+ function createAutocompactTelemetry(options = {}) {
50
+ const telemetry = createPoTelemetry({
51
+ serviceName: SERVICE_NAME,
52
+ packageName: PACKAGE_NAME,
53
+ cwd: options.cwd,
54
+ workspaceRoot: options.workspaceRoot,
55
+ env: options.env,
56
+ telemetryFactory: options.telemetryFactory,
57
+ warn: options.warn,
58
+ enableLogs: true,
59
+ enableTraces: true
60
+ });
61
+ return {
62
+ recordError: (event, error, attributes, errorOptions) => telemetry.recordError(event, error, attributes, errorOptions),
63
+ recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),
64
+ recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),
65
+ runInSpan: (name, attributes, callback) => telemetry.runInSpan(name, attributes, callback),
66
+ flush: () => telemetry.flush(),
67
+ shutdown: () => telemetry.shutdown()
68
+ };
69
+ }
70
+ //#endregion
71
+ //#region ../../core/po-core/src/schemas/uiHub.ts
72
+ /** The application-scoped UI aggregation service owned by po-ui. */
73
+ const PO_UI_HUB_SERVICE = "po/ui-hub";
74
+ function readPoUiHub(context) {
75
+ return context.get(PO_UI_HUB_SERVICE);
76
+ }
77
+ function requirePoUiHub(context) {
78
+ const hub = readPoUiHub(context);
79
+ if (!hub) throw new Error("Po UI hub is unavailable. Load @agimon-ai/po-ui.");
80
+ return hub;
81
+ }
82
+ //#endregion
83
+ //#region ../../default/po-autocompact/src/constants/autocompact.ts
84
+ const STATE_CUSTOM_TYPE = "po-autocompact-state";
85
+ const CHECKPOINT_MESSAGE_TYPE = "po-autocompact-checkpoint";
86
+ const CONTEXT_MESSAGE_TYPE = "po-autocompact-context";
87
+ const RESUME_MESSAGE_TYPE = "po-autocompact-resume";
88
+ const RUNTIME_STATE_MESSAGE_TYPE = "po-autocompact-runtime-state";
89
+ const COMPACTION_THRESHOLDS = {
90
+ 1: {
91
+ ratio: .5,
92
+ capTokens: 2e5
93
+ },
94
+ 2: {
95
+ ratio: .75,
96
+ capTokens: 5e5
97
+ },
98
+ 3: {
99
+ ratio: .95,
100
+ capTokens: 8e5
101
+ }
102
+ };
103
+ const CHECKPOINT_HEADINGS = [
104
+ "## Goal",
105
+ "## Constraints & Preferences",
106
+ "## Progress",
107
+ "### Done",
108
+ "### In Progress",
109
+ "### Blocked",
110
+ "## Key Decisions",
111
+ "## Next Steps",
112
+ "## Critical Context"
113
+ ];
114
+ //#endregion
115
+ //#region ../../default/po-autocompact/src/constants/runtime.ts
116
+ const PLAN_DOCUMENT_ENTRY = "agent-harness-plan-document";
117
+ const FOOTER_SOURCE = "po-autocompact";
118
+ const STATUS_KEY = "po-autocompact";
119
+ //#endregion
120
+ //#region ../../default/po-autocompact/src/services/autocompactRuntime/index.ts
121
+ function errorMessage(error) {
122
+ return error instanceof Error ? error.message : String(error);
123
+ }
124
+ function latestPlanSnapshot(branch) {
125
+ for (const entry of branch.toReversed()) {
126
+ if (entry.type !== "custom" || entry.customType !== "agent-harness-plan-document") continue;
127
+ if (!entry.data || typeof entry.data !== "object") return void 0;
128
+ const data = entry.data;
129
+ if (typeof data.content !== "string" || typeof data.path !== "string") return void 0;
130
+ return {
131
+ content: data.content,
132
+ path: data.path
133
+ };
134
+ }
135
+ }
136
+ const EMPTY_CONTEXT_CONTRIBUTIONS = Object.freeze({
137
+ entries: Object.freeze([]),
138
+ errors: Object.freeze([])
139
+ });
140
+ function readContextContributionsSnapshot(service) {
141
+ if (!service) return EMPTY_CONTEXT_CONTRIBUTIONS;
142
+ try {
143
+ return service.snapshot();
144
+ } catch (error) {
145
+ return {
146
+ entries: [],
147
+ errors: [{
148
+ source: PO_CONTEXT_CONTRIBUTIONS_SERVICE,
149
+ id: "service-snapshot",
150
+ label: "Context contributions",
151
+ order: 0,
152
+ message: errorMessage(error)
153
+ }]
154
+ };
155
+ }
156
+ }
157
+ function formatContextContributions(snapshot) {
158
+ const sections = snapshot.entries.map((entry) => `### ${entry.label}\n${entry.text}`);
159
+ sections.push(...snapshot.errors.map((error) => `### ${error.label}\n(unavailable: ${error.message})`));
160
+ return sections.length > 0 ? sections.join("\n\n") : "(no registered context contributions)";
161
+ }
162
+ function runtimeStateSnapshot(branch, contextContributions) {
163
+ const plan = latestPlanSnapshot(branch);
164
+ return {
165
+ ...plan ? { planPath: plan.path } : {},
166
+ contributions: contextContributions.entries,
167
+ contributionErrors: contextContributions.errors
168
+ };
169
+ }
170
+ function formatRuntimeState(snapshot) {
171
+ return `<compaction-runtime-state>
172
+ Authoritative runtime state captured when compaction committed. Use it to resume coordination without reconstructing state from the summary.
173
+ <active-plan>
174
+ ${snapshot.planPath ? `Source: ${snapshot.planPath}\nExact plan content is restored separately by Po Plan.` : "(no active plan document)"}
175
+ </active-plan>
176
+ <context-contributions>
177
+ ${formatContextContributions({
178
+ entries: snapshot.contributions,
179
+ errors: snapshot.contributionErrors
180
+ })}
181
+ </context-contributions>
182
+ </compaction-runtime-state>`;
183
+ }
184
+ function steeringEnvelope(snapshot) {
185
+ const plan = snapshot.plan ? `Source: ${snapshot.plan.path}\n\n${snapshot.plan.content}` : "(no active plan document)";
186
+ const importantContext = [snapshot.readFiles.length > 0 ? `Read files: ${snapshot.readFiles.join(", ")}` : void 0, snapshot.modifiedFiles.length > 0 ? `Modified files: ${snapshot.modifiedFiles.join(", ")}` : void 0].filter((value) => Boolean(value));
187
+ return `<compaction-steering priority="user,plan,context-contributions,important-context,recent-messages">
188
+ <user-prompt source="conversation">
189
+ Treat the user's explicit goals, constraints, corrections, and preferences in the conversation as authoritative. Newer user instructions override older ones.
190
+ </user-prompt>
191
+ <active-plan>
192
+ ${plan}
193
+ </active-plan>
194
+ <context-contributions>
195
+ ${formatContextContributions(snapshot.contextContributions)}
196
+ </context-contributions>
197
+ <important-context>
198
+ ${importantContext.length > 0 ? importantContext.join("\n") : "(none recorded outside the conversation)"}
199
+ </important-context>
200
+ </compaction-steering>`;
201
+ }
202
+ function checkpointInstructions(pass, steering) {
203
+ const decision = pass === 2 ? "Start with exactly <shouldCompact>true</shouldCompact> or <shouldCompact>false</shouldCompact>. Use true when the staged summary safely retains the important parent context. Use false only when it is not yet sufficient for safe compaction.\n\n" : "";
204
+ return `Create Po autocompact checkpoint pass ${pass}.
205
+
206
+ ${steeringEnvelope(steering)}
207
+
208
+ Apply the steering evidence in priority order. Do not invent plan or contributed runtime state. Preserve verified facts and mark unresolved inference explicitly. Newer evidence replaces superseded information.
209
+
210
+ ${decision}Return only the decision tag when required, followed by a concise structured checkpoint using every heading below. Keep exact goals, constraints, decisions, blockers, commands, errors, file paths, validation evidence, and the immediate next action. Separate verified facts from unresolved inference.
211
+
212
+ ## Goal
213
+ ## Constraints & Preferences
214
+ ## Progress
215
+ ### Done
216
+ ### In Progress
217
+ ### Blocked
218
+ ## Key Decisions
219
+ ## Next Steps
220
+ ## Critical Context`;
221
+ }
222
+ const DEFAULT_RUNTIME_CONFIG = {
223
+ enabled: true,
224
+ ratios: {},
225
+ overrides: []
226
+ };
227
+ /** While admitted settings cannot be read a disable could be hidden, so autocompact stands down for the host. */
228
+ const UNAVAILABLE_RUNTIME_CONFIG = {
229
+ enabled: false,
230
+ ratios: {},
231
+ overrides: []
232
+ };
233
+ /**
234
+ * What the Po config says about this package.
235
+ *
236
+ * `modes.autocompact` is read first and `modes.planning.subagents` is the
237
+ * fallback, because summarization borrowed the planning subagent model before
238
+ * it had keys of its own and existing files still spell it that way.
239
+ *
240
+ * A host that admits its configuration passes `admitted`, and that is read instead of the files. Reading it
241
+ * failing is reported and stands autocompact down, where unreadable files keep the session model and stay on.
242
+ */
243
+ function autocompactRuntimeConfig(root, onLoadFailure, admitted) {
244
+ let modes;
245
+ try {
246
+ modes = admitted ? admitted() : loadPoConfig(root).modes;
247
+ } catch (error) {
248
+ if (admitted) {
249
+ onLoadFailure?.(error);
250
+ return UNAVAILABLE_RUNTIME_CONFIG;
251
+ }
252
+ process.emitWarning("Po autocompact configuration could not be loaded; using the active session model instead.");
253
+ onLoadFailure?.(error);
254
+ return DEFAULT_RUNTIME_CONFIG;
255
+ }
256
+ const configured = modes?.autocompact;
257
+ const agent = (configured && (configured.model !== void 0 || configured.thinking !== void 0) ? {
258
+ ...configured.model ? { model: configured.model } : {},
259
+ ...configured.thinking ? { thinking: configured.thinking } : {}
260
+ } : void 0) ?? modes?.planning?.subagents;
261
+ const thresholds = configured?.thresholds;
262
+ return {
263
+ enabled: configured?.enabled ?? true,
264
+ ...agent ? { agent } : {},
265
+ ratios: {
266
+ ...thresholds?.pass1 === void 0 ? {} : { 1: thresholds.pass1 },
267
+ ...thresholds?.pass2 === void 0 ? {} : { 2: thresholds.pass2 },
268
+ ...thresholds?.pass3 === void 0 ? {} : { 3: thresholds.pass3 }
269
+ },
270
+ overrides: configured?.overrides ?? []
271
+ };
272
+ }
273
+ //#endregion
274
+ //#region ../../default/po-autocompact/src/services/compactionPolicy/index.ts
275
+ function customMessage(entry) {
276
+ if (entry.type === "custom_message") return entry;
277
+ if (entry.type === "message" && entry.message.role === "custom") return entry.message;
278
+ }
279
+ const SHOULD_COMPACT_PATTERN = /<shouldCompact>\s*(true|false)\s*<\/shouldCompact>/i;
280
+ const FILE_SECTION_PATTERN = /\n*<(?:read-files|modified-files)>[\s\S]*?<\/(?:read-files|modified-files)>/g;
281
+ function isRecord(value) {
282
+ return typeof value === "object" && value !== null;
283
+ }
284
+ function isStringArray(value) {
285
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
286
+ }
287
+ function isPass(value) {
288
+ return value === 1 || value === 2 || value === 3;
289
+ }
290
+ function assistantText(entry) {
291
+ if (entry.type !== "message" || entry.message.role !== "assistant") return void 0;
292
+ return entry.message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n").trim() || void 0;
293
+ }
294
+ function isAutocompactMessage(value) {
295
+ return isRecord(value) && typeof value.role === "string";
296
+ }
297
+ function contextDetailsFromUnknown(value) {
298
+ if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return void 0;
299
+ if (!Array.isArray(value.retainedMessages) || !value.retainedMessages.every(isAutocompactMessage)) return void 0;
300
+ if (!isRecord(value.poAutocompact)) return void 0;
301
+ const marker = value.poAutocompact;
302
+ if (marker.version !== 2 || marker.pass !== 2 && marker.pass !== 3 || typeof marker.cycle !== "number" || typeof marker.requestId !== "string" || typeof marker.snapshotLeafId !== "string" || typeof marker.tokensBefore !== "number") return void 0;
303
+ return {
304
+ readFiles: [...value.readFiles],
305
+ modifiedFiles: [...value.modifiedFiles],
306
+ retainedMessages: [...value.retainedMessages],
307
+ poAutocompact: {
308
+ version: 2,
309
+ cycle: marker.cycle,
310
+ pass: marker.pass,
311
+ requestId: marker.requestId,
312
+ snapshotLeafId: marker.snapshotLeafId,
313
+ tokensBefore: marker.tokensBefore
314
+ }
315
+ };
316
+ }
317
+ function createInitialState() {
318
+ return {
319
+ version: 2,
320
+ cycle: 1,
321
+ pass: 1,
322
+ phase: "waiting",
323
+ checkpointQueue: [],
324
+ exhaustedPasses: [],
325
+ invalidAttempts: 0,
326
+ baselineTokens: 0,
327
+ baselinePending: false,
328
+ readFiles: [],
329
+ modifiedFiles: []
330
+ };
331
+ }
332
+ /**
333
+ * The ratios each pass fires at, with configured values folded in.
334
+ *
335
+ * The ladder only works if it climbs, so a configured pass never sits below the
336
+ * one before it: a file that says pass 2 fires earlier than pass 1 gets pass 1's
337
+ * ratio for pass 2 rather than a pass that can never contribute.
338
+ */
339
+ function compactionRatios(configured = {}) {
340
+ let previous = 0;
341
+ const ratios = {};
342
+ for (const pass of [
343
+ 1,
344
+ 2,
345
+ 3
346
+ ]) {
347
+ const ratio = Math.max(configured[pass] ?? COMPACTION_THRESHOLDS[pass].ratio, previous);
348
+ ratios[pass] = ratio;
349
+ previous = ratio;
350
+ }
351
+ return ratios;
352
+ }
353
+ function thresholdTokens(pass, contextWindow, baselineTokens = 0, configured = {}) {
354
+ const threshold = COMPACTION_THRESHOLDS[pass];
355
+ const ratio = compactionRatios(configured)[pass];
356
+ const baseline = Math.max(0, Math.min(baselineTokens, contextWindow));
357
+ const remaining = contextWindow - baseline;
358
+ const staged = baseline + Math.min(Math.floor(remaining * ratio), threshold.capTokens);
359
+ const nativeTrigger = contextWindow - DEFAULT_COMPACTION_POLICY.reserveTokens;
360
+ return nativeTrigger > baseline ? Math.min(staged, nativeTrigger) : staged;
361
+ }
362
+ /**
363
+ * Where every pass fires, with a matching model's absolute token checkpoints folded in.
364
+ *
365
+ * A configured token count replaces the ratio only when it fires earlier, so an
366
+ * override can bring a checkpoint forward on a very large window without ever
367
+ * pushing one past the point Pi compacts natively.
368
+ *
369
+ * Two rules keep the ladder usable. A token count at or below the baseline is
370
+ * ignored, because a compaction that lands above it would otherwise satisfy that
371
+ * pass the moment the next cycle opens and re-fire it every turn. And a pass never
372
+ * sits below the one before it, for the same reason {@link compactionRatios}
373
+ * climbs: `evaluateUsage` skips any pass below the one already reached, so a later
374
+ * pass that fires first does not merely reorder the ladder, it locks the earlier
375
+ * passes out of the cycle and forces compaction with no summary ever written.
376
+ */
377
+ function effectiveThresholds(contextWindow, baselineTokens = 0, configured = {}, tokenOverrides = {}) {
378
+ let previous = 0;
379
+ const thresholds = {};
380
+ for (const pass of [
381
+ 1,
382
+ 2,
383
+ 3
384
+ ]) {
385
+ const ratioTokens = thresholdTokens(pass, contextWindow, baselineTokens, configured);
386
+ const absolute = tokenOverrides[pass];
387
+ thresholds[pass] = Math.max(absolute !== void 0 && absolute > baselineTokens ? Math.min(ratioTokens, absolute) : ratioTokens, previous);
388
+ previous = thresholds[pass];
389
+ }
390
+ return thresholds;
391
+ }
392
+ function latestCheckpointArtifactEntry(branchEntries) {
393
+ return branchEntries.findLast((entry) => entry.type === "compaction" || entry.type === "custom" && entry.customType === "po-autocompact-checkpoint" || customMessage(entry)?.customType === "po-autocompact-checkpoint" || customMessage(entry)?.customType === "po-autocompact-context");
394
+ }
395
+ function baselineUsageIsSettled(branchEntries) {
396
+ const boundaryIndex = branchEntries.findLastIndex((entry) => entry.type === "compaction" || customMessage(entry)?.customType === "po-autocompact-context");
397
+ return branchEntries.slice(boundaryIndex + 1).some((entry) => {
398
+ if (entry.type !== "message" || entry.message.role !== "assistant") return false;
399
+ const { stopReason, usage } = entry.message;
400
+ if (stopReason === "aborted" || stopReason === "error" || !usage) return false;
401
+ return (usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite) > 0;
402
+ });
403
+ }
404
+ function projectContextMessages(messages, branchEntries) {
405
+ const nativeCompactionIndex = branchEntries.findLastIndex((entry) => entry.type === "compaction");
406
+ const markerEntry = branchEntries.slice(nativeCompactionIndex + 1).findLast((entry) => customMessage(entry)?.customType === CONTEXT_MESSAGE_TYPE);
407
+ const markerMessage = markerEntry && customMessage(markerEntry);
408
+ if (!markerEntry || !markerMessage) return {
409
+ messages,
410
+ retainedMessageCount: 0
411
+ };
412
+ const details = contextDetailsFromUnknown(markerMessage.details);
413
+ const summary = checkpointSummaryFromEntry(markerEntry);
414
+ if (!details || !summary) return {
415
+ messages,
416
+ invalidMarker: true,
417
+ retainedMessageCount: 0
418
+ };
419
+ const markerMessageIndex = messages.findLastIndex((message) => message.role === "custom" && message.customType === "po-autocompact-context" && contextDetailsFromUnknown(message.details)?.poAutocompact.requestId === details.poAutocompact.requestId);
420
+ if (markerMessageIndex === -1) return {
421
+ messages,
422
+ invalidMarker: true,
423
+ retainedMessageCount: 0
424
+ };
425
+ return {
426
+ messages: [
427
+ {
428
+ role: "compactionSummary",
429
+ summary,
430
+ tokensBefore: details.poAutocompact.tokensBefore,
431
+ timestamp: messages[markerMessageIndex]?.timestamp ?? Date.now()
432
+ },
433
+ ...details.retainedMessages,
434
+ ...messages.slice(markerMessageIndex + 1)
435
+ ],
436
+ marker: details.poAutocompact,
437
+ retainedMessageCount: details.retainedMessages.length
438
+ };
439
+ }
440
+ function fileOperationsFromMessages(messages) {
441
+ const fileOps = {
442
+ read: /* @__PURE__ */ new Set(),
443
+ written: /* @__PURE__ */ new Set(),
444
+ edited: /* @__PURE__ */ new Set()
445
+ };
446
+ for (const message of messages) {
447
+ if (message.role !== "assistant") continue;
448
+ for (const block of message.content) {
449
+ if (block.type !== "toolCall") continue;
450
+ const path = typeof block.arguments.path === "string" ? block.arguments.path : void 0;
451
+ if (!path) continue;
452
+ if (block.name === "read") fileOps.read.add(path);
453
+ else if (block.name === "write") fileOps.written.add(path);
454
+ else if (block.name === "edit") fileOps.edited.add(path);
455
+ }
456
+ }
457
+ return fileOps;
458
+ }
459
+ function parseState(value) {
460
+ if (!isRecord(value)) return void 0;
461
+ if (value.version !== 2 || typeof value.cycle !== "number" || !isPass(value.pass)) return void 0;
462
+ if (value.phase !== "waiting" && value.phase !== "checkpoint_pending" && value.phase !== "checkpoint_ready" && value.phase !== "compacting") return void 0;
463
+ const baselineTokens = value.baselineTokens ?? 0;
464
+ if (typeof baselineTokens !== "number" || baselineTokens < 0) return void 0;
465
+ const baselinePending = value.baselinePending ?? false;
466
+ if (typeof baselinePending !== "boolean") return void 0;
467
+ const checkpointQueue = value.checkpointQueue ?? [];
468
+ if (!Array.isArray(checkpointQueue) || !checkpointQueue.every(isPass) || checkpointQueue.some((pass, index) => index > 0 && pass <= checkpointQueue[index - 1])) return void 0;
469
+ const exhaustedPasses = value.exhaustedPasses ?? [];
470
+ if (!Array.isArray(exhaustedPasses) || !exhaustedPasses.every(isPass)) return void 0;
471
+ const invalidAttempts = value.invalidAttempts ?? 0;
472
+ if (typeof invalidAttempts !== "number" || invalidAttempts < 0) return void 0;
473
+ if (!isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return void 0;
474
+ if (value.requestId !== void 0 && typeof value.requestId !== "string") return void 0;
475
+ if (value.compactionPass !== void 0 && value.compactionPass !== 2 && value.compactionPass !== 3) return void 0;
476
+ if ("latestCheckpointEntryId" in value) return void 0;
477
+ if (value.latestCheckpointSnapshotLeafId !== void 0 && typeof value.latestCheckpointSnapshotLeafId !== "string") return void 0;
478
+ if (value.lastAttemptLeafId !== void 0 && typeof value.lastAttemptLeafId !== "string") return void 0;
479
+ if (value.snapshotLeafId !== void 0 && typeof value.snapshotLeafId !== "string") return void 0;
480
+ if (value.snapshotTokens !== void 0 && (typeof value.snapshotTokens !== "number" || value.snapshotTokens < 0)) return void 0;
481
+ if (value.pendingCheckpoint !== void 0 && typeof value.pendingCheckpoint !== "string") return void 0;
482
+ return {
483
+ version: 2,
484
+ cycle: value.cycle,
485
+ pass: value.pass,
486
+ phase: value.phase,
487
+ checkpointQueue: [...checkpointQueue],
488
+ exhaustedPasses: [...exhaustedPasses],
489
+ invalidAttempts,
490
+ baselineTokens,
491
+ baselinePending,
492
+ readFiles: [...value.readFiles],
493
+ modifiedFiles: [...value.modifiedFiles],
494
+ ...value.requestId ? { requestId: value.requestId } : {},
495
+ ...value.compactionPass ? { compactionPass: value.compactionPass } : {},
496
+ ...value.latestCheckpointSnapshotLeafId ? { latestCheckpointSnapshotLeafId: value.latestCheckpointSnapshotLeafId } : {},
497
+ ...value.lastAttemptLeafId ? { lastAttemptLeafId: value.lastAttemptLeafId } : {},
498
+ ...value.snapshotLeafId ? { snapshotLeafId: value.snapshotLeafId } : {},
499
+ ...value.snapshotTokens !== void 0 ? { snapshotTokens: value.snapshotTokens } : {},
500
+ ...value.pendingCheckpoint ? { pendingCheckpoint: value.pendingCheckpoint } : {}
501
+ };
502
+ }
503
+ function checkpointSummaryFromEntry(entry) {
504
+ if (!entry) return void 0;
505
+ if (entry.type === "compaction") return entry.summary.trim() || void 0;
506
+ if (entry.type === "custom") return isRecord(entry.data) && typeof entry.data.summary === "string" ? entry.data.summary.trim() || void 0 : void 0;
507
+ const marker = customMessage(entry);
508
+ if (marker) return (typeof marker.content === "string" ? marker.content : marker.content.filter((block) => block.type === "text").map((block) => block.text).join("\n")).trim() || void 0;
509
+ return assistantText(entry);
510
+ }
511
+ function parseCheckpointDecision(response) {
512
+ const match = response.match(SHOULD_COMPACT_PATTERN);
513
+ const summary = response.replace(SHOULD_COMPACT_PATTERN, "").trim();
514
+ if (!match) return { summary };
515
+ return {
516
+ summary,
517
+ shouldCompact: match[1]?.toLowerCase() === "true"
518
+ };
519
+ }
520
+ function isStructuredCheckpoint(summary) {
521
+ return CHECKPOINT_HEADINGS.every((heading) => summary.includes(heading));
522
+ }
523
+ function createRequestId(sessionId, cycle, pass, leafId) {
524
+ return `${sessionId}:${cycle}:${pass}:${leafId ?? "root"}`;
525
+ }
526
+ function checkpointRequestDetails(cycle, pass, requestId) {
527
+ return {
528
+ version: 2,
529
+ cycle,
530
+ pass,
531
+ requestId
532
+ };
533
+ }
534
+ function mergeFileDetails(current, fileOps, additional) {
535
+ const modified = /* @__PURE__ */ new Set([
536
+ ...current.modifiedFiles,
537
+ ...additional?.modifiedFiles ?? [],
538
+ ...fileOps ? [...fileOps.edited, ...fileOps.written] : []
539
+ ]);
540
+ const read = /* @__PURE__ */ new Set([
541
+ ...current.readFiles,
542
+ ...additional?.readFiles ?? [],
543
+ ...fileOps ? [...fileOps.read] : []
544
+ ]);
545
+ for (const path of modified) read.delete(path);
546
+ const recent = (paths) => [...paths].slice(-500).sort();
547
+ return {
548
+ readFiles: recent(read),
549
+ modifiedFiles: recent(modified)
550
+ };
551
+ }
552
+ function fileDetailsFromUnknown(value) {
553
+ if (!isRecord(value) || !isStringArray(value.readFiles) || !isStringArray(value.modifiedFiles)) return void 0;
554
+ return {
555
+ readFiles: value.readFiles,
556
+ modifiedFiles: value.modifiedFiles
557
+ };
558
+ }
559
+ function withCanonicalFileSections(summary, details) {
560
+ const sections = [];
561
+ if (details.readFiles.length > 0) sections.push(`<read-files>\n${details.readFiles.join("\n")}\n</read-files>`);
562
+ if (details.modifiedFiles.length > 0) sections.push(`<modified-files>\n${details.modifiedFiles.join("\n")}\n</modified-files>`);
563
+ const normalized = summary.replace(FILE_SECTION_PATTERN, "").trim();
564
+ return sections.length > 0 ? `${normalized}\n\n${sections.join("\n\n")}` : normalized;
565
+ }
566
+ //#endregion
567
+ //#region ../../default/po-autocompact/src/services/compactionHistory/index.ts
568
+ const FORMAT = "po-compaction/1";
569
+ const HEADER = `---\nformat: ${JSON.stringify(FORMAT)}\n`;
570
+ const HISTORY_PATH = new RegExp(`^${COMPACTION_ARTIFACT_DIRECTORY}/(?:epoch-\\d+/(?:summary|checkpoint-\\d+)|in-epoch/checkpoint-\\d+)\\.md$`);
571
+ const NATIVE_PREFIX = "The conversation history before this point was compacted into the following summary:\n\n<summary>\n";
572
+ const NATIVE_SUFFIX = "\n</summary>";
573
+ function historyFile(path, fields, body) {
574
+ const header = Object.entries({
575
+ format: FORMAT,
576
+ ...fields
577
+ }).flatMap(([key, value]) => value === void 0 ? [] : [`${key}: ${JSON.stringify(value)}`]);
578
+ return {
579
+ path: `${COMPACTION_ARTIFACT_DIRECTORY}/${path}`,
580
+ text: `---\n${header.join("\n")}\n---\n\n${body}\n`
581
+ };
582
+ }
583
+ function isoTime(value) {
584
+ const time = new Date(value);
585
+ return Number.isFinite(time.getTime()) ? time.toISOString() : void 0;
586
+ }
587
+ function passOf(value) {
588
+ if (typeof value !== "object" || value === null || !("pass" in value)) return void 0;
589
+ return value.pass === 1 || value.pass === 2 || value.pass === 3 ? value.pass : void 0;
590
+ }
591
+ function committedFields(entry) {
592
+ if (entry.type === "compaction") {
593
+ const summary = entry.summary.trim();
594
+ return {
595
+ body: summary.startsWith(NATIVE_PREFIX) && summary.endsWith(NATIVE_SUFFIX) ? summary.slice(96, -11).trim() : summary,
596
+ fields: {
597
+ source: "compact",
598
+ tokensBefore: entry.tokensBefore > 0 ? entry.tokensBefore : void 0
599
+ }
600
+ };
601
+ }
602
+ const marker = customMessage(entry);
603
+ const details = marker?.customType === "po-autocompact-context" ? contextDetailsFromUnknown(marker.details) : void 0;
604
+ if (!details) return void 0;
605
+ return {
606
+ body: checkpointSummaryFromEntry(entry) ?? "",
607
+ fields: {
608
+ source: "autocompact",
609
+ pass: details.poAutocompact.pass,
610
+ tokensBefore: details.poAutocompact.tokensBefore
611
+ }
612
+ };
613
+ }
614
+ /** The only entries `wantedHistory` reads, so mirrors can scan history without keeping the rest. */
615
+ function isHistoryEntry(entry) {
616
+ const type = customMessage(entry)?.customType;
617
+ return entry.type === "compaction" || entry.type === "custom" && entry.customType === "po-autocompact-checkpoint" || type === "po-autocompact-checkpoint" || type === "po-autocompact-context";
618
+ }
619
+ /** Number commits along the active branch so a rewind rewrites the same epoch folders. */
620
+ function wantedHistory(entries) {
621
+ const files = [];
622
+ let staged = [];
623
+ let epoch = 1;
624
+ const checkpoints = (folder) => staged.map(({ entry, summary, pass }, index) => historyFile(`${folder}/checkpoint-${index + 1}.md`, {
625
+ kind: "checkpoint",
626
+ epoch,
627
+ checkpoint: index + 1,
628
+ entryId: entry.id,
629
+ source: "autocompact",
630
+ pass,
631
+ timestamp: isoTime(entry.timestamp)
632
+ }, summary));
633
+ for (const entry of entries) {
634
+ const marker = customMessage(entry);
635
+ if (entry.type === "custom" && entry.customType === "po-autocompact-checkpoint" || marker?.customType === "po-autocompact-checkpoint") {
636
+ const summary = checkpointSummaryFromEntry(entry);
637
+ if (summary) staged.push({
638
+ entry,
639
+ summary,
640
+ pass: passOf(entry.type === "custom" ? entry.data : marker?.details)
641
+ });
642
+ continue;
643
+ }
644
+ const committed = committedFields(entry);
645
+ if (!committed) continue;
646
+ files.push(...checkpoints(`epoch-${epoch}`), historyFile(`epoch-${epoch}/summary.md`, {
647
+ kind: "summary",
648
+ epoch,
649
+ entryId: entry.id,
650
+ ...committed.fields,
651
+ timestamp: isoTime(entry.timestamp)
652
+ }, committed.body));
653
+ staged = [];
654
+ epoch += 1;
655
+ }
656
+ files.push(...checkpoints("in-epoch"));
657
+ return files;
658
+ }
659
+ async function ownedHistory(root, path) {
660
+ const file = await openArtifact(root, path).catch((error) => {
661
+ if (error instanceof ArtifactAccessError && error.status === 404) return void 0;
662
+ throw error;
663
+ });
664
+ if (!file) return false;
665
+ try {
666
+ const bytes = await readArtifactBytes(file.handle, Math.min(file.stat.size, HEADER.length));
667
+ return new TextDecoder().decode(bytes) === HEADER;
668
+ } finally {
669
+ await file.handle.close();
670
+ }
671
+ }
672
+ /** Mirror history into the session artifact folder. Pruning touches only files carrying this mirror's header. */
673
+ async function mirrorCompactionHistory(root, entries) {
674
+ const files = wantedHistory(entries);
675
+ if (files.length === 0) return;
676
+ for (const file of files) await writeArtifactText(root, file.path, file.text);
677
+ const listed = await listArtifacts(root);
678
+ if (listed.error) throw new Error(listed.error);
679
+ const wanted = new Set(files.map((file) => file.path));
680
+ const stale = listed.items.filter((item) => HISTORY_PATH.test(item.path) && !wanted.has(item.path));
681
+ for (const item of stale) if (await ownedHistory(root, item.path)) await removeArtifact(root, item.path);
682
+ for (const folder of new Set(stale.map((item) => item.path.slice(0, item.path.lastIndexOf("/"))))) await removeArtifact(root, folder);
683
+ }
684
+ //#endregion
685
+ //#region ../../default/po-autocompact/src/services/modelOverrides/index.ts
686
+ /**
687
+ * A pattern naming a provider is matched against `provider/id`, anything else
688
+ * against the bare id. `*` does not cross `/`, so a bare pattern tested against a
689
+ * qualified subject would never match and would read as a silently dead rule.
690
+ */
691
+ function matchesModelPattern(pattern, model) {
692
+ const subject = pattern.includes("/") ? `${model.provider}/${model.id}` : model.id;
693
+ return minimatch(subject, pattern, { nocase: true });
694
+ }
695
+ function resolveModelTokenOverrides(model, overrides) {
696
+ if (!model) return {};
697
+ const matched = overrides.find((entry) => matchesModelPattern(entry.model, model));
698
+ if (!matched) return {};
699
+ const { pass1, pass2, pass3 } = matched.tokens;
700
+ return {
701
+ ...pass1 === void 0 ? {} : { 1: pass1 },
702
+ ...pass2 === void 0 ? {} : { 2: pass2 },
703
+ ...pass3 === void 0 ? {} : { 3: pass3 }
704
+ };
705
+ }
706
+ //#endregion
707
+ //#region ../../default/po-autocompact/src/services/summarizationModel/index.ts
708
+ const THINKING_SUFFIX_PATTERN = /:(off|minimal|low|medium|high|xhigh|max)$/;
709
+ /** Splits a `provider/model` reference, tolerating the optional thinking suffix. */
710
+ function parseModelReference(reference) {
711
+ const trimmed = reference.trim();
712
+ const thinking = THINKING_SUFFIX_PATTERN.exec(trimmed)?.[1];
713
+ const identity = trimmed.replace(THINKING_SUFFIX_PATTERN, "");
714
+ const separator = identity.indexOf("/");
715
+ if (separator <= 0 || separator >= identity.length - 1) return void 0;
716
+ return {
717
+ provider: identity.slice(0, separator),
718
+ modelId: identity.slice(separator + 1),
719
+ ...thinking ? { thinking } : {}
720
+ };
721
+ }
722
+ //#endregion
723
+ //#region ../../default/po-autocompact/src/services/nativeAutocompact/index.ts
724
+ /** Exact canonical-prefix comparison refuses to apply summaries to edited or replaced evidence. */
725
+ function tailAfter(snapshot, current) {
726
+ if (snapshot.length > current.length || snapshot.some((message, index) => JSON.stringify(message) !== JSON.stringify(current[index]))) return void 0;
727
+ return current.slice(snapshot.length);
728
+ }
729
+ function leaf(entries) {
730
+ return entries.findLast((entry) => entry.type !== "custom" || entry.customType !== "po-autocompact-state" && entry.customType !== "po-autocompact-checkpoint")?.id ?? "root";
731
+ }
732
+ function createNativeAutocompact(dependencies = {}) {
733
+ const telemetry = dependencies.telemetry ?? createAutocompactTelemetry();
734
+ let active = true;
735
+ let generation = 0;
736
+ let state = createInitialState();
737
+ let snapshot;
738
+ let previousSnapshot;
739
+ let rejectedSummary;
740
+ let context;
741
+ let contributions;
742
+ let controller;
743
+ let serial = Promise.resolve();
744
+ const work = /* @__PURE__ */ new Set();
745
+ const applied = /* @__PURE__ */ new Set();
746
+ const invalid = /* @__PURE__ */ new Set();
747
+ let configFailureReported = false;
748
+ let footer;
749
+ let navigating = false;
750
+ let degraded = false;
751
+ let lastNativeCompactionId;
752
+ let checkpointBoundary;
753
+ let mirrorQueued = false;
754
+ let historyWarnedSession;
755
+ const attributes = () => ({
756
+ "pi.session.id": context?.sessionId ?? "",
757
+ "autocompact.cycle": state.cycle,
758
+ "autocompact.pass": state.pass,
759
+ ...state.requestId ? { "autocompact.request.id": state.requestId } : {},
760
+ ...state.snapshotLeafId ? { "autocompact.snapshot_leaf_id": state.snapshotLeafId } : {},
761
+ ...state.snapshotTokens === void 0 ? {} : { "autocompact.tokens_before": state.snapshotTokens }
762
+ });
763
+ const configured = (execution) => autocompactRuntimeConfig(execution.repoRoot, (error) => {
764
+ if (!configFailureReported) {
765
+ configFailureReported = true;
766
+ telemetry.recordWarning(AUTOCOMPACT_EVENT.configurationLoadFailed, error, {
767
+ ...attributes(),
768
+ "failure.kind": "configuration"
769
+ });
770
+ if (dependencies.modes) Promise.allSettled([Promise.resolve().then(() => execution.client.notify({
771
+ body: `Po autocompact is paused until its configuration is available: ${error instanceof Error ? error.message : String(error)}`,
772
+ level: "warning"
773
+ }))]);
774
+ }
775
+ }, dependencies.modes);
776
+ const alive = (version) => active && !navigating && generation === version;
777
+ const refreshStatus = (execution) => {
778
+ const phase = state.phase === "checkpoint_pending" ? "summarizing" : state.phase === "checkpoint_ready" ? "applying" : void 0;
779
+ footer?.update(phase ? {
780
+ fullText: `Compacting p${state.pass}`,
781
+ compactText: `C${state.pass}`
782
+ } : void 0);
783
+ execution.client.setStatus(STATUS_KEY, phase ? `Compacting pass ${state.pass} (${phase})…` : void 0);
784
+ };
785
+ const enqueue = (callback) => {
786
+ const version = generation;
787
+ const operation = serial.then(async () => {
788
+ if (alive(version)) await callback();
789
+ });
790
+ serial = operation.catch(() => void 0);
791
+ return operation;
792
+ };
793
+ const persist = async (execution, version) => {
794
+ if (!alive(version)) return;
795
+ await execution.session.appendCustomEntry(STATE_CUSTOM_TYPE, {
796
+ ...state,
797
+ nativeLastCompactionId: lastNativeCompactionId
798
+ });
799
+ if (alive(version)) refreshStatus(execution);
800
+ };
801
+ const clear = () => {
802
+ delete state.requestId;
803
+ delete state.snapshotLeafId;
804
+ delete state.snapshotTokens;
805
+ delete state.pendingCheckpoint;
806
+ delete state.compactionPass;
807
+ snapshot = void 0;
808
+ };
809
+ const fail = async (execution, version, error, malformed = false, kind = "unknown") => {
810
+ if (!alive(version)) return;
811
+ degraded = true;
812
+ const summaryTooLarge = error !== null && typeof error === "object" && "code" in error && error.code === "SUMMARY_INPUT_TOO_LARGE";
813
+ const eventAttributes = attributes();
814
+ const summaryAttributes = {
815
+ ...summaryTooLarge ? {
816
+ "failure.reason": "SUMMARY_INPUT_TOO_LARGE",
817
+ "failure.phase": "summary_input"
818
+ } : {},
819
+ ...summaryTooLarge && "size" in error && typeof error.size === "number" && Number.isFinite(error.size) ? { "autocompact.summary.characters": error.size } : {},
820
+ ...summaryTooLarge && "limit" in error && typeof error.limit === "number" && Number.isFinite(error.limit) ? { "autocompact.summary.limit_characters": error.limit } : {}
821
+ };
822
+ const attempts = summaryTooLarge ? 1 : state.invalidAttempts + 1;
823
+ const pass = state.pass;
824
+ const failedLeaf = state.snapshotLeafId;
825
+ state.invalidAttempts = summaryTooLarge ? 0 : attempts;
826
+ if (state.invalidAttempts >= 3) {
827
+ state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);
828
+ state.exhaustedPasses.push(pass);
829
+ state.invalidAttempts = 0;
830
+ }
831
+ state.phase = "waiting";
832
+ clear();
833
+ state.lastAttemptLeafId = failedLeaf;
834
+ const errors = [error];
835
+ try {
836
+ await persist(execution, version);
837
+ } catch (persistError) {
838
+ errors.push(persistError);
839
+ }
840
+ if (!alive(version)) return;
841
+ await Promise.allSettled([Promise.resolve().then(() => execution.client.notify({
842
+ body: `Po autocompact summarization pass ${pass} failed: ${error instanceof Error ? error.message : String(error)}`,
843
+ level: "error"
844
+ })), ...errors.map((failure, index) => Promise.resolve().then(() => telemetry.recordError(malformed ? AUTOCOMPACT_EVENT.checkpointInvalid : AUTOCOMPACT_EVENT.checkpointFailed, failure, {
845
+ ...eventAttributes,
846
+ ...index === 0 ? summaryAttributes : {},
847
+ "failure.kind": index === 0 ? summaryTooLarge ? "validation" : kind : "persistence",
848
+ "autocompact.checkpoint.attempts": attempts,
849
+ "autocompact.checkpoint.exhausted": summaryTooLarge || attempts >= 3
850
+ }, { includeException: true })))]);
851
+ };
852
+ const matching = async (execution, keep, stopAt) => {
853
+ const entries = [];
854
+ for await (const record of execution.session.entriesNewestFirst()) {
855
+ const entry = record;
856
+ if (entry.id === stopAt) break;
857
+ if (keep(entry)) entries.push(entry);
858
+ }
859
+ return entries.reverse();
860
+ };
861
+ const policyEntries = async (execution, withCheckpoint) => {
862
+ const entries = [...await execution.session.entries({
863
+ type: "custom",
864
+ customType: PLAN_DOCUMENT_ENTRY,
865
+ limit: 1
866
+ })];
867
+ if (withCheckpoint) for await (const record of execution.session.entriesNewestFirst()) {
868
+ const entry = record;
869
+ if (!latestCheckpointArtifactEntry([entry])) continue;
870
+ entries.push(entry);
871
+ break;
872
+ }
873
+ return entries;
874
+ };
875
+ const contextBranch = async (execution) => {
876
+ const entries = [];
877
+ let foundLeaf = false;
878
+ for await (const record of execution.session.entriesNewestFirst()) {
879
+ const entry = record;
880
+ const isLeaf = leaf([entry]) !== "root";
881
+ if (entry.type !== "custom" || !foundLeaf && isLeaf) entries.push(entry);
882
+ if (isLeaf) foundLeaf = true;
883
+ if (entry.type === "compaction" || customMessage(entry)?.customType === "po-autocompact-context") break;
884
+ }
885
+ return entries.reverse();
886
+ };
887
+ const canonical = async (execution, entries) => {
888
+ if (!execution.session.contextMessages) throw new Error("Canonical context is unavailable for autocompact.");
889
+ return projectContextMessages(await execution.session.contextMessages(), entries).messages;
890
+ };
891
+ const scheduleMirror = (execution) => {
892
+ if (mirrorQueued) return;
893
+ mirrorQueued = true;
894
+ enqueue(async () => {
895
+ mirrorQueued = false;
896
+ try {
897
+ await mirrorCompactionHistory(artifactRoot(execution.sessionId, execution.environment), await matching(execution, isHistoryEntry));
898
+ } catch (error) {
899
+ const warn = historyWarnedSession !== execution.sessionId;
900
+ historyWarnedSession = execution.sessionId;
901
+ await Promise.allSettled([Promise.resolve().then(() => telemetry.recordWarning(AUTOCOMPACT_EVENT.historyWriteFailed, error, attributes())), ...warn ? [Promise.resolve().then(() => execution.client.notify({
902
+ body: `Po autocompact could not save compaction history: ${error instanceof Error ? error.message : String(error)}`,
903
+ level: "warning"
904
+ }))] : []]);
905
+ }
906
+ }).finally(() => {
907
+ mirrorQueued = false;
908
+ });
909
+ };
910
+ const contributionSnapshot = async (execution) => {
911
+ const result = readContextContributionsSnapshot(contributions);
912
+ for (const error of result.errors) {
913
+ await execution.client.notify({
914
+ body: `Po autocompact context contribution degraded (${error.source}/${error.id}): ${error.message}`,
915
+ level: "warning"
916
+ });
917
+ await telemetry.recordWarning(AUTOCOMPACT_EVENT.contextContributionDegraded, new Error(error.message), {
918
+ ...attributes(),
919
+ "autocompact.context_contribution.source": error.source,
920
+ "autocompact.context_contribution.id": error.id,
921
+ "autocompact.context_contribution.order": error.order
922
+ });
923
+ }
924
+ return result;
925
+ };
926
+ const runtimeState = async (execution, entries, version, appendMessage = checkpointBoundary?.appendMessage.bind(checkpointBoundary)) => {
927
+ const saved = runtimeStateSnapshot(entries, await contributionSnapshot(execution));
928
+ if (!alive(version)) return;
929
+ await appendMessage?.({
930
+ type: RUNTIME_STATE_MESSAGE_TYPE,
931
+ text: formatRuntimeState(saved),
932
+ display: false,
933
+ details: {
934
+ version: 2,
935
+ ...saved
936
+ }
937
+ });
938
+ return {
939
+ "autocompact.runtime.plan_present": Boolean(saved.planPath),
940
+ "autocompact.runtime.contribution_count": saved.contributions.length,
941
+ "autocompact.runtime.contribution_error_count": saved.contributionErrors.length
942
+ };
943
+ };
944
+ const summaryModel = async (execution, configuration) => {
945
+ const ownReference = configuration.agent?.model ? parseModelReference(configuration.agent.model) : void 0;
946
+ const candidate = ownReference ? `${ownReference.provider}/${ownReference.modelId}` : void 0;
947
+ const reference = candidate && execution.textCompletion.available(candidate) ? candidate : execution.model ? `${execution.model.provider}/${execution.model.id}` : "";
948
+ return {
949
+ reference,
950
+ thinking: configuration.agent?.thinking ?? (reference === candidate ? ownReference?.thinking : void 0) ?? (await execution.session.readModelSettings?.())?.thinkingLevel
951
+ };
952
+ };
953
+ const manualCompaction = async (event, execution) => {
954
+ const configuration = configured(execution);
955
+ if (!configuration.enabled || !execution.textCompletion?.summarize) return;
956
+ try {
957
+ const entries = await contextBranch(execution);
958
+ const pinned = await policyEntries(execution, state.pass > 1);
959
+ const messages = await canonical(execution, entries);
960
+ const delta = state.pass > 1 && previousSnapshot ? tailAfter(previousSnapshot, messages) : void 0;
961
+ const previous = state.pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(pinned)) : void 0;
962
+ const { reference, thinking } = await summaryModel(execution, configuration);
963
+ const instructions = checkpointInstructions(3, {
964
+ plan: latestPlanSnapshot(pinned),
965
+ contextContributions: await contributionSnapshot(execution),
966
+ readFiles: state.readFiles,
967
+ modifiedFiles: state.modifiedFiles
968
+ });
969
+ const { summary } = parseCheckpointDecision(await execution.textCompletion.summarize(reference, {
970
+ messages: delta ?? messages,
971
+ instructions: typeof event.instructions === "string" && event.instructions.trim() ? `${instructions}\n\n${event.instructions}` : instructions,
972
+ ...previous ? { previousSummary: previous } : {},
973
+ ...thinking ? { thinkingLevel: thinking } : {},
974
+ ...execution.signal ? { signal: execution.signal } : {}
975
+ }));
976
+ if (!isStructuredCheckpoint(summary)) throw new Error("Summarization returned an incomplete checkpoint.");
977
+ const files = mergeFileDetails(state, fileOperationsFromMessages(messages));
978
+ const usage = await execution.session.contextUsage?.();
979
+ return { compaction: {
980
+ summary: withCanonicalFileSections(summary, files),
981
+ tokensBefore: usage?.tokens ?? 0,
982
+ retainedTail: [],
983
+ details: files
984
+ } };
985
+ } catch (error) {
986
+ await execution.client.notify({
987
+ body: `Po autocompact manual compaction failed: ${error instanceof Error ? error.message : String(error)}`,
988
+ level: "error"
989
+ });
990
+ throw error;
991
+ }
992
+ };
993
+ const resetCycle = () => {
994
+ state.phase = "waiting";
995
+ state.checkpointQueue = [];
996
+ state.exhaustedPasses = [];
997
+ state.invalidAttempts = 0;
998
+ state.baselinePending = true;
999
+ state.cycle += 1;
1000
+ state.pass = 1;
1001
+ delete state.lastAttemptLeafId;
1002
+ delete state.latestCheckpointSnapshotLeafId;
1003
+ clear();
1004
+ previousSnapshot = void 0;
1005
+ rejectedSummary = void 0;
1006
+ };
1007
+ const applyReady = async (execution, version, appendMessage) => {
1008
+ if (state.phase !== "checkpoint_ready" || !state.pendingCheckpoint || !state.requestId || !state.snapshotLeafId) return false;
1009
+ const decision = parseCheckpointDecision(state.pendingCheckpoint);
1010
+ if (!isStructuredCheckpoint(decision.summary)) {
1011
+ await fail(execution, version, /* @__PURE__ */ new Error("Summarization returned an incomplete checkpoint."), true, "validation");
1012
+ return false;
1013
+ }
1014
+ const entries = await contextBranch(execution);
1015
+ const messages = await canonical(execution, entries);
1016
+ if (!alive(version)) return false;
1017
+ const tail = snapshot && tailAfter(snapshot, messages);
1018
+ if (!tail) {
1019
+ await fail(execution, version, /* @__PURE__ */ new Error("Canonical checkpoint evidence changed; summary must be regenerated."), false, "evidence_changed");
1020
+ return false;
1021
+ }
1022
+ const pass = state.pass;
1023
+ if (pass === 1 || pass === 2 && decision.shouldCompact !== true) {
1024
+ await execution.session.appendCustomEntry(CHECKPOINT_MESSAGE_TYPE, {
1025
+ ...checkpointRequestDetails(state.cycle, pass, state.requestId),
1026
+ summary: decision.summary
1027
+ });
1028
+ if (!alive(version)) return false;
1029
+ previousSnapshot = snapshot;
1030
+ state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;
1031
+ state.checkpointQueue = state.checkpointQueue.filter((item) => item !== pass);
1032
+ state.pass = pass === 1 ? 2 : 3;
1033
+ state.phase = "waiting";
1034
+ state.invalidAttempts = 0;
1035
+ clear();
1036
+ await persist(execution, version);
1037
+ scheduleMirror(execution);
1038
+ return false;
1039
+ }
1040
+ const files = mergeFileDetails(state, fileOperationsFromMessages(messages));
1041
+ const details = {
1042
+ ...files,
1043
+ poAutocompact: {
1044
+ version: 2,
1045
+ cycle: state.cycle,
1046
+ pass,
1047
+ requestId: state.requestId,
1048
+ snapshotLeafId: state.snapshotLeafId,
1049
+ tokensBefore: state.snapshotTokens ?? 0
1050
+ },
1051
+ retainedMessages: tail
1052
+ };
1053
+ const idle = (await execution.session.activity()).isIdle;
1054
+ if (!alive(version)) return false;
1055
+ const id = await appendMessage({
1056
+ type: CONTEXT_MESSAGE_TYPE,
1057
+ text: withCanonicalFileSections(decision.summary, files),
1058
+ display: false,
1059
+ details
1060
+ }, { resetContext: { retainedMessages: tail } });
1061
+ if (!alive(version) || !id) return false;
1062
+ await execution.session.setLabel?.(id, `autocompact:c${state.cycle}:p${pass}`);
1063
+ if (!alive(version)) return false;
1064
+ const runtimeAttributes = await runtimeState(execution, await policyEntries(execution, false), version, appendMessage);
1065
+ if (!alive(version)) return false;
1066
+ const committedAttributes = attributes();
1067
+ state.readFiles = files.readFiles;
1068
+ state.modifiedFiles = files.modifiedFiles;
1069
+ resetCycle();
1070
+ await persist(execution, version);
1071
+ scheduleMirror(execution);
1072
+ if (!alive(version)) return false;
1073
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextCommitted, {
1074
+ ...committedAttributes,
1075
+ "autocompact.message_count.before": messages.length,
1076
+ "autocompact.message_count.retained": tail.length,
1077
+ "autocompact.apply_mode": idle ? "idle" : "turn_end",
1078
+ ...runtimeAttributes
1079
+ });
1080
+ if (idle && alive(version)) await execution.session.admitMessage?.({
1081
+ type: RESUME_MESSAGE_TYPE,
1082
+ text: "Asynchronous compaction completed. Continue from the compacted checkpoint's immediate next action without repeating completed work.",
1083
+ display: true,
1084
+ details: { notice: "Context compacted · continuing" }
1085
+ }, "steer", `${RESUME_MESSAGE_TYPE}:${details.poAutocompact.requestId}`);
1086
+ return true;
1087
+ };
1088
+ const ensureCheckpointBoundary = (execution) => {
1089
+ if (checkpointBoundary) return;
1090
+ if (!execution.session.registerCheckpointBoundary) throw new Error("Native checkpoint boundaries are unavailable.");
1091
+ checkpointBoundary = execution.session.registerCheckpointBoundary(async (boundary) => {
1092
+ if (!active || navigating || boundary.signal?.aborted) return;
1093
+ const current = context ?? execution;
1094
+ await enqueue(() => boundary.signal?.aborted ? Promise.resolve() : progress(current, true, boundary.appendMessage.bind(boundary)));
1095
+ });
1096
+ };
1097
+ const advance = async (execution, allowBusy = false, appendMessage = checkpointBoundary?.appendMessage.bind(checkpointBoundary)) => {
1098
+ const version = generation;
1099
+ context = execution;
1100
+ const activity = await execution.session.activity();
1101
+ if (!alive(version) || activity.hasPendingMessages) return;
1102
+ if (appendMessage && (activity.isIdle || allowBusy)) {
1103
+ if (await applyReady(execution, version, appendMessage)) return;
1104
+ }
1105
+ if (!alive(version) || state.phase !== "waiting") return;
1106
+ const configuration = configured(execution);
1107
+ if (!configuration.enabled || !execution.session.contextUsage || !execution.textCompletion?.summarize) return;
1108
+ const usage = await execution.session.contextUsage();
1109
+ if (!alive(version) || !usage || typeof usage.tokens !== "number" || !Number.isFinite(usage.tokens) || usage.tokens < 0) return;
1110
+ const tokens = usage.tokens;
1111
+ const thresholds = effectiveThresholds(usage.contextWindow, state.baselineTokens, configuration.ratios, resolveModelTokenOverrides(execution.model, configuration.overrides));
1112
+ if (!state.baselinePending && !state.checkpointQueue.length && ![
1113
+ 1,
1114
+ 2,
1115
+ 3
1116
+ ].some((pass) => pass >= state.pass && !state.exhaustedPasses.includes(pass) && tokens >= thresholds[pass])) return;
1117
+ const entries = await contextBranch(execution);
1118
+ if (!alive(version)) return;
1119
+ if (state.baselinePending) {
1120
+ if (!baselineUsageIsSettled(entries)) return;
1121
+ state.baselineTokens = usage.tokens;
1122
+ state.baselinePending = false;
1123
+ await persist(execution, version);
1124
+ return;
1125
+ }
1126
+ const currentLeaf = leaf(entries);
1127
+ if (currentLeaf === state.lastAttemptLeafId) return;
1128
+ for (const pass of [
1129
+ 1,
1130
+ 2,
1131
+ 3
1132
+ ]) if (pass >= state.pass && !state.checkpointQueue.includes(pass) && !state.exhaustedPasses.includes(pass) && usage.tokens >= thresholds[pass]) state.checkpointQueue.push(pass);
1133
+ const pass = state.checkpointQueue[0];
1134
+ if (!pass) return;
1135
+ state.pass = pass;
1136
+ const checkpointEntries = await policyEntries(execution, pass > 1);
1137
+ const messages = await canonical(execution, entries);
1138
+ const steering = await contributionSnapshot(execution);
1139
+ if (!alive(version)) return;
1140
+ const previous = pass > 1 ? checkpointSummaryFromEntry(latestCheckpointArtifactEntry(checkpointEntries)) : void 0;
1141
+ const delta = previousSnapshot ? tailAfter(previousSnapshot, messages) : void 0;
1142
+ const summaryInput = {
1143
+ messages: pass > 1 && delta ? delta : messages,
1144
+ instructions: checkpointInstructions(pass, {
1145
+ plan: latestPlanSnapshot(checkpointEntries),
1146
+ contextContributions: steering,
1147
+ readFiles: state.readFiles,
1148
+ modifiedFiles: state.modifiedFiles
1149
+ }),
1150
+ ...previous ? { previousSummary: previous } : {}
1151
+ };
1152
+ if (rejectedSummary && rejectedSummary.instructions === summaryInput.instructions && rejectedSummary.previousSummary === summaryInput.previousSummary && tailAfter(rejectedSummary.messages, summaryInput.messages)?.length === 0) return;
1153
+ rejectedSummary = void 0;
1154
+ snapshot = messages;
1155
+ const requestId = createRequestId(execution.sessionId, state.cycle, pass, currentLeaf);
1156
+ state.phase = "checkpoint_pending";
1157
+ state.requestId = requestId;
1158
+ state.snapshotLeafId = currentLeaf;
1159
+ state.snapshotTokens = usage.tokens;
1160
+ delete state.lastAttemptLeafId;
1161
+ delete state.pendingCheckpoint;
1162
+ await persist(execution, version);
1163
+ if (!alive(version)) return;
1164
+ degraded = false;
1165
+ controller?.abort();
1166
+ controller = new AbortController();
1167
+ const signal = controller.signal;
1168
+ const requestAttributes = {
1169
+ ...attributes(),
1170
+ "autocompact.message_count.before": messages.length
1171
+ };
1172
+ let failureKind = "configuration";
1173
+ const completion = telemetry.runInSpan("po_autocompact.checkpoint", requestAttributes, async () => {
1174
+ const { reference, thinking } = await summaryModel(execution, configuration);
1175
+ failureKind = "unknown";
1176
+ if (!alive(version) || signal.aborted) return "";
1177
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointStarted, requestAttributes);
1178
+ return execution.textCompletion.summarize(reference, {
1179
+ ...summaryInput,
1180
+ messages: summaryInput.messages,
1181
+ ...thinking ? { thinkingLevel: thinking } : {},
1182
+ signal
1183
+ });
1184
+ }).then(async (summary) => {
1185
+ await enqueue(async () => {
1186
+ if (!alive(version) || signal.aborted || state.requestId !== requestId) return;
1187
+ if (!summary.trim()) {
1188
+ await fail(execution, version, /* @__PURE__ */ new Error("Summarization returned an empty checkpoint."), false, "empty_checkpoint");
1189
+ return;
1190
+ }
1191
+ state.phase = "checkpoint_ready";
1192
+ state.pendingCheckpoint = summary.trim();
1193
+ failureKind = "persistence";
1194
+ await persist(execution, version);
1195
+ failureKind = "unknown";
1196
+ if (!alive(version)) return;
1197
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.checkpointCompleted, {
1198
+ ...requestAttributes,
1199
+ "autocompact.checkpoint.characters": summary.length
1200
+ });
1201
+ if ((await execution.session.activity()).isIdle && alive(version)) await progress(execution);
1202
+ });
1203
+ }).catch(async (error) => {
1204
+ await enqueue(async () => {
1205
+ if (alive(version) && state.requestId === requestId) {
1206
+ if (error !== null && typeof error === "object" && "code" in error && error.code === "SUMMARY_INPUT_TOO_LARGE") rejectedSummary = summaryInput;
1207
+ await fail(execution, version, error, false, failureKind);
1208
+ }
1209
+ });
1210
+ });
1211
+ work.add(completion);
1212
+ completion.then(() => work.delete(completion), () => work.delete(completion));
1213
+ };
1214
+ const progress = async (execution, allowBusy = false, appendMessage) => {
1215
+ const version = generation;
1216
+ try {
1217
+ ensureCheckpointBoundary(execution);
1218
+ await advance(execution, allowBusy, appendMessage);
1219
+ } catch (error) {
1220
+ try {
1221
+ await fail(execution, version, error, false, "persistence");
1222
+ } finally {
1223
+ if (alive(version)) delete state.lastAttemptLeafId;
1224
+ }
1225
+ }
1226
+ };
1227
+ const load = async (execution) => {
1228
+ if (!active) return;
1229
+ navigating = false;
1230
+ generation += 1;
1231
+ const version = generation;
1232
+ controller?.abort(/* @__PURE__ */ new Error("Autocompact session generation changed."));
1233
+ controller = void 0;
1234
+ context = execution;
1235
+ applied.clear();
1236
+ invalid.clear();
1237
+ const saved = await execution.session.customSnapshot?.(STATE_CUSTOM_TYPE);
1238
+ if (!alive(version)) return;
1239
+ const entry = saved?.available ? saved.entry : void 0;
1240
+ const data = entry?.type === "custom" && entry.data && typeof entry.data === "object" ? entry.data : void 0;
1241
+ state = parseState(data) ?? createInitialState();
1242
+ lastNativeCompactionId = typeof data?.nativeLastCompactionId === "string" ? data.nativeLastCompactionId : void 0;
1243
+ const validMessages = (value) => Array.isArray(value) && value.every((message) => message && typeof message === "object" && typeof message.role === "string");
1244
+ snapshot = validMessages(data?.nativeSnapshot) ? data.nativeSnapshot : void 0;
1245
+ previousSnapshot = validMessages(data?.nativePreviousSnapshot) ? data.nativePreviousSnapshot : void 0;
1246
+ if (entry?.id && state.phase === "checkpoint_ready" && state.requestId) {
1247
+ const artifacts = await matching(execution, (item) => item.type === "custom" && item.customType === "po-autocompact-checkpoint" || customMessage(item)?.customType === "po-autocompact-context", entry?.id);
1248
+ const committed = artifacts.findLast((item) => {
1249
+ const message = item.type === "message" ? item.message : void 0;
1250
+ if (message?.role !== "custom" || message.customType !== "po-autocompact-context") return false;
1251
+ const details = contextDetailsFromUnknown(message.details);
1252
+ return details !== void 0 && details.poAutocompact.requestId === state.requestId && details.poAutocompact.cycle === state.cycle && details.poAutocompact.pass === state.pass && details.poAutocompact.snapshotLeafId === state.snapshotLeafId && isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? "");
1253
+ });
1254
+ if (committed?.type === "message" && committed.message.role === "custom") {
1255
+ const details = contextDetailsFromUnknown(committed.message.details);
1256
+ state.readFiles = details.readFiles;
1257
+ state.modifiedFiles = details.modifiedFiles;
1258
+ resetCycle();
1259
+ await persist(execution, version);
1260
+ } else if (artifacts.findLast((item) => {
1261
+ if (item.type !== "custom" || item.customType !== "po-autocompact-checkpoint") return false;
1262
+ const details = item.data;
1263
+ return details?.version === 2 && details.requestId === state.requestId && details.cycle === state.cycle && details.pass === state.pass && isStructuredCheckpoint(checkpointSummaryFromEntry(item) ?? "");
1264
+ }) && (state.pass === 1 || state.pass === 2)) {
1265
+ previousSnapshot = snapshot;
1266
+ state.latestCheckpointSnapshotLeafId = state.snapshotLeafId;
1267
+ state.checkpointQueue = state.checkpointQueue.filter((pass) => pass !== state.pass);
1268
+ state.pass = state.pass === 1 ? 2 : 3;
1269
+ state.phase = "waiting";
1270
+ state.invalidAttempts = 0;
1271
+ clear();
1272
+ await persist(execution, version);
1273
+ }
1274
+ }
1275
+ if (state.phase !== "waiting" && (state.phase !== "checkpoint_ready" || !snapshot)) {
1276
+ state.phase = "waiting";
1277
+ clear();
1278
+ delete state.lastAttemptLeafId;
1279
+ await persist(execution, version);
1280
+ }
1281
+ if (!alive(version)) return;
1282
+ const progressed = enqueue(() => progress(execution));
1283
+ scheduleMirror(execution);
1284
+ await progressed;
1285
+ };
1286
+ const restore = async (execution) => {
1287
+ const version = generation + 1;
1288
+ try {
1289
+ await load(execution);
1290
+ } catch (error) {
1291
+ await fail(execution, version, error);
1292
+ }
1293
+ };
1294
+ return {
1295
+ hooks: [
1296
+ {
1297
+ event: "session_start",
1298
+ handle: (_event, execution) => restore(execution)
1299
+ },
1300
+ {
1301
+ event: "session_tree",
1302
+ handle: (event, execution) => {
1303
+ if (!active) return;
1304
+ if (event.status === "started") {
1305
+ navigating = true;
1306
+ generation += 1;
1307
+ controller?.abort(/* @__PURE__ */ new Error("Autocompact navigation started."));
1308
+ return;
1309
+ }
1310
+ return restore(execution);
1311
+ }
1312
+ },
1313
+ {
1314
+ event: "turn_end",
1315
+ handle: (_event, execution) => enqueue(() => progress(execution))
1316
+ },
1317
+ {
1318
+ event: "agent_settled",
1319
+ handle: (_event, execution) => enqueue(() => progress(execution))
1320
+ },
1321
+ {
1322
+ event: "session_before_compact",
1323
+ handle: (event, execution) => {
1324
+ if (!active || navigating) return;
1325
+ if (event.reason === "manual") return manualCompaction(event, execution);
1326
+ return !degraded && configured(execution).enabled && event.reason === "threshold" && (state.phase === "checkpoint_pending" || state.phase === "checkpoint_ready") ? { cancel: true } : void 0;
1327
+ }
1328
+ },
1329
+ {
1330
+ event: "context",
1331
+ async handle(event, execution) {
1332
+ if (!active || navigating || !Array.isArray(event.messages)) return;
1333
+ const started = Date.now();
1334
+ try {
1335
+ const version = generation;
1336
+ const entries = await contextBranch(execution);
1337
+ if (!alive(version)) return;
1338
+ const projection = projectContextMessages(event.messages, entries);
1339
+ if (projection.invalidMarker) {
1340
+ const id = leaf(entries);
1341
+ if (!invalid.has(id)) {
1342
+ invalid.add(id);
1343
+ await telemetry.recordError(AUTOCOMPACT_EVENT.contextMarkerInvalid, /* @__PURE__ */ new Error("Po autocompact context marker is malformed."), {
1344
+ ...attributes(),
1345
+ "autocompact.leaf_id": id
1346
+ });
1347
+ }
1348
+ return;
1349
+ }
1350
+ if (!projection.marker) return;
1351
+ if (!applied.has(projection.marker.requestId)) {
1352
+ applied.add(projection.marker.requestId);
1353
+ await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextApplied, {
1354
+ ...attributes(),
1355
+ "autocompact.request.id": projection.marker.requestId,
1356
+ "autocompact.cycle": projection.marker.cycle,
1357
+ "autocompact.pass": projection.marker.pass,
1358
+ "autocompact.snapshot_leaf_id": projection.marker.snapshotLeafId,
1359
+ "autocompact.tokens_before": projection.marker.tokensBefore,
1360
+ "autocompact.message_count.before": event.messages.length,
1361
+ "autocompact.message_count.after": projection.messages.length,
1362
+ "autocompact.message_count.retained": projection.retainedMessageCount
1363
+ });
1364
+ }
1365
+ return alive(version) ? { messages: projection.messages } : void 0;
1366
+ } finally {
1367
+ const hookMs = Date.now() - started;
1368
+ if (active && hookMs >= 25) await telemetry.recordEvent(AUTOCOMPACT_EVENT.contextHookSlow, {
1369
+ ...attributes(),
1370
+ hook_ms: hookMs,
1371
+ "autocompact.message_count": event.messages.length
1372
+ });
1373
+ }
1374
+ }
1375
+ },
1376
+ {
1377
+ event: "session_compact",
1378
+ handle: (event, execution) => {
1379
+ if (!active || event.status !== "completed" || typeof event.entryId !== "string" || event.entryId === lastNativeCompactionId) return;
1380
+ const observedGeneration = generation;
1381
+ return enqueue(async () => {
1382
+ const compacted = (await execution.session.entries({
1383
+ type: "compaction",
1384
+ limit: 1
1385
+ }))[0];
1386
+ if (!alive(observedGeneration) || !compacted || compacted.type !== "compaction" || compacted.id !== event.entryId || compacted.id === lastNativeCompactionId) return;
1387
+ generation += 1;
1388
+ const version = generation;
1389
+ controller?.abort(/* @__PURE__ */ new Error("Native compaction superseded checkpoint."));
1390
+ controller = void 0;
1391
+ lastNativeCompactionId = compacted.id;
1392
+ const files = mergeFileDetails(state, void 0, fileDetailsFromUnknown("details" in compacted ? compacted.details : void 0));
1393
+ state.readFiles = files.readFiles;
1394
+ state.modifiedFiles = files.modifiedFiles;
1395
+ await execution.session.setLabel?.(compacted.id, `autocompact:c${state.cycle}:external`);
1396
+ if (!alive(version)) return;
1397
+ const plan = await execution.session.entries({
1398
+ type: "custom",
1399
+ customType: PLAN_DOCUMENT_ENTRY,
1400
+ limit: 1
1401
+ });
1402
+ const runtimeAttributes = await runtimeState(execution, plan, version);
1403
+ if (!alive(version)) return;
1404
+ const nativeAttributes = attributes();
1405
+ resetCycle();
1406
+ await persist(execution, version);
1407
+ scheduleMirror(execution);
1408
+ if (alive(version)) await telemetry.recordEvent(AUTOCOMPACT_EVENT.nativeCompactionCompleted, {
1409
+ ...nativeAttributes,
1410
+ "autocompact.native.reason": typeof event.reason === "string" ? event.reason : "unknown",
1411
+ "autocompact.native.from_extension": "fromHook" in compacted && compacted.fromHook === true,
1412
+ "autocompact.tokens_before": compacted.tokensBefore,
1413
+ ...runtimeAttributes
1414
+ });
1415
+ });
1416
+ }
1417
+ }
1418
+ ],
1419
+ plugin(cordis) {
1420
+ cordis.inject([PO_UI_HUB_SERVICE], (injected) => {
1421
+ const contribution = requirePoUiHub(injected).registerFooter({
1422
+ source: FOOTER_SOURCE,
1423
+ id: "autocompact",
1424
+ order: 20
1425
+ });
1426
+ footer = contribution;
1427
+ if (context && active) refreshStatus(context);
1428
+ return () => {
1429
+ contribution.dispose();
1430
+ if (footer === contribution) footer = void 0;
1431
+ };
1432
+ });
1433
+ cordis.inject([PO_CONTEXT_CONTRIBUTIONS_SERVICE], (injected) => {
1434
+ const service = requirePoContextContributions(injected);
1435
+ contributions = service;
1436
+ return () => {
1437
+ if (contributions === service) contributions = void 0;
1438
+ };
1439
+ });
1440
+ },
1441
+ start: restore,
1442
+ async stop() {
1443
+ active = false;
1444
+ checkpointBoundary?.dispose();
1445
+ checkpointBoundary = void 0;
1446
+ generation += 1;
1447
+ controller?.abort(/* @__PURE__ */ new Error("Autocompact is shutting down."));
1448
+ await Promise.allSettled([...work, serial]);
1449
+ context?.client.setStatus(STATUS_KEY, void 0);
1450
+ footer?.update(void 0);
1451
+ footer = void 0;
1452
+ context = void 0;
1453
+ contributions = void 0;
1454
+ await telemetry.shutdown();
1455
+ }
1456
+ };
1457
+ }
1458
+ //#endregion
1459
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/root.server.ts
1460
+ var root_server_default = defineRoot(({ agent, context }) => {
1461
+ const runtime = createNativeAutocompact({
1462
+ telemetry: createAutocompactTelemetry({
1463
+ env: agent?.context.environment,
1464
+ cwd: agent?.context.cwd
1465
+ }),
1466
+ modes: admittedModes(context)
1467
+ });
1468
+ return {
1469
+ value: runtime,
1470
+ services: [runtime.plugin],
1471
+ onDispose: runtime.stop
1472
+ };
1473
+ });
1474
+ //#endregion
1475
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/agent-settled.server.ts
1476
+ var agent_settled_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "agent_settled"));
1477
+ //#endregion
1478
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/context.server.ts
1479
+ var context_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "context"));
1480
+ //#endregion
1481
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/session-before-compact.server.ts
1482
+ var session_before_compact_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "session_before_compact"));
1483
+ //#endregion
1484
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/session-compact.server.ts
1485
+ var session_compact_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "session_compact"));
1486
+ //#endregion
1487
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/session-start.server.ts
1488
+ var session_start_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "session_start"));
1489
+ //#endregion
1490
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/session-tree.server.ts
1491
+ var session_tree_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "session_tree"));
1492
+ //#endregion
1493
+ //#region ../../default/po-autocompact/src/extensions/workspaces/sessions/(backend)/hook/turn-end.server.ts
1494
+ var turn_end_server_default = defineHook(({ root }) => root.hooks.find((hook) => hook.event === "turn_end"));
1495
+ //#endregion
1496
+ //#region ../../default/po-autocompact/generated/server.ts
1497
+ const at = (value, context) => typeof value === "function" ? value(context) : value;
1498
+ const via = (identity, value) => value === void 0 ? void 0 : {
1499
+ ...identity,
1500
+ ...value
1501
+ };
1502
+ const serverPlugin = defineServerPlugin({
1503
+ name: "@agimon-ai/po-autocompact",
1504
+ providerOverrides: composeServerProviderOverrides(root_server_default),
1505
+ injects: composeRootInjects({ session: [root_server_default] }),
1506
+ session: async (context) => {
1507
+ const scopeSession = await context.scopeRoot("session", root_server_default, context);
1508
+ const contextSession = {
1509
+ ...context,
1510
+ root: scopeSession.value
1511
+ };
1512
+ return {
1513
+ ...composeRootHooks(scopeSession),
1514
+ get hooks() {
1515
+ return [
1516
+ via({ event: "agent_settled" }, at(agent_settled_server_default, contextSession)),
1517
+ via({ event: "context" }, at(context_server_default, contextSession)),
1518
+ via({ event: "session_before_compact" }, at(session_before_compact_server_default, contextSession)),
1519
+ via({ event: "session_compact" }, at(session_compact_server_default, contextSession)),
1520
+ via({ event: "session_start" }, at(session_start_server_default, contextSession)),
1521
+ via({ event: "session_tree" }, at(session_tree_server_default, contextSession)),
1522
+ via({ event: "turn_end" }, at(turn_end_server_default, contextSession))
1523
+ ];
1524
+ },
1525
+ services: [...scopeSession.services ?? []],
1526
+ get activities() {
1527
+ return [...scopeSession.activities ?? []];
1528
+ }
1529
+ };
1530
+ }
1531
+ });
1532
+ //#endregion
1533
+ export { serverPlugin as default, serverPlugin };