@ensocode/server 0.3.13 → 0.3.15-beta.234

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 (216) hide show
  1. package/README.md +11 -1
  2. package/out/phone/assets/{EditDiff-B3HxLrbF.js → EditDiff-DlIQ0NvB.js} +1 -1
  3. package/out/phone/assets/{ReadFileView-BFpGH-kK.js → ReadFileView-hlSV-q1S.js} +1 -1
  4. package/out/phone/assets/{abnfDiagram-VCTEODGH-BNvyPGoF.js → abnfDiagram-VCTEODGH-cWLl_02_.js} +1 -1
  5. package/out/phone/assets/architecture-7GRP2DOG-WvHUAPXe.js +1 -0
  6. package/out/phone/assets/{architectureDiagram-5GKGNRK7-1bhpTEFA.js → architectureDiagram-5GKGNRK7-QEXMUvv5.js} +1 -1
  7. package/out/phone/assets/{blockDiagram-I7D4REHJ-Bo9UMudu.js → blockDiagram-I7D4REHJ-FzQ3vEDv.js} +1 -1
  8. package/out/phone/assets/{c4Diagram-7LVT6UL2-YS11cig2.js → c4Diagram-7LVT6UL2-6iRtBvvT.js} +1 -1
  9. package/out/phone/assets/channel-t2MFK_dg.js +1 -0
  10. package/out/phone/assets/{chunk-4HAMMTFA-gA-CzNGD.js → chunk-4HAMMTFA-4eZjiClJ.js} +1 -1
  11. package/out/phone/assets/{chunk-75Z2AOVW-BL_5b1Dw.js → chunk-75Z2AOVW-BTVSMC3k.js} +1 -1
  12. package/out/phone/assets/{chunk-DU6HZSFF-BpNlAs9R.js → chunk-DU6HZSFF-Ca9U1rWL.js} +1 -1
  13. package/out/phone/assets/{chunk-F27PBJKO-lsKx96Nt.js → chunk-F27PBJKO-iUczI4_Q.js} +1 -1
  14. package/out/phone/assets/{chunk-GMAD6QVW-CxbljbtE.js → chunk-GMAD6QVW-DlbCwmvq.js} +1 -1
  15. package/out/phone/assets/{chunk-GVQU2GXP-CTO3kTOF.js → chunk-GVQU2GXP-DlijzCAw.js} +1 -1
  16. package/out/phone/assets/{chunk-IMKFNOWR-Cq8XlkcB.js → chunk-IMKFNOWR-B1BOj8O6.js} +1 -1
  17. package/out/phone/assets/{chunk-L3NEJ4N5-CvIm0JX7.js → chunk-L3NEJ4N5-Fr_w5bRg.js} +1 -1
  18. package/out/phone/assets/{chunk-OSK3NFVY-Cj3ilTL-.js → chunk-OSK3NFVY-CccDEhXi.js} +1 -1
  19. package/out/phone/assets/{chunk-P2QGCYS3-B-twI_Fz.js → chunk-P2QGCYS3-Dn46j2El.js} +1 -1
  20. package/out/phone/assets/{chunk-POPQ4Y6H-lPQttJ5s.js → chunk-POPQ4Y6H-BQchiHrQ.js} +1 -1
  21. package/out/phone/assets/{chunk-PWAF6VOD-DjwqZuIR.js → chunk-PWAF6VOD-BENw9N2v.js} +1 -1
  22. package/out/phone/assets/{chunk-SHT3W25Y-BWRVin1H.js → chunk-SHT3W25Y-C93BlEB0.js} +1 -1
  23. package/out/phone/assets/{chunk-SVP7TREG-CGLhvnsS.js → chunk-SVP7TREG-wfL37BUq.js} +1 -1
  24. package/out/phone/assets/{chunk-TICWLB2K-DkFUa03q.js → chunk-TICWLB2K-C9-wZ6kk.js} +1 -1
  25. package/out/phone/assets/classDiagram-ZZMXUADV-CM29lfur.js +1 -0
  26. package/out/phone/assets/classDiagram-v2-VYDZK3BY-CM29lfur.js +1 -0
  27. package/out/phone/assets/{codeHighlighter-jQti-W31.js → codeHighlighter-DQ-g-VWX.js} +1 -1
  28. package/out/phone/assets/{cynefin-OW5HDTMX-L8oWVu5S.js → cynefin-OW5HDTMX-DamvwfM9.js} +1 -1
  29. package/out/phone/assets/{cynefinDiagram-5FMLGOSQ-DH8-4p4N.js → cynefinDiagram-5FMLGOSQ-Coz1le1N.js} +1 -1
  30. package/out/phone/assets/{dagre-GXQ25YYZ-HhLDmcu9.js → dagre-GXQ25YYZ-ByJC9Z6k.js} +1 -1
  31. package/out/phone/assets/desk-XkzvZXuU.js +70 -0
  32. package/out/phone/assets/{diagram-S7CK7UJ4-CeIbR3Ir.js → diagram-S7CK7UJ4-BabBefXt.js} +1 -1
  33. package/out/phone/assets/{diagram-UQ7AKVKN-BQ84Qnq6.js → diagram-UQ7AKVKN-DEX56Otl.js} +1 -1
  34. package/out/phone/assets/{diagram-VSXAHHWV-aF_J57fD.js → diagram-VSXAHHWV-GeNN1ZwW.js} +1 -1
  35. package/out/phone/assets/{diagram-VX7I27RA-Bg1ZqM4Y.js → diagram-VX7I27RA-DkclPqXj.js} +1 -1
  36. package/out/phone/assets/{diagram-Z3DM3KII-DjTkPAqa.js → diagram-Z3DM3KII-CDKrxb7_.js} +1 -1
  37. package/out/phone/assets/{ebnfDiagram-PWID7BFC-DPsH5Eky.js → ebnfDiagram-PWID7BFC-B-lRq0nU.js} +1 -1
  38. package/out/phone/assets/{erDiagram-RLTQ6QDP-ExvY7e6T.js → erDiagram-RLTQ6QDP-2PdYpZdI.js} +1 -1
  39. package/out/phone/assets/eventmodeling-NTZA5JFV-DBO84WXk.js +1 -0
  40. package/out/phone/assets/flowDiagram-HODETNUW-89Bcp6BV.js +1 -0
  41. package/out/phone/assets/{ganttDiagram-EL5Y4UJY-hCe06ucl.js → ganttDiagram-EL5Y4UJY-XG84VKNq.js} +1 -1
  42. package/out/phone/assets/{gitGraph-4MIJSDKK-BuZ6lDat.js → gitGraph-4MIJSDKK-BqrA_WVv.js} +1 -1
  43. package/out/phone/assets/{gitGraphDiagram-WWUBYQGX-D-8aVxvj.js → gitGraphDiagram-WWUBYQGX-BAIxr-mN.js} +1 -1
  44. package/out/phone/assets/{info-A6RAGUB7-CrZtdoYs.js → info-A6RAGUB7-DE-jKSbG.js} +1 -1
  45. package/out/phone/assets/{infoDiagram-27XIBGKW-BLRFHxtO.js → infoDiagram-27XIBGKW-BSTxH5Al.js} +1 -1
  46. package/out/phone/assets/{ishikawaDiagram-5VMMS53U-D7SYWKoj.js → ishikawaDiagram-5VMMS53U-zOO97Npq.js} +1 -1
  47. package/out/phone/assets/{journeyDiagram-3NMN7TZE-BPsg7CQD.js → journeyDiagram-3NMN7TZE-dSMVlg_5.js} +1 -1
  48. package/out/phone/assets/{kanban-definition-UXKFOSKX-CbPuNr-E.js → kanban-definition-UXKFOSKX-DHok-qdM.js} +1 -1
  49. package/out/phone/assets/{line-CkpKMiqK.js → line-C5TJMvf6.js} +1 -1
  50. package/out/phone/assets/main-Bk2Gcz5l.css +2 -0
  51. package/out/phone/assets/main-DNK2uR8l.js +277 -0
  52. package/out/phone/assets/{mermaid-parser.core-RTq_mEm1.js → mermaid-parser.core-CrJ82mWd.js} +3 -3
  53. package/out/phone/assets/{mermaid.core-D9LtIKua.js → mermaid.core-CkfKqc8K.js} +4 -4
  54. package/out/phone/assets/{mindmap-definition-YA3MSWOX-8cGgRiRD.js → mindmap-definition-YA3MSWOX-DD-W0NPL.js} +1 -1
  55. package/out/phone/assets/{packet-AYTQ26CC-D9-eSn0v.js → packet-AYTQ26CC-DEZk6B2e.js} +1 -1
  56. package/out/phone/assets/{pegDiagram-XKGWAZYB-DztU_rIE.js → pegDiagram-XKGWAZYB-KND-JwT0.js} +1 -1
  57. package/out/phone/assets/{pie-WAS4IAKB-Bk2Tqaq_.js → pie-WAS4IAKB-DS5oCOdm.js} +1 -1
  58. package/out/phone/assets/{pieDiagram-E7YTZNPT-Dm_3mJ9_.js → pieDiagram-E7YTZNPT-CfWh8T4Z.js} +1 -1
  59. package/out/phone/assets/{quadrantDiagram-AXDQQJYC-lKskzjzu.js → quadrantDiagram-AXDQQJYC-CbquaKYM.js} +1 -1
  60. package/out/phone/assets/{radar-RG4KPBEZ-B2z8Txd8.js → radar-RG4KPBEZ-C0kqKhsd.js} +1 -1
  61. package/out/phone/assets/{railroad-74A4TZTK-11VmdALq.js → railroad-74A4TZTK-C5WV19mk.js} +1 -1
  62. package/out/phone/assets/railroad-abnf-HS5TGJTU-BqkB5NuR.js +1 -0
  63. package/out/phone/assets/railroad-ebnf-LZEXJU2U-DF9ncZF9.js +1 -0
  64. package/out/phone/assets/railroad-peg-WCYAUIDC-CrvTMEVw.js +1 -0
  65. package/out/phone/assets/{railroadDiagram-O6MQD6OU-Dr0NTIA6.js → railroadDiagram-O6MQD6OU-CmkCOdfu.js} +1 -1
  66. package/out/phone/assets/{requirementDiagram-BXWQKSXE-C0W6h_5I.js → requirementDiagram-BXWQKSXE-CrQKPUwx.js} +1 -1
  67. package/out/phone/assets/{sankeyDiagram-P5KCCOFB-CVJDathY.js → sankeyDiagram-P5KCCOFB-CBCG-Eyn.js} +1 -1
  68. package/out/phone/assets/{sequenceDiagram-WJ2MYXX4-BxHQTG6x.js → sequenceDiagram-WJ2MYXX4-D9oVD380.js} +1 -1
  69. package/out/phone/assets/shellUpdate-2rxcUhg5.js +5 -0
  70. package/out/phone/assets/{stateDiagram-D77RDMKH-BO5MAjhs.js → stateDiagram-D77RDMKH-VNnCDAvS.js} +1 -1
  71. package/out/phone/assets/stateDiagram-v2-MP3YSRHH-Qadztnwb.js +1 -0
  72. package/out/phone/assets/{swimlanes-42K2YHIH-DnhDPyy6.js → swimlanes-42K2YHIH-DFtKlQwi.js} +1 -1
  73. package/out/phone/assets/swimlanesDiagram-VR7AAH4N-BG4PsK7t.js +8 -0
  74. package/out/phone/assets/{timeline-definition-24CTP7MA-bLEjS7re.js → timeline-definition-24CTP7MA-BwrAy7Qu.js} +1 -1
  75. package/out/phone/assets/{treeView-Q6P3EWNA-Ci-sA9wK.js → treeView-Q6P3EWNA-BLyQtiYC.js} +1 -1
  76. package/out/phone/assets/{treemap-WGGIJYW6-BXCjzK65.js → treemap-WGGIJYW6-gub1bjDX.js} +1 -1
  77. package/out/phone/assets/{vennDiagram-4TSXK5OY-DHsj5dRx.js → vennDiagram-4TSXK5OY-DayfmvoI.js} +1 -1
  78. package/out/phone/assets/{wardley-WFR3VGLG-d8TdCu-H.js → wardley-WFR3VGLG-B5_pluIE.js} +1 -1
  79. package/out/phone/assets/{wardleyDiagram-VM6X3IG4-DQFVP9qu.js → wardleyDiagram-VM6X3IG4-CHS5ryk0.js} +1 -1
  80. package/out/phone/assets/{xychartDiagram-S5SC5T6Z-Dni2Y0ov.js → xychartDiagram-S5SC5T6Z-C21zSdz1.js} +1 -1
  81. package/out/phone/desk.html +3 -3
  82. package/out/phone/index.html +4 -4
  83. package/out/phone/sw.js +2 -2
  84. package/out/renderer/assets/EditDiff-DJaW24DH.js +1 -0
  85. package/out/renderer/assets/ReadFileView-B1RfgY1_.js +4 -0
  86. package/out/renderer/assets/SidePanel-CXOSOIj_.js +48 -0
  87. package/out/renderer/assets/{SidePanel-D0m4IYxS.css → SidePanel-DN2RL6QD.css} +1 -1
  88. package/out/renderer/assets/abnfDiagram-VCTEODGH-DteC7eOG.js +1 -0
  89. package/out/renderer/assets/{arc-B8im8n0O.js → arc-BafilblL.js} +1 -1
  90. package/out/renderer/assets/{architectureDiagram-5GKGNRK7-BRSi5FBk.js → architectureDiagram-5GKGNRK7-BXxAIsNI.js} +2 -2
  91. package/out/renderer/assets/{blockDiagram-I7D4REHJ-CQ1wirIl.js → blockDiagram-I7D4REHJ-Bt4I5z76.js} +1 -1
  92. package/out/renderer/assets/{c4Diagram-7LVT6UL2-9HyLIioe.js → c4Diagram-7LVT6UL2-Dg1rhQSn.js} +1 -1
  93. package/out/renderer/assets/channel-CpN2DlDo.js +1 -0
  94. package/out/renderer/assets/{chunk-2Q5K7J3B-BwC9g3bx.js → chunk-2Q5K7J3B-Bea4O-pP.js} +1 -1
  95. package/out/renderer/assets/{chunk-5VM5RSS4-DMtgxPBL.js → chunk-5VM5RSS4-9g4O6TgX.js} +1 -1
  96. package/out/renderer/assets/{chunk-F27PBJKO-DSi_XV5v.js → chunk-F27PBJKO-CQFAhmZp.js} +1 -1
  97. package/out/renderer/assets/{chunk-IMKFNOWR-Dctc6Apj.js → chunk-IMKFNOWR-DZKvnXil.js} +1 -1
  98. package/out/renderer/assets/{chunk-JWPE2WC7-I2BD5qM7.js → chunk-JWPE2WC7-UkNkhirX.js} +1 -1
  99. package/out/renderer/assets/{chunk-POPQ4Y6H-k60pc4eT.js → chunk-POPQ4Y6H-D3CSUp94.js} +1 -1
  100. package/out/renderer/assets/{chunk-SVP7TREG-zCGemfqm.js → chunk-SVP7TREG-F3dgPzel.js} +1 -1
  101. package/out/renderer/assets/{chunk-TICWLB2K-CdDiHIq-.js → chunk-TICWLB2K-URu59zvj.js} +1 -1
  102. package/out/renderer/assets/{chunk-XXDRQBXY-GYVDxVfN.js → chunk-XXDRQBXY-DRFxCPER.js} +1 -1
  103. package/out/renderer/assets/classDiagram-ZZMXUADV-D-KG_eK-.js +1 -0
  104. package/out/renderer/assets/classDiagram-v2-VYDZK3BY-D-KG_eK-.js +1 -0
  105. package/out/renderer/assets/cose-bilkent-JH36ORCC-Bx5VqEhK.js +1 -0
  106. package/out/renderer/assets/{cynefin-OW5HDTMX-DnQaS9VN.js → cynefin-OW5HDTMX-YKYl0dFh.js} +1 -1
  107. package/out/renderer/assets/cynefinDiagram-5FMLGOSQ-DaHqCls4.js +62 -0
  108. package/out/renderer/assets/{dagre-GXQ25YYZ-fG1vMsyn.js → dagre-GXQ25YYZ-CRqSls6Q.js} +1 -1
  109. package/out/renderer/assets/{diagram-S7CK7UJ4-BcfAFVc2.js → diagram-S7CK7UJ4-_oJhPbvH.js} +1 -1
  110. package/out/renderer/assets/diagram-UQ7AKVKN-B7P-4UYL.js +41 -0
  111. package/out/renderer/assets/{diagram-VSXAHHWV-B-U9CIWt.js → diagram-VSXAHHWV--0uBugR7.js} +1 -1
  112. package/out/renderer/assets/diagram-VX7I27RA-IaMWXRBT.js +24 -0
  113. package/out/renderer/assets/diagram-Z3DM3KII-BLCY3C4h.js +24 -0
  114. package/out/renderer/assets/ebnfDiagram-PWID7BFC-CUYHhexz.js +1 -0
  115. package/out/renderer/assets/{erDiagram-RLTQ6QDP-CfMNvEoW.js → erDiagram-RLTQ6QDP-BIOsECZV.js} +1 -1
  116. package/out/renderer/assets/{flowDiagram-HODETNUW-C8XM3p4T.js → flowDiagram-HODETNUW-DjggEdce.js} +1 -1
  117. package/out/renderer/assets/ganttDiagram-EL5Y4UJY-Dik61bQB.js +292 -0
  118. package/out/renderer/assets/gitGraphDiagram-WWUBYQGX-BrPFNa7W.js +106 -0
  119. package/out/renderer/assets/index-CtOLwaEJ.css +1 -0
  120. package/out/renderer/assets/index-mVE4g58q.js +3003 -0
  121. package/out/renderer/assets/infoDiagram-27XIBGKW-ZfCvFQE5.js +2 -0
  122. package/out/renderer/assets/{ishikawaDiagram-5VMMS53U-mUoXchkB.js → ishikawaDiagram-5VMMS53U-BhteuTmM.js} +1 -1
  123. package/out/renderer/assets/{journeyDiagram-3NMN7TZE-zzLL0HFW.js → journeyDiagram-3NMN7TZE-BJyr-G3R.js} +1 -1
  124. package/out/renderer/assets/{kanban-definition-UXKFOSKX-BJ_9aIhB.js → kanban-definition-UXKFOSKX-CJyl9IUl.js} +1 -1
  125. package/out/renderer/assets/{layout-3SRMHY7n.js → layout-oTkojEy1.js} +1 -1
  126. package/out/renderer/assets/{linear-CWpclK_R.js → linear-qICDecPr.js} +1 -1
  127. package/out/renderer/assets/{mermaid.core-DORpmVi3.js → mermaid.core-F0flUThf.js} +5 -5
  128. package/out/renderer/assets/{mindmap-definition-YA3MSWOX-CYBlCqIB.js → mindmap-definition-YA3MSWOX-pG7PXlKk.js} +1 -1
  129. package/out/renderer/assets/pegDiagram-XKGWAZYB-CwO9p66t.js +1 -0
  130. package/out/renderer/assets/{pieDiagram-E7YTZNPT-Bzpc57-A.js → pieDiagram-E7YTZNPT-BpqTKO7A.js} +1 -1
  131. package/out/renderer/assets/{quadrantDiagram-AXDQQJYC-spKXEbds.js → quadrantDiagram-AXDQQJYC-Ci1QOcG6.js} +1 -1
  132. package/out/renderer/assets/railroadDiagram-O6MQD6OU-Be-ymk25.js +1 -0
  133. package/out/renderer/assets/{requirementDiagram-BXWQKSXE-CX-Dqij_.js → requirementDiagram-BXWQKSXE-Dotur23i.js} +1 -1
  134. package/out/renderer/assets/{sankeyDiagram-P5KCCOFB-Bgx1W6B9.js → sankeyDiagram-P5KCCOFB-BlTTRpKU.js} +1 -1
  135. package/out/renderer/assets/{sequenceDiagram-WJ2MYXX4-CKQv6pcU.js → sequenceDiagram-WJ2MYXX4-C_llXVvH.js} +1 -1
  136. package/out/renderer/assets/{sessionChanges-BLzNhRuv.js → sessionChanges-BpPkx6v0.js} +5 -5
  137. package/out/renderer/assets/sizeCapture-INFHLROL-xhuCXQI9.js +1 -0
  138. package/out/renderer/assets/stateDiagram-D77RDMKH-BfESnkCR.js +1 -0
  139. package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-C7QWw0La.js +1 -0
  140. package/out/renderer/assets/swimlanes-42K2YHIH-DX8_KJTt.js +1 -0
  141. package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-B7JGQCYf.js +8 -0
  142. package/out/renderer/assets/{timeline-definition-24CTP7MA-CsZAMmMZ.js → timeline-definition-24CTP7MA-DIoNEHAB.js} +1 -1
  143. package/out/renderer/assets/{vennDiagram-4TSXK5OY-COQ7L1f7.js → vennDiagram-4TSXK5OY-KrS4uyWo.js} +1 -1
  144. package/out/renderer/assets/{wardleyDiagram-VM6X3IG4-dqMWLTCs.js → wardleyDiagram-VM6X3IG4-D4i6zXyf.js} +1 -1
  145. package/out/renderer/assets/{xychartDiagram-S5SC5T6Z-DX4clIYP.js → xychartDiagram-S5SC5T6Z-DpCpSTPN.js} +1 -1
  146. package/out/renderer/index.html +2 -3
  147. package/out/renderer/web-preload.js +1 -51
  148. package/out/server/agent.js +1413 -307
  149. package/out/server/chunks/agentConstants-D4t7d6iS.js +9 -0
  150. package/out/server/chunks/builtinOccupancy-zo5-z-s5.js +93 -0
  151. package/out/server/chunks/dispatchModel-D7papgSj.js +76 -0
  152. package/out/server/chunks/{gpuBackendInstall-jAzoFq7U.js → gpuBackendInstall-xFEdr70P.js} +2 -2
  153. package/out/server/chunks/killTree-T-p6Lr3w.js +787 -0
  154. package/out/server/chunks/{loadProvider-NdOVbsHi.js → loadProvider-ChfeR5km.js} +2 -2
  155. package/out/server/chunks/{manifest-BPXFscqI.js → manifest-CmnE8RBt.js} +4 -2
  156. package/out/server/chunks/menuSkills-DC4qs2MC.js +54 -0
  157. package/out/server/chunks/projectCode-BAgpkYYS.js +112 -0
  158. package/out/server/chunks/{registry-BhoHPSKn.js → registry-G4AKEQtl.js} +98 -116
  159. package/out/server/chunks/sendImage-BmenO8Vx.js +646 -0
  160. package/out/server/chunks/{sendImage-BCNW9JRV.js → toolParams-0GakTs9V.js} +25 -234
  161. package/out/server/chunks/web-9MujZLkq.js +7787 -0
  162. package/out/server/chunks/{workflowPresets-C2T1BzA2.js → workflowPresets-CTv2r-Sh.js} +13659 -15598
  163. package/out/server/index.js +10281 -3781
  164. package/out/server/memory-service.js +205 -148
  165. package/out/server/plugin-host.js +44 -18
  166. package/package.json +1 -1
  167. package/out/phone/assets/architecture-7GRP2DOG-Duql1LsL.js +0 -1
  168. package/out/phone/assets/channel-BPoIHov1.js +0 -1
  169. package/out/phone/assets/classDiagram-ZZMXUADV-CIR76lHP.js +0 -1
  170. package/out/phone/assets/classDiagram-v2-VYDZK3BY-CIR76lHP.js +0 -1
  171. package/out/phone/assets/desk-CixRGdTk.js +0 -52
  172. package/out/phone/assets/eventmodeling-NTZA5JFV-DYp-zWcL.js +0 -1
  173. package/out/phone/assets/flowDiagram-HODETNUW-CIU32By5.js +0 -1
  174. package/out/phone/assets/main-BCnf7dVM.js +0 -264
  175. package/out/phone/assets/main-nqB-uD3v.css +0 -2
  176. package/out/phone/assets/railroad-abnf-HS5TGJTU-BkSycwye.js +0 -1
  177. package/out/phone/assets/railroad-ebnf-LZEXJU2U-BsPIU3iV.js +0 -1
  178. package/out/phone/assets/railroad-peg-WCYAUIDC-Cy8G7u5C.js +0 -1
  179. package/out/phone/assets/shellUpdate-DPSfgHG3.js +0 -36
  180. package/out/phone/assets/stateDiagram-v2-MP3YSRHH-B8IHc2bm.js +0 -1
  181. package/out/phone/assets/swimlanesDiagram-VR7AAH4N-dmSDAN2F.js +0 -8
  182. package/out/renderer/assets/EditDiff-DxxLuCEI.js +0 -1
  183. package/out/renderer/assets/File-Tz3MUtN6.js +0 -1
  184. package/out/renderer/assets/ReadFileView-DFoLPU04.js +0 -4
  185. package/out/renderer/assets/SidePanel-CL40W2RY.js +0 -47
  186. package/out/renderer/assets/Virtualizer-B0uwx_XV.js +0 -1345
  187. package/out/renderer/assets/abnfDiagram-VCTEODGH-CJ9nn9eH.js +0 -1
  188. package/out/renderer/assets/channel-DjB0ww6b.js +0 -1
  189. package/out/renderer/assets/classDiagram-ZZMXUADV-6SiAw1np.js +0 -1
  190. package/out/renderer/assets/classDiagram-v2-VYDZK3BY-6SiAw1np.js +0 -1
  191. package/out/renderer/assets/cose-bilkent-JH36ORCC-BnSAtUh-.js +0 -1
  192. package/out/renderer/assets/cynefinDiagram-5FMLGOSQ-BNQdw0PV.js +0 -62
  193. package/out/renderer/assets/cytoscape-fcose-CzkrRInm.js +0 -1
  194. package/out/renderer/assets/cytoscape.esm-DzSz-X2X.js +0 -321
  195. package/out/renderer/assets/diagram-UQ7AKVKN-D8f3Tsx9.js +0 -41
  196. package/out/renderer/assets/diagram-VX7I27RA-CX6ifTkJ.js +0 -24
  197. package/out/renderer/assets/diagram-Z3DM3KII-49dS9s3L.js +0 -24
  198. package/out/renderer/assets/ebnfDiagram-PWID7BFC-CraGJRI7.js +0 -1
  199. package/out/renderer/assets/ganttDiagram-EL5Y4UJY-DlJBMKFX.js +0 -292
  200. package/out/renderer/assets/gitGraphDiagram-WWUBYQGX-DvEzDsKF.js +0 -106
  201. package/out/renderer/assets/globals-BFf1P-Y5.js +0 -715
  202. package/out/renderer/assets/globals-DUBhAVpU.css +0 -1
  203. package/out/renderer/assets/index-L4TTIP10.js +0 -89
  204. package/out/renderer/assets/infoDiagram-27XIBGKW-CckfBO-R.js +0 -2
  205. package/out/renderer/assets/manifest-DOzTaB8J.js +0 -525
  206. package/out/renderer/assets/pegDiagram-XKGWAZYB-DhWwLs4v.js +0 -1
  207. package/out/renderer/assets/railroadDiagram-O6MQD6OU-Br553px3.js +0 -1
  208. package/out/renderer/assets/settings-Bsrw4ERp.js +0 -25
  209. package/out/renderer/assets/sizeCapture-INFHLROL-DtRedfRe.js +0 -1
  210. package/out/renderer/assets/stateDiagram-D77RDMKH-CMP5owem.js +0 -1
  211. package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-6-731AqJ.js +0 -1
  212. package/out/renderer/assets/swimlanes-42K2YHIH-D30AvvmW.js +0 -1
  213. package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-B8KijqIT.js +0 -8
  214. package/out/renderer/settings.html +0 -23
  215. package/out/server/chunks/agent-BbNq8i9j.js +0 -4241
  216. package/out/server/chunks/dispatchModel-CsfmL396.js +0 -20
@@ -1,4241 +0,0 @@
1
- import { parse, stringify } from "yaml";
2
- const APPROVAL_ALLOW_THRESHOLDS = [0.85, 0.9, 0.95];
3
- const DEFAULT_APPROVAL_ALLOW_THRESHOLD = 0.9;
4
- function isApprovalAllowThreshold(value) {
5
- return APPROVAL_ALLOW_THRESHOLDS.includes(value);
6
- }
7
- function parseApprovalAllowThreshold(value) {
8
- return isApprovalAllowThreshold(value) ? value : DEFAULT_APPROVAL_ALLOW_THRESHOLD;
9
- }
10
- const APPROVAL_REVIEW_REASONS = [
11
- "read_only",
12
- "regenerable",
13
- "reversible_workspace_change",
14
- "data_loss",
15
- "system_state",
16
- "exfiltration",
17
- "unclear_target"
18
- ];
19
- const APPROVAL_REVIEW_FALLBACKS = [
20
- "timeout",
21
- "error",
22
- "invalid"
23
- ];
24
- const MODEL_MAX = 200;
25
- function isApprovalReviewReason(value) {
26
- return APPROVAL_REVIEW_REASONS.includes(value);
27
- }
28
- function isProbability(value) {
29
- return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
30
- }
31
- function parseApprovalReviewRecord(value) {
32
- if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
33
- const { verdict, model, allow, ask, block, reason } = value;
34
- if (verdict !== "allow" && verdict !== "deny" || typeof model !== "string" || !model || model.length > MODEL_MAX || !isProbability(allow) || !isProbability(ask) || !isProbability(block) || reason !== void 0 && !isApprovalReviewReason(reason))
35
- return void 0;
36
- return { verdict, model, allow, ask, block, ...reason ? { reason } : {} };
37
- }
38
- const UNLIMITED_AUTO_RETRY = -1;
39
- const DEFAULT_AUTO_RETRY_LIMIT = 3;
40
- const MAX_AUTO_RETRY_LIMIT = 100;
41
- function parseAutoRetryLimit(value) {
42
- if (typeof value !== "number" || !Number.isInteger(value)) return null;
43
- return value >= UNLIMITED_AUTO_RETRY && value <= MAX_AUTO_RETRY_LIMIT ? value : null;
44
- }
45
- function normalizeAutoRetryLimit(value) {
46
- return parseAutoRetryLimit(value) ?? DEFAULT_AUTO_RETRY_LIMIT;
47
- }
48
- function autoRetryOverrides(limit) {
49
- if (limit === 0) return { enabled: false, maxRetries: 0 };
50
- return {
51
- enabled: true,
52
- maxRetries: limit === UNLIMITED_AUTO_RETRY ? Number.POSITIVE_INFINITY : limit
53
- };
54
- }
55
- const MCP_TRANSPORTS = ["stdio", "http", "sse"];
56
- const DEFAULT_PRESET_ID = "default";
57
- const BUILTIN_AGENT_TYPES = [
58
- {
59
- name: "scout",
60
- description: "Fast read-only recon; returns compressed findings",
61
- systemPrompt: "You are a fast reconnaissance agent. Read and search only — never modify files or run commands with side effects. Return a compact, well-structured report of findings with concrete file paths.",
62
- tools: "readonly",
63
- modelMode: "agent_pick"
64
- },
65
- {
66
- name: "worker",
67
- description: "Implements a self-contained coding subtask end to end",
68
- systemPrompt: "You are an implementation agent. Complete the assigned coding subtask end to end: read the relevant code, make the changes, and verify them (typecheck/tests where available). Report what you changed and any follow-ups.",
69
- tools: "all",
70
- modelMode: "agent_pick"
71
- },
72
- {
73
- name: "reviewer",
74
- description: "Reviews code or diffs; read-only, returns prioritized issues",
75
- systemPrompt: "You are a code review agent. Read the relevant code or diff and return a prioritized list of concrete issues (correctness first), each with file:line and a suggested fix. Do not modify anything.",
76
- tools: "readonly",
77
- modelMode: "agent_pick"
78
- },
79
- {
80
- name: "tester",
81
- description: "Writes failing tests first (TDD RED); can only write test files, never implementation",
82
- systemPrompt: "You are a test-first author. Write failing tests that pin down the contract described in the task, run them and confirm each fails because the behavior is missing (not because of a typo). Never write or edit implementation files — only test files (the toolset enforces this). Read specs, type contracts and existing tests; avoid reading the implementation body of the module under test so the tests stay independent of it. Do only the slice in this turn — do not expand to adjacent modules or the rest of the PRD. After the slice is red for the right reason, stop and wait for the parent to send the next slice or a green audit. Report the test files, case counts, and the exact failure reasons.",
83
- tools: "all",
84
- writeScope: ["**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx", "test/**"],
85
- modelMode: "agent_pick"
86
- }
87
- ];
88
- const LEGACY_ENSO_TYPE_KEY = "agent:enso";
89
- const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
90
- const BUILTIN_NAME_PATTERN = /^[a-z][a-z0-9_-]*$/;
91
- const RESERVED_AGENT_NAMES = {
92
- enso: true,
93
- [LEGACY_ENSO_TYPE_KEY]: true,
94
- "enso-locked-v1": true,
95
- "enso-system-v1": true
96
- };
97
- const RESERVED_AGENT_PREFIXES = [
98
- "agent:",
99
- "builtin:",
100
- "custom:",
101
- "builtin-agent:",
102
- "bot:"
103
- ];
104
- function isUuid(value) {
105
- return typeof value === "string" && UUID_PATTERN.test(value);
106
- }
107
- function normalizeAgentTypeName(value) {
108
- return value.normalize("NFKC").trim().toLocaleLowerCase("en-US");
109
- }
110
- function isReservedAgentTypeName(value) {
111
- const normalized = normalizeAgentTypeName(value);
112
- return !normalized || Object.hasOwn(RESERVED_AGENT_NAMES, normalized) || RESERVED_AGENT_PREFIXES.some((prefix) => normalized.startsWith(prefix));
113
- }
114
- function isValidLegacyProfile(typeKey, profileId) {
115
- return typeKey === LEGACY_ENSO_TYPE_KEY ? profileId === "enso-locked-v1" : profileId === void 0;
116
- }
117
- function parseAgentTypeKey(value) {
118
- if (value === LEGACY_ENSO_TYPE_KEY) return LEGACY_ENSO_TYPE_KEY;
119
- if (typeof value !== "string") return null;
120
- if (value.startsWith("builtin:")) {
121
- const name = value.slice("builtin:".length);
122
- return BUILTIN_NAME_PATTERN.test(name) && name !== "general" && name !== "enso" ? value : null;
123
- }
124
- if (value.startsWith("custom:")) {
125
- return isUuid(value.slice("custom:".length)) ? value : null;
126
- }
127
- if (value.startsWith("bot:")) {
128
- return isUuid(value.slice("bot:".length)) ? value : null;
129
- }
130
- return null;
131
- }
132
- function parseSessionIdentity(value) {
133
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
134
- const identity = value;
135
- if (Object.keys(identity).length !== 2 || typeof identity.sessionId !== "string" || !identity.sessionId || !isUuid(identity.generation)) {
136
- return null;
137
- }
138
- return { sessionId: identity.sessionId, generation: identity.generation };
139
- }
140
- function parseChildSessionIdentity(value) {
141
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
142
- const identity = value;
143
- const allowed = [
144
- "sessionId",
145
- "generation",
146
- "parent",
147
- "instanceId",
148
- "instanceName",
149
- "typeKey",
150
- "profileId"
151
- ];
152
- if (Object.keys(identity).length < 6 || Object.keys(identity).some((key) => !allowed.includes(key))) {
153
- return null;
154
- }
155
- const own = parseSessionIdentity({
156
- sessionId: identity.sessionId,
157
- generation: identity.generation
158
- });
159
- const parent = parseSessionIdentity(identity.parent);
160
- const typeKey = parseAgentTypeKey(identity.typeKey);
161
- if (!own || !parent || !isUuid(identity.instanceId) || typeof identity.instanceName !== "string" || !identity.instanceName || !typeKey || own.sessionId === parent.sessionId || own.generation === parent.generation || !isValidLegacyProfile(typeKey, identity.profileId)) {
162
- return null;
163
- }
164
- return identity;
165
- }
166
- function isSameChildSessionIdentity(expected, value) {
167
- const actual = parseChildSessionIdentity(value);
168
- return actual !== null && actual.sessionId === expected.sessionId && actual.generation === expected.generation && actual.parent.sessionId === expected.parent.sessionId && actual.parent.generation === expected.parent.generation && actual.instanceId === expected.instanceId && actual.typeKey === expected.typeKey && actual.profileId === expected.profileId;
169
- }
170
- function visibleMemberAgentTypes(members, customAgentTypes) {
171
- const taken = new Set(
172
- [...BUILTIN_AGENT_TYPES, ...customAgentTypes].map((entry) => normalizeAgentTypeName(entry.name))
173
- );
174
- return members.filter((member) => {
175
- const name = normalizeAgentTypeName(member.name);
176
- if (!isUuid(member.id) || isReservedAgentTypeName(name) || taken.has(name)) return false;
177
- taken.add(name);
178
- return true;
179
- });
180
- }
181
- function buildAgentTypeRegistrySnapshot(input) {
182
- const disabled = new Set(input.disabledBuiltinAgentTypes);
183
- const overriddenNames = new Set(
184
- input.customAgentTypes.filter((entry) => isUuid(entry.id) && !isReservedAgentTypeName(entry.name)).map((entry) => entry.name.trim().toLowerCase())
185
- );
186
- const candidates = [];
187
- for (const builtin of BUILTIN_AGENT_TYPES) {
188
- if (builtin.name === "general" || builtin.name === "enso" || disabled.has(builtin.name) || overriddenNames.has(builtin.name)) {
189
- continue;
190
- }
191
- candidates.push({
192
- typeKey: `builtin:${builtin.name}`,
193
- displayName: builtin.name,
194
- description: builtin.description,
195
- source: "builtin",
196
- locked: false,
197
- canDisable: true,
198
- canEdit: false
199
- });
200
- }
201
- for (const custom of input.customAgentTypes) {
202
- if (!isUuid(custom.id) || isReservedAgentTypeName(custom.name)) continue;
203
- candidates.push({
204
- typeKey: `custom:${custom.id}`,
205
- displayName: custom.name.trim(),
206
- description: custom.description,
207
- source: "custom",
208
- locked: false,
209
- canDisable: false,
210
- canEdit: true
211
- });
212
- }
213
- for (const member of visibleMemberAgentTypes(input.members ?? [], input.customAgentTypes)) {
214
- candidates.push({
215
- typeKey: `bot:${member.id}`,
216
- displayName: member.name.trim(),
217
- description: member.description,
218
- source: "bot",
219
- locked: false,
220
- canDisable: false,
221
- canEdit: false
222
- });
223
- }
224
- return { revision: input.revision, candidates };
225
- }
226
- const PRODUCT_SURFACE_INVENTORY = {
227
- "general.language": { domain: "general", kind: "setting", label: "Language" },
228
- "general.load-local-skills": {
229
- domain: "general",
230
- kind: "setting",
231
- label: "Load local skills"
232
- },
233
- "general.load-harness-assets": {
234
- domain: "general",
235
- kind: "setting",
236
- label: "Load project harness assets"
237
- },
238
- "general.windows-local-shell": {
239
- domain: "general",
240
- kind: "setting",
241
- label: "Windows local command shell"
242
- },
243
- "general.terminal-shell": {
244
- domain: "general",
245
- kind: "setting",
246
- label: "Terminal shell"
247
- },
248
- "general.worktree-root": {
249
- domain: "general",
250
- kind: "setting",
251
- label: "Worktree root directory"
252
- },
253
- "general.automatic-updates": {
254
- domain: "general",
255
- kind: "setting",
256
- label: "Automatic updates"
257
- },
258
- "general.proxy-mode": { domain: "general", kind: "setting", label: "Proxy mode" },
259
- "general.custom-proxy-url": { domain: "general", kind: "setting", label: "Custom proxy URL" },
260
- "general.keybindings.list": { domain: "general", kind: "action", label: "List keybindings" },
261
- "general.keybindings.set": { domain: "general", kind: "setting", label: "Set keybinding" },
262
- "general.keybindings.reset": { domain: "general", kind: "setting", label: "Reset keybinding" },
263
- "appearance.theme": { domain: "appearance", kind: "setting", label: "Application theme" },
264
- "appearance.accent": { domain: "appearance", kind: "setting", label: "Accent color" },
265
- "appearance.terminal-theme": {
266
- domain: "appearance",
267
- kind: "setting",
268
- label: "Terminal theme"
269
- },
270
- "appearance.terminal-font-size": {
271
- domain: "appearance",
272
- kind: "setting",
273
- label: "Terminal font size"
274
- },
275
- "appearance.terminal-font-family": {
276
- domain: "appearance",
277
- kind: "setting",
278
- label: "Terminal font family"
279
- },
280
- "appearance.terminal-font-weight": {
281
- domain: "appearance",
282
- kind: "setting",
283
- label: "Terminal font weight"
284
- },
285
- "appearance.terminal-bold-weight": {
286
- domain: "appearance",
287
- kind: "setting",
288
- label: "Terminal bold font weight"
289
- },
290
- "appearance.favorite-terminal-themes": {
291
- domain: "appearance",
292
- kind: "setting",
293
- label: "Favorite terminal themes"
294
- },
295
- "appearance.status-line-segments": {
296
- domain: "appearance",
297
- kind: "setting",
298
- label: "Status line segments"
299
- },
300
- "providers.list": { domain: "providers", kind: "action", label: "List model providers" },
301
- "providers.import-local": {
302
- domain: "providers",
303
- kind: "action",
304
- label: "Import providers from local apps"
305
- },
306
- "providers.add": { domain: "providers", kind: "action", label: "Add model provider" },
307
- "providers.update": { domain: "providers", kind: "setting", label: "Edit model provider" },
308
- "providers.remove": { domain: "providers", kind: "action", label: "Remove model provider" },
309
- "providers.fetch-models": {
310
- domain: "providers",
311
- kind: "action",
312
- label: "Fetch provider models"
313
- },
314
- "providers.test-connection": {
315
- domain: "providers",
316
- kind: "action",
317
- label: "Test provider connection"
318
- },
319
- "providers.model-meta": { domain: "providers", kind: "action", label: "Read model metadata" },
320
- "providers.toggle-provider": {
321
- domain: "providers",
322
- kind: "setting",
323
- label: "Enable or disable provider"
324
- },
325
- "providers.toggle-model": {
326
- domain: "providers",
327
- kind: "setting",
328
- label: "Enable or disable model"
329
- },
330
- "providers.default-model": {
331
- domain: "providers",
332
- kind: "setting",
333
- label: "Set global default model"
334
- },
335
- "providers.subagent-models": {
336
- domain: "providers",
337
- kind: "setting",
338
- label: "Models the agent may pick for subagents"
339
- },
340
- "providers.subagent-models.toggle": {
341
- domain: "providers",
342
- kind: "setting",
343
- label: "Enable or disable subagent model picking"
344
- },
345
- "providers.subagent-models.add": {
346
- domain: "providers",
347
- kind: "setting",
348
- label: "Add subagent model entry"
349
- },
350
- "providers.subagent-models.update": {
351
- domain: "providers",
352
- kind: "setting",
353
- label: "Edit subagent model entry"
354
- },
355
- "providers.subagent-models.remove": {
356
- domain: "providers",
357
- kind: "setting",
358
- label: "Remove subagent model entry"
359
- },
360
- "providers.oauth.list": {
361
- domain: "providers",
362
- kind: "action",
363
- label: "List subscription providers and accounts"
364
- },
365
- "providers.oauth.login": {
366
- domain: "providers",
367
- kind: "action",
368
- label: "Sign in to subscription"
369
- },
370
- "providers.oauth.logout": {
371
- domain: "providers",
372
- kind: "action",
373
- label: "Sign out subscription account"
374
- },
375
- "providers.oauth.usage": {
376
- domain: "providers",
377
- kind: "action",
378
- label: "Read subscription usage"
379
- },
380
- "providers.oauth.cancel-login": {
381
- domain: "providers",
382
- kind: "action",
383
- label: "Cancel subscription login"
384
- },
385
- "providers.oauth.reopen-login": {
386
- domain: "providers",
387
- kind: "action",
388
- label: "Reopen subscription authorization"
389
- },
390
- "skills.list": { domain: "skills", kind: "action", label: "List skills" },
391
- "skills.import-local": { domain: "skills", kind: "action", label: "Import local skills" },
392
- "skills.toggle": { domain: "skills", kind: "setting", label: "Enable or disable skill" },
393
- "skills.remove": { domain: "skills", kind: "action", label: "Remove skill registration" },
394
- "mcp.list": { domain: "mcp", kind: "action", label: "List MCP servers" },
395
- "mcp.import-local": { domain: "mcp", kind: "action", label: "Import local MCP servers" },
396
- "mcp.edit": { domain: "mcp", kind: "setting", label: "Edit MCP server" },
397
- "mcp.toggle": { domain: "mcp", kind: "setting", label: "Enable or disable MCP server" },
398
- "mcp.remove": { domain: "mcp", kind: "action", label: "Remove MCP server" },
399
- "instructions.list": { domain: "instructions", kind: "action", label: "List instruction files" },
400
- "instructions.import-local": {
401
- domain: "instructions",
402
- kind: "action",
403
- label: "Import local instruction files"
404
- },
405
- "instructions.toggle": {
406
- domain: "instructions",
407
- kind: "setting",
408
- label: "Enable instruction file"
409
- },
410
- "instructions.read": {
411
- domain: "instructions",
412
- kind: "action",
413
- label: "Read instruction content"
414
- },
415
- "instructions.edit-local-copy": {
416
- domain: "instructions",
417
- kind: "setting",
418
- label: "Edit local instruction copy"
419
- },
420
- "instructions.overwrite-source": {
421
- domain: "instructions",
422
- kind: "action",
423
- label: "Overwrite original instruction file"
424
- },
425
- "instructions.remove": {
426
- domain: "instructions",
427
- kind: "action",
428
- label: "Remove instruction registration"
429
- },
430
- "presets.list": { domain: "presets", kind: "action", label: "List presets" },
431
- "presets.create": { domain: "presets", kind: "setting", label: "Create preset" },
432
- "presets.edit": { domain: "presets", kind: "setting", label: "Edit preset" },
433
- "presets.delete": { domain: "presets", kind: "action", label: "Delete preset" },
434
- "presets.set-default": {
435
- domain: "presets",
436
- kind: "setting",
437
- label: "Set default preset for new conversations"
438
- },
439
- "presets.select-for-conversation": {
440
- domain: "presets",
441
- kind: "setting",
442
- label: "Select conversation preset"
443
- },
444
- "agent-types.list": { domain: "agent-types", kind: "action", label: "List agent types" },
445
- "agent-types.create": { domain: "agent-types", kind: "setting", label: "Create agent type" },
446
- "agent-types.edit": { domain: "agent-types", kind: "setting", label: "Edit agent type" },
447
- "agent-types.toggle-builtin": {
448
- domain: "agent-types",
449
- kind: "setting",
450
- label: "Enable or disable built-in agent type"
451
- },
452
- "agent-types.delete": { domain: "agent-types", kind: "action", label: "Delete agent type" },
453
- "tools.list": { domain: "tools", kind: "action", label: "List built-in tools" },
454
- "tools.toggle-builtin": {
455
- domain: "tools",
456
- kind: "setting",
457
- label: "Enable or disable built-in tool"
458
- },
459
- "onboarding.complete": {
460
- domain: "onboarding",
461
- kind: "action",
462
- label: "Complete first-run onboarding"
463
- },
464
- "projects.list": { domain: "projects", kind: "action", label: "List projects" },
465
- "projects.recent": { domain: "projects", kind: "action", label: "List recent projects" },
466
- "projects.add": { domain: "projects", kind: "action", label: "Add project" },
467
- "projects.remove": { domain: "projects", kind: "action", label: "Remove project" },
468
- "projects.ssh-connections": {
469
- domain: "projects",
470
- kind: "action",
471
- label: "List SSH connection profiles"
472
- },
473
- "projects.ssh-connections.add": {
474
- domain: "projects",
475
- kind: "action",
476
- label: "Add SSH connection profile"
477
- },
478
- "projects.ssh-connections.update": {
479
- domain: "projects",
480
- kind: "setting",
481
- label: "Edit SSH connection profile"
482
- },
483
- "projects.ssh-connections.remove": {
484
- domain: "projects",
485
- kind: "action",
486
- label: "Remove SSH connection profile"
487
- },
488
- "projects.ssh-connections.test": {
489
- domain: "projects",
490
- kind: "action",
491
- label: "Test SSH connection"
492
- },
493
- "conversations.list": { domain: "conversations", kind: "action", label: "List conversations" },
494
- "conversations.create": {
495
- domain: "conversations",
496
- kind: "action",
497
- label: "Create conversation"
498
- },
499
- "conversations.select": {
500
- domain: "conversations",
501
- kind: "action",
502
- label: "Select conversation"
503
- },
504
- "conversations.delete": {
505
- domain: "conversations",
506
- kind: "action",
507
- label: "Delete conversation"
508
- },
509
- "conversations.import-external": {
510
- domain: "conversations",
511
- kind: "action",
512
- label: "Import external conversation"
513
- },
514
- "conversations.send": { domain: "conversations", kind: "action", label: "Send message" },
515
- "conversations.abort": { domain: "conversations", kind: "action", label: "Abort current turn" },
516
- "conversations.set-model": {
517
- domain: "conversations",
518
- kind: "setting",
519
- label: "Select conversation model"
520
- },
521
- "conversations.set-reasoning": {
522
- domain: "conversations",
523
- kind: "setting",
524
- label: "Set reasoning mode"
525
- },
526
- "conversations.set-thinking": {
527
- domain: "conversations",
528
- kind: "setting",
529
- label: "Set thinking level"
530
- },
531
- "conversations.set-approval-mode": {
532
- domain: "conversations",
533
- kind: "setting",
534
- label: "Set approval mode"
535
- },
536
- "conversations.approval.respond": {
537
- domain: "conversations",
538
- kind: "action",
539
- label: "Resolve coding tool approval"
540
- },
541
- "conversations.ask.respond": {
542
- domain: "conversations",
543
- kind: "action",
544
- label: "Answer coding agent question"
545
- },
546
- "conversations.background-task.stop": {
547
- domain: "conversations",
548
- kind: "action",
549
- label: "Stop background task"
550
- },
551
- "conversations.file-mention.attach": {
552
- domain: "conversations",
553
- kind: "action",
554
- label: "Attach project file mention"
555
- },
556
- "conversations.queue.edit": {
557
- domain: "conversations",
558
- kind: "action",
559
- label: "Edit queued message"
560
- },
561
- "conversations.queue.remove": {
562
- domain: "conversations",
563
- kind: "action",
564
- label: "Remove queued message"
565
- },
566
- "conversations.queue.send-now": {
567
- domain: "conversations",
568
- kind: "action",
569
- label: "Send queued message now"
570
- },
571
- "conversations.goal.set": { domain: "conversations", kind: "action", label: "Set session goal" },
572
- "conversations.goal.pause": {
573
- domain: "conversations",
574
- kind: "action",
575
- label: "Pause session goal"
576
- },
577
- "conversations.goal.resume": {
578
- domain: "conversations",
579
- kind: "action",
580
- label: "Resume session goal"
581
- },
582
- "conversations.goal.clear": {
583
- domain: "conversations",
584
- kind: "action",
585
- label: "Clear session goal"
586
- },
587
- "conversations.worktree.create": {
588
- domain: "conversations",
589
- kind: "action",
590
- label: "Create isolated worktree for conversation"
591
- },
592
- "conversations.worktree.status": {
593
- domain: "conversations",
594
- kind: "action",
595
- label: "Inspect conversation worktree status"
596
- },
597
- "conversations.worktree.remove": {
598
- domain: "conversations",
599
- kind: "action",
600
- label: "Clean up conversation worktree"
601
- },
602
- "conversations.worktree.rebuild": {
603
- domain: "conversations",
604
- kind: "action",
605
- label: "Rebuild missing conversation worktree"
606
- },
607
- "conversations.worktree.release": {
608
- domain: "conversations",
609
- kind: "action",
610
- label: "Release live session for workspace migration"
611
- },
612
- "conversations.retry-turn": {
613
- domain: "conversations",
614
- kind: "action",
615
- label: "Retry failed turn"
616
- },
617
- "conversations.rewind": { domain: "conversations", kind: "action", label: "Rewind conversation" },
618
- "conversations.rewind-files": {
619
- domain: "conversations",
620
- kind: "action",
621
- label: "Rewind conversation and restore files"
622
- },
623
- "team.list-agent-types": { domain: "team", kind: "action", label: "List team agent types" },
624
- "team.list-coworkers": { domain: "team", kind: "action", label: "List origin coworkers" },
625
- "team.hire-coworker": { domain: "team", kind: "action", label: "Hire coworker" },
626
- "team.dismiss-coworker": { domain: "team", kind: "action", label: "Dismiss coworker" },
627
- "team.message-coworker": { domain: "team", kind: "action", label: "Message coworker" },
628
- "updates.status": { domain: "updates", kind: "action", label: "Read update status" },
629
- "updates.check": { domain: "updates", kind: "action", label: "Check for updates" },
630
- "updates.download": { domain: "updates", kind: "action", label: "Download update" },
631
- "updates.install": { domain: "updates", kind: "action", label: "Quit and install update" },
632
- "window.open-settings": { domain: "window", kind: "action", label: "Open settings window" },
633
- "window.focus-conversation-notification": {
634
- domain: "window",
635
- kind: "action",
636
- label: "Focus conversation from notification"
637
- },
638
- "window.minimize": { domain: "window", kind: "action", label: "Minimize window" },
639
- "window.maximize": { domain: "window", kind: "action", label: "Maximize or restore window" },
640
- "window.close": { domain: "window", kind: "action", label: "Close window" },
641
- "window.toggle-sidebar": { domain: "window", kind: "action", label: "Toggle sidebar" },
642
- "window.fullscreen": { domain: "window", kind: "action", label: "Enter or leave fullscreen" },
643
- "coding-tools.command": { domain: "coding-tools", kind: "action", label: "Run command" },
644
- "coding-tools.file-read": { domain: "coding-tools", kind: "action", label: "Read project file" },
645
- "coding-tools.file-search": {
646
- domain: "coding-tools",
647
- kind: "action",
648
- label: "Search project files"
649
- },
650
- "coding-tools.file-edit": { domain: "coding-tools", kind: "action", label: "Edit project file" },
651
- "coding-tools.file-write": {
652
- domain: "coding-tools",
653
- kind: "action",
654
- label: "Write project file"
655
- },
656
- "coding-tools.mcp": { domain: "coding-tools", kind: "action", label: "Call MCP tool" },
657
- "coding-tools.subagent": { domain: "coding-tools", kind: "action", label: "Run subagent" },
658
- "coding-tools.workflow": {
659
- domain: "coding-tools",
660
- kind: "action",
661
- label: "Run workflow"
662
- },
663
- "coding-tools.coworker": { domain: "coding-tools", kind: "action", label: "Use coworker tool" },
664
- "coding-tools.todo": { domain: "coding-tools", kind: "action", label: "Manage coding todo list" },
665
- "coding-tools.ask-user": { domain: "coding-tools", kind: "action", label: "Ask coding question" },
666
- "coding-tools.background-task": {
667
- domain: "coding-tools",
668
- kind: "action",
669
- label: "Run background shell task"
670
- },
671
- "coding-tools.browser": {
672
- domain: "coding-tools",
673
- kind: "action",
674
- label: "Use built-in browser"
675
- },
676
- "coding-tools.web": {
677
- domain: "coding-tools",
678
- kind: "action",
679
- label: "Search and fetch the web"
680
- },
681
- "coding-tools.isolated-sandbox": {
682
- domain: "coding-tools",
683
- kind: "action",
684
- label: "Run isolated sandbox"
685
- },
686
- "coding-tools.memory": {
687
- domain: "coding-tools",
688
- kind: "action",
689
- label: "Search and capture long-term memory"
690
- },
691
- "coding-tools.computer": {
692
- domain: "coding-tools",
693
- kind: "action",
694
- label: "Use host desktop computer"
695
- },
696
- "coding-tools.plan": {
697
- domain: "coding-tools",
698
- kind: "action",
699
- label: "Submit a plan in plan mode"
700
- }
701
- };
702
- const CAPABILITY_SUBJECT_KINDS = [
703
- "setting",
704
- "provider",
705
- "account",
706
- "agent-type",
707
- "preset",
708
- "tool",
709
- "project",
710
- "conversation",
711
- "coworker",
712
- "other"
713
- ];
714
- const CAPABILITY_OUTCOMES = [
715
- "succeeded",
716
- "denied",
717
- "failed",
718
- "unavailable",
719
- "cancelled"
720
- ];
721
- const isRecord$6 = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
722
- const isNonEmptyString$2 = (value) => typeof value === "string" && value.length > 0;
723
- const hasOnlyKeys$1 = (value, allowed) => Object.keys(value).every((key) => allowed.includes(key));
724
- const hasExactKeys$3 = (value, keys) => Object.keys(value).length === keys.length && hasOnlyKeys$1(value, keys);
725
- const isProductSurfaceId$1 = (value) => typeof value === "string" && Object.hasOwn(PRODUCT_SURFACE_INVENTORY, value);
726
- function parseCapabilityResult(value) {
727
- if (!isRecord$6(value) || typeof value.ok !== "boolean") return null;
728
- if (value.ok) {
729
- return hasExactKeys$3(value, ["ok", "data"]) ? { ok: true, data: value.data } : null;
730
- }
731
- if (!hasOnlyKeys$1(value, ["ok", "code", "error", "suggestedAction"]) || value.code !== "denied" && value.code !== "invalid" && value.code !== "failed" && value.code !== "unavailable" && value.code !== "cancelled" || !isNonEmptyString$2(value.error) || value.suggestedAction !== void 0 && !isNonEmptyString$2(value.suggestedAction)) {
732
- return null;
733
- }
734
- return value;
735
- }
736
- function parseCapabilitySubject(value) {
737
- if (!isRecord$6(value) || !hasExactKeys$3(value, ["kind", "id", "label"])) return null;
738
- return CAPABILITY_SUBJECT_KINDS.includes(value.kind) && isNonEmptyString$2(value.id) && isNonEmptyString$2(value.label) ? value : null;
739
- }
740
- function parseCapabilityChange(value) {
741
- if (!isRecord$6(value) || !hasExactKeys$3(value, ["field", "previous", "value"])) return null;
742
- return isNonEmptyString$2(value.field) ? value : null;
743
- }
744
- function parseCapabilityReceipt(value) {
745
- if (!isRecord$6(value)) return null;
746
- if (!hasOnlyKeys$1(value, [
747
- "receiptId",
748
- "operationId",
749
- "child",
750
- "turnId",
751
- "requestId",
752
- "capabilityId",
753
- "risk",
754
- "subject",
755
- "outcome",
756
- "summary",
757
- "changes",
758
- "suggestedAction",
759
- "occurredAt",
760
- "sequence"
761
- ]) || !isUuid(value.receiptId) || !isNonEmptyString$2(value.operationId) || !parseChildSessionIdentity(value.child) || !isNonEmptyString$2(value.turnId) || !isNonEmptyString$2(value.requestId) || !isProductSurfaceId$1(value.capabilityId) || value.risk !== "read" && value.risk !== "reversible" && value.risk !== "dangerous" || !parseCapabilitySubject(value.subject) || !CAPABILITY_OUTCOMES.includes(value.outcome) || !isNonEmptyString$2(value.summary) || value.changes !== void 0 && (!Array.isArray(value.changes) || value.changes.some((change) => parseCapabilityChange(change) === null)) || value.suggestedAction !== void 0 && !isNonEmptyString$2(value.suggestedAction) || typeof value.occurredAt !== "number" || !Number.isFinite(value.occurredAt) || !Number.isInteger(value.sequence) || value.sequence < 0) {
762
- return null;
763
- }
764
- return value;
765
- }
766
- const COMPACT_STRATEGIES = [
767
- "standard",
768
- "smart",
769
- "codex-native",
770
- "continuous-memory"
771
- ];
772
- function parseCompactStrategy(value) {
773
- return typeof value === "string" && COMPACT_STRATEGIES.includes(value) ? value : null;
774
- }
775
- function resolveCompactStrategy(value, legacySmart) {
776
- const parsed = parseCompactStrategy(value);
777
- if (parsed) return parsed;
778
- return legacySmart === true ? "smart" : "standard";
779
- }
780
- const ARTIFACT_ID = /^[A-Za-z0-9._:-]{1,128}$/;
781
- const PLUGIN_ID$1 = /^[a-z][a-z0-9]*(\.[a-z0-9]+)+$/;
782
- function parsePluginArtifactInfo(raw) {
783
- if (typeof raw !== "object" || raw === null) return null;
784
- const value = raw;
785
- if (typeof value.id !== "string" || !ARTIFACT_ID.test(value.id)) return null;
786
- if (typeof value.pluginId !== "string" || value.pluginId.length > 40 || !PLUGIN_ID$1.test(value.pluginId))
787
- return null;
788
- if (typeof value.name !== "string" || value.name.length === 0 || value.name.length > 256)
789
- return null;
790
- if (typeof value.mime !== "string" || value.mime.length === 0 || value.mime.length > 128)
791
- return null;
792
- if (typeof value.size !== "number" || !Number.isFinite(value.size) || value.size < 0) return null;
793
- if (typeof value.createdAt !== "number" || !Number.isFinite(value.createdAt)) return null;
794
- return {
795
- id: value.id,
796
- pluginId: value.pluginId,
797
- name: value.name,
798
- mime: value.mime,
799
- size: value.size,
800
- createdAt: value.createdAt
801
- };
802
- }
803
- function pluginArtifactsFromToolDetails(details) {
804
- if (typeof details !== "object" || details === null || Array.isArray(details)) return [];
805
- const raw = details.artifacts;
806
- if (!Array.isArray(raw)) return [];
807
- return raw.flatMap((item) => {
808
- const parsed = parsePluginArtifactInfo(item);
809
- return parsed ? [parsed] : [];
810
- });
811
- }
812
- const PLUGIN_EVENTS = [
813
- "session_start",
814
- "session_end",
815
- "agent_start",
816
- "agent_end",
817
- "before_compact",
818
- "after_compact",
819
- "tool_call",
820
- "tool_result",
821
- "input",
822
- "context_usage",
823
- "session_status",
824
- "model_select",
825
- "before_agent_start"
826
- ];
827
- const HOST_PLUGIN_EVENTS = ["session_status"];
828
- const isHostPluginEvent = (event) => HOST_PLUGIN_EVENTS.includes(event);
829
- const AGENT_END_TEXT_MAX = 64 * 1024;
830
- const CONTEXT_USAGE_BUCKETS = [
831
- "system",
832
- "instructions",
833
- "skills",
834
- "tools",
835
- "conversation",
836
- "compaction",
837
- "reminders"
838
- ];
839
- const CONTEXT_PART_KINDS = [
840
- "system",
841
- "tools",
842
- "skills",
843
- "memory",
844
- "files",
845
- "results",
846
- "chat"
847
- ];
848
- const CONTEXT_PART_ITEMS = 24;
849
- const PLUGIN_INTERCEPT_EVENTS = [
850
- "tool_call",
851
- "tool_result",
852
- "input",
853
- "before_agent_start"
854
- ];
855
- const APPEND_ONLY_INTERCEPT_EVENTS = ["before_agent_start"];
856
- const BEFORE_AGENT_START_APPEND_MAX = 16 * 1024;
857
- const BEFORE_AGENT_START_PROMPT_MAX = 64 * 1024;
858
- const BEFORE_COMPACT_TIMEOUT_MS = 1e4;
859
- const INTERCEPT_TIMEOUT_MS = 5e3;
860
- const INTERCEPT_TOTAL_TIMEOUT_MS = 25e3;
861
- const CHILD_INTERCEPT_EVENTS = [
862
- "tool_call"
863
- ];
864
- const CHILD_INTERCEPT_TIMEOUT_MS = 2e3;
865
- const CHILD_INTERCEPT_TOTAL_TIMEOUT_MS = 5e3;
866
- const OBSERVE_TIMEOUT_MS = 3e4;
867
- const isInterceptEvent = (event) => PLUGIN_INTERCEPT_EVENTS.includes(event);
868
- const isChildInterceptEvent = (event) => CHILD_INTERCEPT_EVENTS.includes(event);
869
- const isRecord$5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
870
- function initialInterceptState(event, payload) {
871
- const result = event === "input" ? { action: "continue" } : {};
872
- return { event, payload, result, done: false };
873
- }
874
- function applyInterceptResult(state, raw) {
875
- if (state.done || !isRecord$5(raw)) return state;
876
- if (state.event === "tool_call") {
877
- const payload = state.payload;
878
- const result = { ...state.result };
879
- if (raw.block === true) {
880
- return {
881
- ...state,
882
- done: true,
883
- result: {
884
- ...result,
885
- block: true,
886
- ...typeof raw.reason === "string" ? { reason: raw.reason.slice(0, 2e3) } : {}
887
- }
888
- };
889
- }
890
- if (!isRecord$5(raw.input)) return state;
891
- return {
892
- ...state,
893
- payload: { ...payload, input: raw.input },
894
- result: { ...result, input: raw.input }
895
- };
896
- }
897
- if (state.event === "tool_result") {
898
- const payload = state.payload;
899
- const result = { ...state.result };
900
- const nextPayload = { ...payload };
901
- if (typeof raw.content === "string") {
902
- result.content = raw.content;
903
- nextPayload.content = raw.content;
904
- }
905
- if (typeof raw.isError === "boolean") {
906
- result.isError = raw.isError;
907
- nextPayload.isError = raw.isError;
908
- }
909
- return {
910
- ...state,
911
- payload: nextPayload,
912
- result
913
- };
914
- }
915
- if (state.event === "before_agent_start") {
916
- if (typeof raw.append !== "string" || raw.append.length === 0) return state;
917
- const previous = state.result.append;
918
- const append = (previous ? `${previous}
919
-
920
- ${raw.append}` : raw.append).slice(
921
- 0,
922
- BEFORE_AGENT_START_APPEND_MAX
923
- );
924
- return { ...state, result: { append } };
925
- }
926
- if (raw.action === "handled")
927
- return { ...state, done: true, result: { action: "handled" } };
928
- if (raw.action === "transform" && typeof raw.text === "string") {
929
- return {
930
- ...state,
931
- payload: { ...state.payload, text: raw.text },
932
- result: { action: "transform", text: raw.text }
933
- };
934
- }
935
- return state;
936
- }
937
- function failClosedResult(event, pluginName) {
938
- const reason = `插件 ${pluginName} 未能完成检查,已按其策略拒绝`;
939
- if (event === "tool_call") return { block: true, reason };
940
- if (event === "tool_result") return { content: reason, isError: true };
941
- if (event === "before_agent_start") return {};
942
- return { action: "handled" };
943
- }
944
- const PLUGIN_INJECT_MAX_CHARS = 32 * 1024;
945
- const PLUGIN_PROGRESS_MAX_CHARS = 16 * 1024;
946
- const PLUGIN_INJECT_MAX_IMAGES = 4;
947
- const PLUGIN_INJECT_IMAGE_MAX_CHARS = 7 * 1024 * 1024;
948
- const PLUGIN_IMAGE_MIME = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
949
- function parsePluginInjectImages(value) {
950
- if (value === void 0) return [];
951
- if (!Array.isArray(value) || value.length > PLUGIN_INJECT_MAX_IMAGES) return null;
952
- const images = [];
953
- for (const item of value) {
954
- if (typeof item !== "object" || item === null) return null;
955
- const { data, mimeType } = item;
956
- if (typeof mimeType !== "string" || !PLUGIN_IMAGE_MIME.has(mimeType)) return null;
957
- if (typeof data !== "string" || data.length === 0 || data.length > PLUGIN_INJECT_IMAGE_MAX_CHARS || !/^[A-Za-z0-9+/]+={0,2}$/.test(data))
958
- return null;
959
- images.push({ data, mimeType });
960
- }
961
- return images;
962
- }
963
- const PLUGIN_MESSAGE_TYPE = "enso-plugin-message";
964
- const PLUGIN_AGENT_PROMPT_MAX_CHARS = 64 * 1024;
965
- const PLUGIN_AGENT_SYSTEM_MAX_CHARS = 32 * 1024;
966
- const PLUGIN_AGENT_DEFAULT_TIMEOUT_MS = 10 * 6e4;
967
- const PLUGIN_AGENT_MAX_TIMEOUT_MS = 20 * 6e4;
968
- const PLUGIN_AGENT_TEXT_MAX_CHARS = 64 * 1024;
969
- const PLUGIN_AGENT_ARGS_MAX_CHARS = 4096;
970
- const PLUGIN_AGENT_OUTPUT_MAX_CHARS = 4096;
971
- const PLUGIN_AGENT_RUN_ID = /^[A-Za-z0-9_-]{1,64}$/;
972
- function parsePluginAgentRunEvent(raw) {
973
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
974
- const v = raw;
975
- const keys = Object.keys(v);
976
- const only = (...allowed) => keys.every((key) => allowed.includes(key));
977
- const short2 = (s, max) => typeof s === "string" && s.length <= max;
978
- const id = (s) => typeof s === "string" && s.length > 0 && s.length <= 256;
979
- switch (v.type) {
980
- case "tool-start":
981
- return only("type", "id", "name", "args", "parentId") && id(v.id) && id(v.name) && short2(v.args, PLUGIN_AGENT_ARGS_MAX_CHARS) && (v.parentId === void 0 || id(v.parentId)) ? {
982
- type: "tool-start",
983
- id: v.id,
984
- name: v.name,
985
- args: v.args,
986
- ...v.parentId ? { parentId: v.parentId } : {}
987
- } : null;
988
- case "tool-end":
989
- return only("type", "id", "isError", "output") && id(v.id) && typeof v.isError === "boolean" && (v.output === void 0 || short2(v.output, PLUGIN_AGENT_OUTPUT_MAX_CHARS)) ? {
990
- type: "tool-end",
991
- id: v.id,
992
- isError: v.isError,
993
- ...v.output !== void 0 ? { output: v.output } : {}
994
- } : null;
995
- case "text":
996
- return only("type", "text") && short2(v.text, PLUGIN_AGENT_TEXT_MAX_CHARS) ? { type: "text", text: v.text } : null;
997
- case "end":
998
- if (v.ok === true)
999
- return only("type", "ok", "text", "model") && short2(v.text, PLUGIN_AGENT_TEXT_MAX_CHARS) && (v.model === void 0 || id(v.model)) ? { type: "end", ok: true, text: v.text, ...v.model ? { model: v.model } : {} } : null;
1000
- return v.ok === false && only("type", "ok", "error", "aborted") && typeof v.error === "string" && v.error.length > 0 && v.error.length <= 4096 && (v.aborted === void 0 || v.aborted === true) ? { type: "end", ok: false, error: v.error, ...v.aborted ? { aborted: true } : {} } : null;
1001
- default:
1002
- return null;
1003
- }
1004
- }
1005
- const PLUGIN_ID = /^[a-z][a-z0-9]*(\.[a-z0-9]+)+$/;
1006
- function parsePluginMessageSource(raw) {
1007
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
1008
- const { pluginId, pluginName } = raw;
1009
- if (typeof pluginId !== "string" || pluginId.length > 40 || !PLUGIN_ID.test(pluginId))
1010
- return null;
1011
- if (typeof pluginName !== "string" || pluginName.length === 0 || pluginName.length > 60)
1012
- return null;
1013
- return { pluginId, pluginName };
1014
- }
1015
- function parsePluginAgentSource(raw, ownerSessionId) {
1016
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
1017
- const value = raw;
1018
- if (Object.keys(value).some((key) => !["kind", "sessionId", "name", "agentType"].includes(key)))
1019
- return null;
1020
- const { kind, sessionId, name, agentType } = value;
1021
- if (kind !== "subagent" && kind !== "coworker") return null;
1022
- if (sessionId !== ownerSessionId || !ownerSessionId.includes("::")) return null;
1023
- if (typeof name !== "string" || name.length === 0 || name.length > 128) return null;
1024
- if (agentType !== void 0 && (typeof agentType !== "string" || agentType.length === 0 || agentType.length > 128))
1025
- return null;
1026
- return { kind, sessionId, name, ...agentType !== void 0 ? { agentType } : {} };
1027
- }
1028
- const PLUGIN_HOST_APIS = [
1029
- "fs.readText",
1030
- "fs.writeText",
1031
- "net.fetch",
1032
- "ui.notify",
1033
- /** 推一条事件到本插件已打开的侧栏页面;args { name, data } */
1034
- "ui.viewEvent",
1035
- /** 打开右侧栏并创建或定位到本插件的侧栏页面;args { viewId? } */
1036
- "ui.viewOpen",
1037
- "ui.viewClose",
1038
- /** 改清单声明过的输入框底栏状态项;args { id, text?, tooltip?, tone?, visible? } */
1039
- "ui.statusUpdate",
1040
- "composer.readDraft",
1041
- "composer.insertText",
1042
- "composer.replaceDraft",
1043
- "config.get",
1044
- "mcp.tools",
1045
- "mcp.call",
1046
- /** 工具执行中上报进度;args { text } */
1047
- "tool.progress",
1048
- /** 写一份产出文件;args { name, text | base64, mime? },返回 { id, name, size, mime } */
1049
- "artifact.write",
1050
- /** 向会话注入消息;args { sessionId?, text, images?, deliverAs?, triggerTurn? } */
1051
- "session.inject",
1052
- /** 中止会话当前一轮;args { sessionId? },权限同 session.inject */
1053
- "session.abort",
1054
- /** 调用其他插件导出的方法;args { pluginId, name, args } */
1055
- "plugin.call",
1056
- "ui.clipboard",
1057
- "ui.openExternal",
1058
- /** 运行期增减工具与命令;args { kind, name, ...meta } */
1059
- "contrib.register",
1060
- "contrib.unregister",
1061
- /** 宿主能力探测 */
1062
- "host.capabilities",
1063
- /** 秘书联系方式:注册渠道实现;args { channelId, caps } */
1064
- "contact.register",
1065
- /** 渠道收到一句话;args { channelId, peerId, text, senderId?, chatType?, chatTitle?, name?, at? } */
1066
- "contact.inbound",
1067
- /** 渠道状态;args { channelId, status, detail?, peers? } */
1068
- "contact.setStatus",
1069
- /** 列出会话及其状态;args { scope? }:缺省同项目,'all' 为所有项目(需 session.readAll);返回 { current, sessions } */
1070
- "session.list",
1071
- /** 会话汇总状态;args { sessionId? } 缺省发起会话,返回 { sessionId, state, pendingAsks, pendingApprovals } */
1072
- "session.status",
1073
- /** 切换到会话;args { sessionId },需用户手势 */
1074
- "session.focus",
1075
- /** 切到会话并展开某个子代理的详情;args { sessionId, agentId },需用户手势 */
1076
- "session.focusSubagent",
1077
- /** 打开某个子会话的历史弹窗;args { parentId, childId },需用户手势 */
1078
- "session.openChildRun",
1079
- /** 在发起会话的项目里新建会话并切过去;args { text?, presetId? },presetId 只能填本插件的预设 */
1080
- "session.create",
1081
- /** 开关本进程的回合结束订阅;args { on },权限同 session.status */
1082
- "session.watchTurnEnd",
1083
- /** 用发起会话的模型跑一个只读代理;args { runId, prompt, systemPrompt?, context?, timeoutMs? },进度与结果经 agent-run 推送 */
1084
- "agent.run",
1085
- /** 取消本插件发起的代理;args { runId } */
1086
- "agent.cancel"
1087
- ];
1088
- const PREFIX = "plugin_";
1089
- const SEPARATOR = "__";
1090
- const EXTERNAL = /^plugin_([a-z][a-z0-9]*(?:-[a-z0-9]+)+)__([a-z][a-z0-9_]*)$/;
1091
- function pluginToolName(pluginId, toolName) {
1092
- return `${PREFIX}${pluginId.replaceAll(".", "-")}${SEPARATOR}${toolName}`;
1093
- }
1094
- function parsePluginToolName(name) {
1095
- const match = EXTERNAL.exec(name);
1096
- if (!match?.[1] || !match[2] || match[2].includes(SEPARATOR)) return null;
1097
- return { pluginId: match[1].replaceAll("-", "."), toolName: match[2] };
1098
- }
1099
- function isClassifierOnlyProvider(provider) {
1100
- if (provider.api === "typesafe-system-one" || provider.catalogId === "typesafe") return true;
1101
- try {
1102
- const host = new URL(provider.baseUrl ?? "").hostname.toLowerCase();
1103
- return host === "api.typesafe.ai" || host.endsWith(".api.typesafe.ai");
1104
- } catch {
1105
- return false;
1106
- }
1107
- }
1108
- const DEFAULT_BASE_URLS = {
1109
- "openai-completions": "https://api.openai.com/v1",
1110
- "openai-responses": "https://api.openai.com/v1",
1111
- "anthropic-messages": "https://api.anthropic.com",
1112
- // pi 的 Google SDK 在有自定义 baseUrl 时会把 apiVersion 置空,版本号必须写进地址
1113
- "google-generative-ai": "https://generativelanguage.googleapis.com/v1beta",
1114
- ollama: "http://127.0.0.1:11434",
1115
- "typesafe-system-one": "https://api.typesafe.ai/v1/"
1116
- };
1117
- function withVersionSegment(base, segment) {
1118
- const trimmed = base.replace(/\/+$/, "");
1119
- return trimmed.endsWith(`/${segment}`) ? trimmed : `${trimmed}/${segment}`;
1120
- }
1121
- function resolvePiProviderBaseUrl(api, baseUrl) {
1122
- const base = baseUrl.trim().replace(/\/+$/, "") || DEFAULT_BASE_URLS[api];
1123
- return api === "google-generative-ai" ? withVersionSegment(base, "v1beta") : base;
1124
- }
1125
- function record$1(value) {
1126
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1127
- }
1128
- function validUrl(value) {
1129
- try {
1130
- const url = new URL(value);
1131
- return (url.protocol === "http:" || url.protocol === "https:") && !url.username && !url.password && !url.search && !url.hash && !value.includes("?") && !value.includes("#");
1132
- } catch {
1133
- return false;
1134
- }
1135
- }
1136
- function parseImageGenerationConfig(value) {
1137
- const raw = record$1(value);
1138
- if (!raw) return null;
1139
- if (Object.keys(raw).some(
1140
- (key) => !["providerId", "modelId", "protocol", "baseUrl", "apiKey"].includes(key)
1141
- ))
1142
- return null;
1143
- const { providerId, modelId, protocol, baseUrl, apiKey } = raw;
1144
- if (typeof providerId !== "string" || !providerId.trim() || typeof modelId !== "string" || !modelId.trim() || typeof apiKey !== "string" || !apiKey.trim() || typeof baseUrl !== "string" || !validUrl(baseUrl) || protocol !== "openai" && protocol !== "openai-compatible" && protocol !== "gemini")
1145
- return null;
1146
- return { providerId, modelId, protocol, baseUrl, apiKey };
1147
- }
1148
- function providerConfig(provider, modelId) {
1149
- if (provider?.enabled !== true || provider.oauthAccountKey || provider.oauthAccountPool || typeof provider.apiKey !== "string" || !provider.apiKey.trim() || typeof provider.baseUrl !== "string")
1150
- return null;
1151
- let protocol;
1152
- if (provider.api === "google-generative-ai") protocol = "gemini";
1153
- else if (provider.api === "openai-completions" || provider.api === "openai-responses") {
1154
- let host = "";
1155
- try {
1156
- host = new URL(provider.baseUrl).hostname.toLowerCase();
1157
- } catch {
1158
- }
1159
- protocol = provider.catalogId !== "__custom" && (provider.catalogId === "openai" || !provider.catalogId && host === "api.openai.com") ? "openai" : "openai-compatible";
1160
- } else return null;
1161
- const fallback = protocol === "gemini" ? DEFAULT_BASE_URLS["google-generative-ai"] : protocol === "openai" ? DEFAULT_BASE_URLS["openai-responses"] : "";
1162
- let baseUrl = provider.baseUrl.trim().replace(/\/+$/, "") || fallback;
1163
- if (protocol === "gemini" && baseUrl) baseUrl = withVersionSegment(baseUrl, "v1beta");
1164
- if (protocol === "openai" && baseUrl) {
1165
- try {
1166
- if (new URL(baseUrl).pathname === "/") baseUrl = `${baseUrl}/v1`;
1167
- } catch {
1168
- }
1169
- }
1170
- return parseImageGenerationConfig({
1171
- providerId: provider.id,
1172
- modelId,
1173
- protocol,
1174
- baseUrl,
1175
- apiKey: provider.apiKey
1176
- });
1177
- }
1178
- function imageModels(provider) {
1179
- return Array.isArray(provider?.models) ? provider.models.filter(
1180
- (model) => Boolean(model) && typeof model === "object" && typeof model.id === "string" && Boolean(model.id.trim()) && model.enabled !== false && model.imageGeneration === true
1181
- ) : [];
1182
- }
1183
- function resolveImageGenerationConfig(ref, providers) {
1184
- if (ref === null || ref === void 0) return { config: null };
1185
- const raw = record$1(ref);
1186
- if (!raw || typeof raw.providerId !== "string" || typeof raw.modelId !== "string")
1187
- return { config: null, error: "Invalid image generation model selection" };
1188
- const provider = providers.find((p) => p?.id === raw.providerId);
1189
- const model = imageModels(provider).find((m) => m.id === raw.modelId);
1190
- const config = provider && model ? providerConfig(provider, model.id) : null;
1191
- return config ? { config } : { config: null, error: "Image generation model is unavailable" };
1192
- }
1193
- const LOCAL_IMAGE_SCHEME = "local-image";
1194
- const POSIX_HOST = "posix";
1195
- const REMOTE_FETCH_HOST = "remote-fetch";
1196
- const BOT_AVATAR_HOST = "bot-avatar";
1197
- const SECRETARY_AVATAR_HOST = "secretary-avatar";
1198
- const SECRETARY_REPORT_HOST = "secretary-report";
1199
- const PLUGIN_ASSET_HOST = "plugin-asset";
1200
- const IMAGE_EXTENSIONS = [
1201
- "png",
1202
- "jpg",
1203
- "jpeg",
1204
- "gif",
1205
- "webp",
1206
- "bmp",
1207
- "svg",
1208
- "jfif",
1209
- "avif"
1210
- ];
1211
- const VIDEO_EXTENSIONS = ["mp4", "webm", "ogg", "ogv", "mov"];
1212
- const MEDIA_EXTENSIONS = [...IMAGE_EXTENSIONS, ...VIDEO_EXTENSIONS];
1213
- function mediaExtension(pathOrUrl) {
1214
- const clean = pathOrUrl.split(/[?#]/)[0] ?? "";
1215
- const idx = clean.lastIndexOf(".");
1216
- if (idx < 0) return "";
1217
- return clean.slice(idx + 1).toLowerCase();
1218
- }
1219
- function isMediaPath(pathOrUrl) {
1220
- return MEDIA_EXTENSIONS.includes(mediaExtension(pathOrUrl));
1221
- }
1222
- function isVideoPath(pathOrUrl) {
1223
- return VIDEO_EXTENSIONS.includes(mediaExtension(pathOrUrl));
1224
- }
1225
- function localImageUrlToPath(url) {
1226
- const host = url.hostname;
1227
- if (!host || host === REMOTE_FETCH_HOST || host === BOT_AVATAR_HOST || host === SECRETARY_AVATAR_HOST || host === SECRETARY_REPORT_HOST || host === PLUGIN_ASSET_HOST)
1228
- return null;
1229
- const segments = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
1230
- if (host === POSIX_HOST) {
1231
- return `/${segments.join("/")}`;
1232
- }
1233
- if (/^[a-z]$/i.test(host)) {
1234
- return `${host.toUpperCase()}:\\${segments.join("\\")}`;
1235
- }
1236
- return `\\\\${host}\\${segments.join("\\")}`;
1237
- }
1238
- const extensions = new Set(IMAGE_EXTENSIONS);
1239
- function isPreviewPath(value) {
1240
- if (typeof value !== "string" || value.includes("\0")) return false;
1241
- const normalized = value.replaceAll("\\", "/");
1242
- return !normalized.startsWith("//") && (normalized.startsWith("/") || /^[A-Za-z]:\//.test(normalized)) && extensions.has(normalized.slice(normalized.lastIndexOf(".") + 1).toLowerCase());
1243
- }
1244
- function parseGeneratedImagePaths(value) {
1245
- if (!Array.isArray(value) || value.length > 640 || !value.every(isPreviewPath)) return null;
1246
- return [...new Set(value)];
1247
- }
1248
- function imageGenerationPreviewPaths(output) {
1249
- try {
1250
- const value = JSON.parse(output);
1251
- if (!value || !Array.isArray(value.items)) return [];
1252
- return [
1253
- ...new Set(
1254
- value.items.flatMap((item) => {
1255
- if (!item || typeof item !== "object") return [];
1256
- const entry = item;
1257
- return entry.status === "success" && isPreviewPath(entry.path) && typeof entry.mimeType === "string" && entry.mimeType.startsWith("image/") ? [entry.path] : [];
1258
- })
1259
- )
1260
- ].slice(0, 10);
1261
- } catch {
1262
- return [];
1263
- }
1264
- }
1265
- const DEFAULT_MAX_ACTIVE_COWORKERS = 5;
1266
- const MIN_MAX_ACTIVE_COWORKERS = 1;
1267
- const MAX_MAX_ACTIVE_COWORKERS = 20;
1268
- function normalizeMaxActiveCoworkers(value) {
1269
- if (typeof value !== "number" || !Number.isInteger(value)) return DEFAULT_MAX_ACTIVE_COWORKERS;
1270
- if (value < MIN_MAX_ACTIVE_COWORKERS) return MIN_MAX_ACTIVE_COWORKERS;
1271
- if (value > MAX_MAX_ACTIVE_COWORKERS) return MAX_MAX_ACTIVE_COWORKERS;
1272
- return value;
1273
- }
1274
- function parseMaxActiveCoworkers(value) {
1275
- if (typeof value !== "number" || !Number.isInteger(value)) return null;
1276
- if (value < MIN_MAX_ACTIVE_COWORKERS || value > MAX_MAX_ACTIVE_COWORKERS) return null;
1277
- return value;
1278
- }
1279
- const isCodexAccountKey = (key) => typeof key === "string" && /^openai-codex(?:#[2-9]\d*|#1\d+)?$/.test(key);
1280
- function parseOauthPoolFailure(value) {
1281
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1282
- const object = value;
1283
- return Object.keys(object).every(
1284
- (key) => ["accountKey", "reason", "resetAt", "selectionReceipt"].includes(key)
1285
- ) && isCodexAccountKey(object.accountKey) && (object.selectionReceipt === void 0 || isUuid(object.selectionReceipt)) && (object.reason === "quota-exhausted" || object.reason === "login-invalid") && (object.resetAt === void 0 || typeof object.resetAt === "number" && Number.isFinite(object.resetAt) && object.resetAt > 0) ? object : null;
1286
- }
1287
- function classifyCodexPoolFailure(status, body, accountKey) {
1288
- if (!isCodexAccountKey(accountKey)) return null;
1289
- const record2 = body && typeof body === "object" && !Array.isArray(body) ? body : void 0;
1290
- const error = record2?.error && typeof record2.error === "object" && !Array.isArray(record2.error) ? record2.error : void 0;
1291
- const code = error?.code ?? error?.type;
1292
- if (status === 401 || (status === 400 || status === 403) && ["token_expired", "token_revoked", "invalid_token", "invalid_grant"].includes(String(code))) {
1293
- return { accountKey, reason: "login-invalid" };
1294
- }
1295
- if (![400, 402, 403, 429].includes(status) || code !== "usage_limit_reached") return null;
1296
- const reset = error?.resets_at;
1297
- const resetAt = typeof reset === "number" && Number.isFinite(reset * 1e3) && reset > 0 ? reset * 1e3 : void 0;
1298
- return { accountKey, reason: "quota-exhausted", ...resetAt ? { resetAt } : {} };
1299
- }
1300
- function parseOauthAccountPool(value) {
1301
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1302
- const object = value;
1303
- if (Object.keys(object).some((key) => key !== "accountKeys") || !Array.isArray(object.accountKeys))
1304
- return null;
1305
- const keys = object.accountKeys;
1306
- return keys.length > 0 && keys.length <= 100 && keys.every(isCodexAccountKey) && new Set(keys).size === keys.length ? { accountKeys: [...keys] } : null;
1307
- }
1308
- function isOauthAccountPool(provider) {
1309
- return !provider.apiKey && isCodexAccountKey(provider.oauthAccountKey) && parseOauthAccountPool(provider.oauthAccountPool) !== null;
1310
- }
1311
- function eligibleOauthPoolAccountKeys(provider, modelId, providers, authenticatedAccountKeys) {
1312
- if (!isOauthAccountPool(provider) || !provider.enabled || !provider.models.some((model) => model.id === modelId && model.enabled !== false))
1313
- return [];
1314
- return (provider.oauthAccountPool?.accountKeys ?? []).filter(
1315
- (key) => authenticatedAccountKeys.has(key) && providers.some(
1316
- (entry) => entry.id !== provider.id && entry.oauthAccountPool === void 0 && !entry.apiKey && entry.oauthAccountKey === key && entry.enabled && entry.models.some((model) => model.id === modelId && model.enabled !== false)
1317
- )
1318
- );
1319
- }
1320
- const PLAN_ENTRY_TYPE = "enso-plan";
1321
- const PLAN_TITLE_MAX = 120;
1322
- const PLAN_TEXT_MAX = 32 * 1024;
1323
- const PLAN_RESOLUTIONS = ["approved", "revised", "discarded", "superseded"];
1324
- const PLAN_RESPOND_ACTIONS = ["approve", "revise", "discard", "finish"];
1325
- const PLAN_FEEDBACK_MAX = 8 * 1024;
1326
- const EMPTY_PLAN_STATE = { active: false, resolutions: {} };
1327
- function planPhase(state) {
1328
- if (!state) return "off";
1329
- if (state.pending) return "awaiting_review";
1330
- if (state.active) return "planning";
1331
- return state.executing ? "executing" : "off";
1332
- }
1333
- const isRecord$4 = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
1334
- const hasExactKeys$2 = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => key in value);
1335
- const nonEmpty = (value, max) => typeof value === "string" && value.trim().length > 0 && value.length <= max;
1336
- const isResolution = (value) => PLAN_RESOLUTIONS.includes(value);
1337
- function parsePlanDoc(value) {
1338
- if (!isRecord$4(value) || !hasExactKeys$2(value, ["planId", "title", "text"])) return null;
1339
- const { planId, title, text } = value;
1340
- if (!nonEmpty(planId, 64) || !nonEmpty(title, PLAN_TITLE_MAX) || !nonEmpty(text, PLAN_TEXT_MAX))
1341
- return null;
1342
- return { planId, title, text };
1343
- }
1344
- function parsePlanEntry(value) {
1345
- if (!isRecord$4(value) || value.v !== 1 || typeof value.at !== "number") return null;
1346
- const { at } = value;
1347
- switch (value.kind) {
1348
- case "mode":
1349
- return hasExactKeys$2(value, ["v", "kind", "active", "at"]) && typeof value.active === "boolean" ? { v: 1, kind: "mode", active: value.active, at } : null;
1350
- case "submitted": {
1351
- if (!hasExactKeys$2(value, ["v", "kind", "planId", "title", "text", "at"])) return null;
1352
- const doc = parsePlanDoc({ planId: value.planId, title: value.title, text: value.text });
1353
- return doc ? { v: 1, kind: "submitted", ...doc, at } : null;
1354
- }
1355
- case "resolved":
1356
- return hasExactKeys$2(value, ["v", "kind", "planId", "action", "at"]) && nonEmpty(value.planId, 64) && isResolution(value.action) ? { v: 1, kind: "resolved", planId: value.planId, action: value.action, at } : null;
1357
- case "finished":
1358
- return hasExactKeys$2(value, ["v", "kind", "planId", "at"]) && nonEmpty(value.planId, 64) ? { v: 1, kind: "finished", planId: value.planId, at } : null;
1359
- default:
1360
- return null;
1361
- }
1362
- }
1363
- function foldPlanState(entries) {
1364
- let state = { ...EMPTY_PLAN_STATE, resolutions: {} };
1365
- const resolve = (planId, action2) => {
1366
- state.resolutions = { ...state.resolutions, [planId]: action2 };
1367
- };
1368
- for (const raw of entries) {
1369
- if (!isRecord$4(raw) || raw.type !== "custom" || raw.customType !== PLAN_ENTRY_TYPE) continue;
1370
- const entry = parsePlanEntry(raw.data);
1371
- if (!entry) continue;
1372
- if (entry.kind === "mode") {
1373
- if (entry.active) {
1374
- state = { ...state, active: true, executing: void 0 };
1375
- } else {
1376
- if (state.pending) resolve(state.pending.planId, "discarded");
1377
- state = { ...state, active: false, pending: void 0 };
1378
- }
1379
- } else if (entry.kind === "submitted") {
1380
- if (!state.active) continue;
1381
- if (state.pending) resolve(state.pending.planId, "superseded");
1382
- state = { ...state, pending: { planId: entry.planId, title: entry.title, text: entry.text } };
1383
- } else if (entry.kind === "resolved") {
1384
- const pending = state.pending;
1385
- if (pending?.planId !== entry.planId) continue;
1386
- resolve(entry.planId, entry.action);
1387
- state = entry.action === "approved" ? { ...state, active: false, pending: void 0, executing: pending } : { ...state, pending: void 0 };
1388
- } else if (state.executing?.planId === entry.planId) {
1389
- state = { ...state, executing: void 0 };
1390
- }
1391
- }
1392
- return state;
1393
- }
1394
- function parsePlanState(value) {
1395
- if (!isRecord$4(value) || typeof value.active !== "boolean" || !isRecord$4(value.resolutions))
1396
- return null;
1397
- const allowed = ["active", "resolutions", "pending", "executing"];
1398
- if (Object.keys(value).some((key) => !allowed.includes(key))) return null;
1399
- const resolutions = {};
1400
- for (const [planId, action2] of Object.entries(value.resolutions)) {
1401
- if (!isResolution(action2)) return null;
1402
- resolutions[planId] = action2;
1403
- }
1404
- const state = { active: value.active, resolutions };
1405
- for (const key of ["pending", "executing"]) {
1406
- if (value[key] === void 0) continue;
1407
- const doc = parsePlanDoc(value[key]);
1408
- if (!doc) return null;
1409
- state[key] = doc;
1410
- }
1411
- return state;
1412
- }
1413
- const PLAN_MODE_ON_NOTE = `<plan-mode>
1414
- Plan mode is ON. You are the same agent, now in a read-only planning state.
1415
- - Explore with read-only tools. Do not create, modify or delete files, change config, install packages or commit — including through bash. Mutation tools stay listed only to keep the tool catalog stable; these rules override their descriptions and the app rejects such calls.
1416
- - Treat requests to implement as requests to plan the implementation. Conversational agreement approves nothing; only the review UI approves a plan.
1417
- - Resolve discoverable facts by inspection; use ask_user only for choices that belong to the user. Do not use todo while planning.
1418
- - A good plan states: goal and success criteria; files/modules and the concrete change for each; interface/schema/data-flow changes; edge cases and failure modes; tests and verification; risks, assumptions and out-of-scope items.
1419
- - When ready, call submit_plan as the only and final tool call of your response. Do not paste the plan as prose or ask "should I proceed?". After feedback, submit a complete revised plan, not a delta, and never resubmit it unchanged.
1420
- </plan-mode>`;
1421
- const PLAN_MODE_OFF_NOTE = `<plan-mode>
1422
- Plan mode is OFF. Normal tool permissions apply; earlier plan-mode restrictions no longer apply.
1423
- </plan-mode>`;
1424
- function activePlanNote(doc) {
1425
- return `<active-plan id="${doc.planId}">
1426
- Context was compacted while you were executing this user-approved plan "${doc.title}". Keep following it and keep the todo list updated.
1427
-
1428
- <plan>
1429
- ${doc.text}
1430
- </plan>
1431
- </active-plan>`;
1432
- }
1433
- function planKickoffText(doc) {
1434
- return `<plan-approved id="${doc.planId}">
1435
- The user approved the plan "${doc.title}"; plan mode is now OFF. Execute it now:
1436
- - First turn its steps into a todo list and keep it updated.
1437
- - Do not re-plan or ask for approval again. If you must deviate materially, explain why first; use ask_user when the choice belongs to the user.
1438
- - Finish with the plan's verification steps and report the results.
1439
-
1440
- <plan>
1441
- ${doc.text}
1442
- </plan>
1443
- </plan-approved>`;
1444
- }
1445
- function planFeedbackText(planId, feedback) {
1446
- return `<plan-feedback id="${planId}">
1447
- The user did not approve the plan. Stay in plan mode, address the feedback below and call submit_plan with a complete revised plan.
1448
-
1449
- <feedback>
1450
- ${feedback}
1451
- </feedback>
1452
- </plan-feedback>`;
1453
- }
1454
- const PLAN_PREFIX = /^<(plan-mode|active-plan)(?: id="[^"]*")?>\n([\s\S]*?)\n<\/\1>(?:\n\n|$)/;
1455
- function splitPlanPrefix(text) {
1456
- const match = PLAN_PREFIX.exec(text);
1457
- if (!match) return { rest: text };
1458
- const note = match[1] === "active-plan" ? "active-plan" : match[2].includes("Plan mode is ON") ? "on" : "off";
1459
- return { note, rest: text.slice(match[0].length) };
1460
- }
1461
- const KICKOFF = /^<plan-approved id="([^"]*)">\nThe user approved the plan "([\s\S]*?)"; plan mode/;
1462
- const FEEDBACK = /^<plan-feedback id="([^"]*)">\n[\s\S]*?<feedback>\n([\s\S]*)\n<\/feedback>\n<\/plan-feedback>$/;
1463
- function parsePlanMessage(text) {
1464
- const kickoff = KICKOFF.exec(text);
1465
- if (kickoff) return { kind: "approved", planId: kickoff[1], title: kickoff[2] };
1466
- const feedback = FEEDBACK.exec(text);
1467
- return feedback ? { kind: "feedback", planId: feedback[1], feedback: feedback[2] } : null;
1468
- }
1469
- const MASK_WHERE = [
1470
- "system",
1471
- "user",
1472
- "tool_result",
1473
- "tool_args",
1474
- "assistant",
1475
- "tools"
1476
- ];
1477
- class MaskReportBuilder {
1478
- hits = /* @__PURE__ */ new Map();
1479
- blocked = false;
1480
- restored = 0;
1481
- add(hit, count2 = 1) {
1482
- const key = `${hit.kind}\0${hit.rule}\0${hit.action}\0${hit.where}\0${hit.token}`;
1483
- const prev = this.hits.get(key);
1484
- if (prev) prev.count += count2;
1485
- else this.hits.set(key, { ...hit, count: count2 });
1486
- }
1487
- get empty() {
1488
- return this.hits.size === 0 && this.restored === 0;
1489
- }
1490
- build() {
1491
- return {
1492
- hits: [...this.hits.values()].map((h) => ({ ...h })),
1493
- blocked: this.blocked,
1494
- restored: this.restored
1495
- };
1496
- }
1497
- }
1498
- const ACTIONS = /* @__PURE__ */ new Set(["mask", "warn", "block"]);
1499
- const WHERE = new Set(MASK_WHERE);
1500
- const short = (v, max) => typeof v === "string" && v.length > 0 && v.length <= max;
1501
- const count = (v) => Number.isSafeInteger(v) && v >= 0;
1502
- function parseHit(value) {
1503
- if (!value || typeof value !== "object") return void 0;
1504
- const h = value;
1505
- if (!short(h.kind, 32) || !/^[A-Z][A-Z_]*$/.test(h.kind) || !short(h.rule, 32) || !ACTIONS.has(h.action) || !WHERE.has(h.where) || !short(h.token, 16) || !/^[a-z2-7]+$/.test(h.token) || !short(h.preview, 40) || !count(h.count))
1506
- return void 0;
1507
- return {
1508
- kind: h.kind,
1509
- rule: h.rule,
1510
- action: h.action,
1511
- where: h.where,
1512
- token: h.token,
1513
- preview: h.preview,
1514
- count: h.count
1515
- };
1516
- }
1517
- function parseMaskReport(value) {
1518
- if (!value || typeof value !== "object") return void 0;
1519
- const r = value;
1520
- if (!Array.isArray(r.hits) || typeof r.blocked !== "boolean" || !count(r.restored))
1521
- return void 0;
1522
- const hits = r.hits.slice(0, 200).flatMap((h) => parseHit(h) ?? []);
1523
- return { hits, blocked: r.blocked, restored: r.restored };
1524
- }
1525
- function mergeMaskReports(a, b) {
1526
- if (!a) return b;
1527
- const builder = new MaskReportBuilder();
1528
- for (const h of [...a.hits, ...b.hits]) builder.add(h, h.count);
1529
- builder.blocked = a.blocked || b.blocked;
1530
- builder.restored = a.restored + b.restored;
1531
- return builder.build();
1532
- }
1533
- const PRIVACY_MASK_ENTRY = "enso-privacy-mask";
1534
- function parsePrivacyMaskRecord(value) {
1535
- if (!value || typeof value !== "object") return void 0;
1536
- const r = value;
1537
- const report = parseMaskReport(r.report);
1538
- if (!report || !count(r.at) || !short(r.provider, 200) || !short(r.model, 200) || r.source !== "session" && r.source !== "compaction" && r.source !== "aux" || r.sessionId !== void 0 && !short(r.sessionId, 200))
1539
- return void 0;
1540
- return {
1541
- at: r.at,
1542
- provider: r.provider,
1543
- model: r.model,
1544
- source: r.source,
1545
- ...r.sessionId !== void 0 ? { sessionId: r.sessionId } : {},
1546
- report
1547
- };
1548
- }
1549
- const PERSONAL_KINDS = ["email", "phone", "idCard", "bankCard", "ip"];
1550
- const DEFAULT_PRIVACY_MASK_SETTINGS = {
1551
- enabled: false,
1552
- secrets: { enabled: true, shape: false },
1553
- personal: { enabled: false, kinds: ["email", "phone", "idCard", "bankCard"] }
1554
- };
1555
- const rec = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
1556
- const bool = (v, d) => typeof v === "boolean" ? v : d;
1557
- const action = (v) => v === "mask" || v === "warn" || v === "block" ? v : "mask";
1558
- const strings = (v) => Array.isArray(v) ? [...new Set(v.flatMap((x) => typeof x === "string" && x.trim() ? [x.trim()] : []))] : [];
1559
- function parsePrivacyMaskSettings(value) {
1560
- const d = DEFAULT_PRIVACY_MASK_SETTINGS;
1561
- const v = rec(value);
1562
- const s = rec(v.secrets);
1563
- const p = rec(v.personal);
1564
- const c = rec(v.custom);
1565
- return {
1566
- enabled: bool(v.enabled, d.enabled),
1567
- secrets: {
1568
- enabled: bool(s.enabled, d.secrets.enabled),
1569
- action: action(s.action),
1570
- shape: bool(s.shape, d.secrets.shape)
1571
- },
1572
- personal: {
1573
- enabled: bool(p.enabled, d.personal.enabled),
1574
- action: action(p.action),
1575
- kinds: Array.isArray(p.kinds) ? strings(p.kinds).filter(
1576
- (k) => PERSONAL_KINDS.includes(k)
1577
- ) : [...d.personal.kinds]
1578
- },
1579
- custom: { words: strings(c.words), rules: strings(c.rules), action: action(c.action) },
1580
- allow: strings(v.allow)
1581
- };
1582
- }
1583
- const HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1584
- const INVALID_HEADER_VALUE_RE = /[^\t\x20-\x7e\x80-\xff]/;
1585
- function isSendableHeaderValue(value) {
1586
- return !INVALID_HEADER_VALUE_RE.test(value);
1587
- }
1588
- const droppedHeaderWarnings = /* @__PURE__ */ new Set();
1589
- function warnDroppedHeader(name) {
1590
- if (droppedHeaderWarnings.has(name)) return;
1591
- droppedHeaderWarnings.add(name);
1592
- console.warn(`[provider-headers] dropped ${name}: value cannot be sent as a header`);
1593
- }
1594
- function parseProviderHeaders(value, { warn = true } = {}) {
1595
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1596
- const headers = {};
1597
- for (const [name, headerValue] of Object.entries(value)) {
1598
- if (!HEADER_NAME_RE.test(name)) continue;
1599
- if (typeof headerValue !== "string") continue;
1600
- if (!isSendableHeaderValue(headerValue)) {
1601
- if (warn) warnDroppedHeader(name);
1602
- continue;
1603
- }
1604
- headers[name] = headerValue;
1605
- }
1606
- return Object.keys(headers).length > 0 ? headers : void 0;
1607
- }
1608
- function escapePiConfigValue(value) {
1609
- const doubled = value.replaceAll("$", () => "$$");
1610
- return doubled.startsWith("!") ? `$${doubled}` : doubled;
1611
- }
1612
- function parseRequestBodyUsage(value) {
1613
- if (!isRecord$3(value)) return null;
1614
- const keys = ["bytes", "limitBytes", "stage", "blocked", "at"];
1615
- if (Object.keys(value).length !== keys.length || Object.keys(value).some((key) => !keys.includes(key)))
1616
- return null;
1617
- if (typeof value.bytes !== "number" || !Number.isSafeInteger(value.bytes) || value.bytes < 0 || typeof value.limitBytes !== "number" || !Number.isSafeInteger(value.limitBytes) || value.limitBytes <= 0 || typeof value.at !== "number" || !Number.isSafeInteger(value.at) || value.at < 0 || value.stage !== "payload" && value.stage !== "wire" || typeof value.blocked !== "boolean" || value.blocked !== value.bytes > value.limitBytes)
1618
- return null;
1619
- return {
1620
- bytes: value.bytes,
1621
- limitBytes: value.limitBytes,
1622
- stage: value.stage,
1623
- blocked: value.blocked,
1624
- at: value.at
1625
- };
1626
- }
1627
- function isRecord$3(value) {
1628
- return value !== null && typeof value === "object" && !Array.isArray(value);
1629
- }
1630
- const cap = (text, limit) => text.length > limit ? `${text.slice(0, limit)}…` : text;
1631
- function parseRtkToolStats(value) {
1632
- if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
1633
- const record2 = value;
1634
- const { status, originalCommand, rewrittenCommand, inputTokens, outputTokens, reason } = record2;
1635
- if (status !== "compressed" && status !== "unchanged" && status !== "pending" && status !== "bypassed" && status !== "unavailable" || typeof originalCommand !== "string" || rewrittenCommand !== void 0 && typeof rewrittenCommand !== "string" || reason !== void 0 && typeof reason !== "string")
1636
- return void 0;
1637
- const result = { status, originalCommand: cap(originalCommand, 16e3) };
1638
- if (rewrittenCommand !== void 0) result.rewrittenCommand = cap(rewrittenCommand, 16e3);
1639
- if (reason !== void 0) result.reason = cap(reason, 1e3);
1640
- if (inputTokens !== void 0 || outputTokens !== void 0) {
1641
- if (typeof inputTokens !== "number" || !Number.isSafeInteger(inputTokens) || inputTokens < 0 || typeof outputTokens !== "number" || !Number.isSafeInteger(outputTokens) || outputTokens < 0)
1642
- return void 0;
1643
- result.inputTokens = inputTokens;
1644
- result.outputTokens = outputTokens;
1645
- }
1646
- return result;
1647
- }
1648
- const NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/u;
1649
- const SKILL_NAME_MAX = 48;
1650
- const SKILL_DESCRIPTION_MAX = 1024;
1651
- const SKILL_BODY_MAX = 2e4;
1652
- function isSecretarySlug(value) {
1653
- return typeof value === "string" && value.length <= SKILL_NAME_MAX && NAME_RE.test(value);
1654
- }
1655
- const isSecretarySkillName = isSecretarySlug;
1656
- function parseSecretarySkillDraft(value) {
1657
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1658
- return { ok: false, error: "invalid skill" };
1659
- }
1660
- const record2 = value;
1661
- const name = typeof record2.name === "string" ? record2.name.trim() : "";
1662
- if (!isSecretarySkillName(name)) return { ok: false, error: "invalid skill name" };
1663
- const description = typeof record2.description === "string" ? record2.description.trim() : "";
1664
- if (!description || description.length > SKILL_DESCRIPTION_MAX || /[\r\n]/u.test(description)) {
1665
- return { ok: false, error: "invalid skill description" };
1666
- }
1667
- const body = typeof record2.body === "string" ? record2.body.trim() : "";
1668
- if (!body || body.length > SKILL_BODY_MAX) return { ok: false, error: "invalid skill body" };
1669
- return { ok: true, draft: { name, description, body } };
1670
- }
1671
- function renderSecretarySkillFile(draft) {
1672
- const frontmatter = stringify({ name: draft.name, description: draft.description });
1673
- return `---
1674
- ${frontmatter}---
1675
-
1676
- ${draft.body}
1677
- `;
1678
- }
1679
- function parseSecretarySkillFile(raw) {
1680
- const text = raw.replace(/^\uFEFF/u, "");
1681
- if (!text.startsWith("---")) return null;
1682
- const end = text.indexOf("\n---", 3);
1683
- if (end < 0) return null;
1684
- let fields;
1685
- try {
1686
- fields = parse(text.slice(3, end));
1687
- } catch {
1688
- return null;
1689
- }
1690
- if (!fields || typeof fields !== "object") return null;
1691
- const { name, description } = fields;
1692
- const parsed = parseSecretarySkillDraft({
1693
- name,
1694
- description,
1695
- body: text.slice(end + 4)
1696
- });
1697
- return parsed.ok ? parsed.draft : null;
1698
- }
1699
- const TOOL_DESCRIPTION_MAX = 1024;
1700
- const TOOL_PARAMETERS_MAX = 8 * 1024;
1701
- const TOOL_CODE_MAX = 5e4;
1702
- const TOOL_TIMEOUT_DEFAULT = 60;
1703
- const TOOL_TIMEOUT_MAX = 300;
1704
- const TOOL_DESCRIPTOR_MAX = 50;
1705
- const TOOL_OUTPUT_MAX = 2e4;
1706
- const TOOL_RUN_TIMEOUT_MS = (TOOL_TIMEOUT_MAX + 5) * 1e3;
1707
- const TOOL_ID_RE = /^my_[a-z0-9]+(_[a-z0-9]+)*$/u;
1708
- const TOOL_ID_MAX = 60;
1709
- const DESCRIPTOR_KEYS = ["name", "description", "parameters", "readOnly"];
1710
- function secretaryToolScriptFile(runtime) {
1711
- return runtime === "python" ? "main.py" : "main.mjs";
1712
- }
1713
- function secretaryToolId(name) {
1714
- return `my_${name.replace(/-/gu, "_")}`;
1715
- }
1716
- function record(value) {
1717
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1718
- }
1719
- function validToolParameters(parameters) {
1720
- const fields = parameters.properties === void 0 ? {} : record(parameters.properties);
1721
- if (!fields) return false;
1722
- if (!Object.values(fields).every((value) => record(value) !== null)) return false;
1723
- const required = parameters.required;
1724
- if (required === void 0) return true;
1725
- return Array.isArray(required) && required.every((name) => typeof name === "string" && Object.hasOwn(fields, name));
1726
- }
1727
- function parseSecretaryToolDraft(value) {
1728
- const fields = record(value);
1729
- if (!fields) return { ok: false, error: "invalid tool" };
1730
- const name = typeof fields.name === "string" ? fields.name.trim() : "";
1731
- if (!isSecretarySlug(name)) return { ok: false, error: "invalid tool name" };
1732
- const description = typeof fields.description === "string" ? fields.description.trim() : "";
1733
- if (!description || description.length > TOOL_DESCRIPTION_MAX || /[\r\n]/u.test(description)) {
1734
- return { ok: false, error: "invalid tool description" };
1735
- }
1736
- const runtime = fields.runtime;
1737
- if (runtime !== "python" && runtime !== "node") {
1738
- return { ok: false, error: "invalid tool runtime" };
1739
- }
1740
- const parameters = record(fields.parameters);
1741
- if (parameters?.type !== "object" || !validToolParameters(parameters)) {
1742
- return { ok: false, error: "invalid tool parameters" };
1743
- }
1744
- let serialized;
1745
- try {
1746
- serialized = JSON.stringify(parameters);
1747
- } catch {
1748
- return { ok: false, error: "invalid tool parameters" };
1749
- }
1750
- if (serialized.length > TOOL_PARAMETERS_MAX) {
1751
- return { ok: false, error: "invalid tool parameters" };
1752
- }
1753
- const readOnly = fields.readOnly === void 0 ? false : fields.readOnly;
1754
- if (typeof readOnly !== "boolean") return { ok: false, error: "invalid tool readOnly" };
1755
- const timeout = fields.timeoutSec;
1756
- if (timeout !== void 0 && timeout !== null && (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < 1 || timeout > TOOL_TIMEOUT_MAX)) {
1757
- return { ok: false, error: "invalid tool timeout" };
1758
- }
1759
- const code = typeof fields.code === "string" ? fields.code.trim() : "";
1760
- if (!code || code.length > TOOL_CODE_MAX) return { ok: false, error: "invalid tool code" };
1761
- return {
1762
- ok: true,
1763
- draft: {
1764
- name,
1765
- description,
1766
- runtime,
1767
- parameters,
1768
- readOnly,
1769
- ...typeof timeout === "number" ? { timeoutSec: timeout } : {},
1770
- code
1771
- }
1772
- };
1773
- }
1774
- function renderSecretaryToolFile(draft) {
1775
- const { code: _code, ...meta } = draft;
1776
- return `${JSON.stringify(meta, null, 2)}
1777
- `;
1778
- }
1779
- function parseSecretaryToolFile(raw, code) {
1780
- let fields;
1781
- try {
1782
- fields = JSON.parse(raw.replace(/^\uFEFF/u, ""));
1783
- } catch {
1784
- return null;
1785
- }
1786
- const parsed = parseSecretaryToolDraft({ ...record(fields) ?? {}, code });
1787
- return parsed.ok ? parsed.draft : null;
1788
- }
1789
- function secretaryToolDescriptor(draft) {
1790
- return {
1791
- name: secretaryToolId(draft.name),
1792
- description: draft.description,
1793
- parameters: draft.parameters,
1794
- readOnly: draft.readOnly
1795
- };
1796
- }
1797
- function parseSecretaryToolDescriptors(value) {
1798
- if (!Array.isArray(value) || value.length > TOOL_DESCRIPTOR_MAX) return null;
1799
- const out = [];
1800
- const seen = /* @__PURE__ */ new Set();
1801
- for (const entry of value) {
1802
- const fields = record(entry);
1803
- if (!fields || Object.keys(fields).length !== DESCRIPTOR_KEYS.length) return null;
1804
- if (!DESCRIPTOR_KEYS.every((key) => key in fields)) return null;
1805
- const name = fields.name;
1806
- const description = fields.description;
1807
- const parameters = record(fields.parameters);
1808
- const readOnly = fields.readOnly;
1809
- if (typeof name !== "string" || name.length > TOOL_ID_MAX || !TOOL_ID_RE.test(name) || seen.has(name) || typeof description !== "string" || !description || description.length > TOOL_DESCRIPTION_MAX || !parameters || parameters.type !== "object" || typeof readOnly !== "boolean") {
1810
- return null;
1811
- }
1812
- seen.add(name);
1813
- out.push({ name, description, parameters, readOnly });
1814
- }
1815
- return out;
1816
- }
1817
- const WINDOWS_LOCAL_SHELLS = ["auto", "powershell", "bash"];
1818
- function parseWindowsLocalShell(value) {
1819
- return typeof value === "string" && WINDOWS_LOCAL_SHELLS.includes(value) ? value : "auto";
1820
- }
1821
- const WORKSPACE_WRITE_TOOL_ID = "workspace_write";
1822
- function childProfileToolIds(tools, options = {}) {
1823
- const editMode = options.editMode ?? "apply_patch";
1824
- const shell = options.shell ?? "bash";
1825
- const ids = ["read", "grep", "find", "ls"];
1826
- if (tools === "all" && options.workspaceWrite !== false) {
1827
- ids.push(shell);
1828
- if (editMode === "apply_patch") ids.push("apply_patch");
1829
- else ids.push("edit", "write");
1830
- ids.push("task_output", "task_stop", "task_settle");
1831
- }
1832
- ids.push("message_main_agent", "message_coworker");
1833
- if (options.exploreFold) ids.push("explore_mark", "explore_fold");
1834
- if (options.isolatedSandbox !== false) ids.push("codemode");
1835
- return ids;
1836
- }
1837
- function childProfileShell(input) {
1838
- if (input.remote) return "bash";
1839
- if (input.platform !== "win32") return "bash";
1840
- return parseWindowsLocalShell(input.preference) === "bash" ? "bash" : "powershell";
1841
- }
1842
- const WEB_SEARCH_CHAIN_MAX = 8;
1843
- function isXaiResponsesHost(baseUrl) {
1844
- try {
1845
- return new URL(baseUrl).hostname === "api.x.ai";
1846
- } catch {
1847
- return false;
1848
- }
1849
- }
1850
- function nativeSearchKindFor(api, baseUrl) {
1851
- switch (api) {
1852
- case "anthropic-messages":
1853
- return "anthropic";
1854
- case "openai-responses":
1855
- return "responses";
1856
- case "openai-codex-responses":
1857
- return "codex";
1858
- case "google-generative-ai":
1859
- return "gemini";
1860
- case "google-antigravity":
1861
- // antigravity.ts 的 ANTIGRAVITY_API_ID:provider 注册进 pi runtime 后,
1862
- // composeModelProvider 会用 config.api 给每个模型盖戳,registry 里 Antigravity
1863
- // 模型实际携带的是带 -cca 后缀的 id。漏认会被「no native web search support」
1864
- // 静默跳过——请求都发不出去。
1865
- case "google-antigravity-cca":
1866
- return "antigravity";
1867
- case "openai-completions":
1868
- return isXaiResponsesHost(baseUrl) ? "responses" : void 0;
1869
- default:
1870
- return void 0;
1871
- }
1872
- }
1873
- function isWebSearchChainEntry(value) {
1874
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1875
- const entry = value;
1876
- return typeof entry.providerId === "string" && entry.providerId.trim() !== "" && typeof entry.modelId === "string" && entry.modelId.trim() !== "";
1877
- }
1878
- function parseWebSearchChain(value) {
1879
- if (!Array.isArray(value)) return [];
1880
- const out = [];
1881
- const seen = /* @__PURE__ */ new Set();
1882
- for (const item of value) {
1883
- if (!isWebSearchChainEntry(item)) continue;
1884
- const providerId = item.providerId.trim();
1885
- const modelId = item.modelId.trim();
1886
- const key = `${providerId}
1887
- ${modelId}`;
1888
- if (seen.has(key)) continue;
1889
- seen.add(key);
1890
- out.push({ providerId, modelId });
1891
- if (out.length >= WEB_SEARCH_CHAIN_MAX) break;
1892
- }
1893
- return out;
1894
- }
1895
- const BUILTIN_TOOLS = [
1896
- {
1897
- id: "image_generation",
1898
- name: "ImageGen",
1899
- description: "Generate images with the configured image model and save them to the session scratch directory"
1900
- },
1901
- {
1902
- id: "subagent",
1903
- name: "Subagent",
1904
- description: "Unified agents: delegate one-shot tasks or keep persistent coworkers under Main control"
1905
- },
1906
- {
1907
- id: "workflow",
1908
- name: "Workflow",
1909
- description: "Run a JavaScript workflow that fans work out across subagents. Live status appears in the side panel."
1910
- },
1911
- { id: "todo", name: "Todo", description: "Task list: track progress on multi-step work" },
1912
- {
1913
- id: "plan",
1914
- name: "Plan mode",
1915
- description: "Plan mode: research read-only, submit a plan for approval, then carry it out after approval"
1916
- },
1917
- {
1918
- id: "ask_user",
1919
- name: "Ask user",
1920
- description: "Ask the user a question and wait for an answer (options / timeout)"
1921
- },
1922
- {
1923
- id: "browser",
1924
- name: "Browser",
1925
- description: "Built-in browser: open pages in Enso's own Chromium, read snapshots, click and type by ref"
1926
- },
1927
- {
1928
- id: "web",
1929
- name: "Web search",
1930
- description: "Web search and fetch: search with the session model's built-in search (falls back to a keyless service) and read public pages as markdown"
1931
- },
1932
- {
1933
- id: "background_tasks",
1934
- name: "Background tasks",
1935
- description: "Background shell task: run long commands in the background and notify on completion"
1936
- },
1937
- {
1938
- id: "memory",
1939
- name: "Memory",
1940
- description: "Long-term memory: the agent can search, capture and consolidate durable decisions, preferences and lessons across sessions"
1941
- },
1942
- {
1943
- id: "turn_discard",
1944
- name: "Turn discard",
1945
- description: "Let the agent drop an irrelevant automatic delivery or throwaway exchange from its context; the timeline keeps it and turn_recall can read it back"
1946
- },
1947
- {
1948
- id: "isolated_sandbox",
1949
- name: "Isolated sandbox",
1950
- description: "Run JavaScript in an isolated sandbox that can call session tools. Intermediate reads and edits stay out of the chat; only the returned value is added to the conversation."
1951
- },
1952
- {
1953
- id: "computer",
1954
- name: "Computer",
1955
- description: "Host desktop: list windows, screenshot, accessibility tree, and input. Default off. Not the built-in browser."
1956
- }
1957
- ];
1958
- const DEFAULT_DISABLED_BUILTIN_TOOLS = ["memory", "computer"];
1959
- const COMPUTER_DEFAULT_OFF_SETTINGS_VERSION = 14;
1960
- function withComputerDisabled(entry) {
1961
- if (!Array.isArray(entry.disabledBuiltinTools)) return entry;
1962
- const list = entry.disabledBuiltinTools.filter((id) => typeof id === "string");
1963
- return list.includes("computer") ? entry : { ...entry, disabledBuiltinTools: [...list, "computer"] };
1964
- }
1965
- function addComputerDefaultOff(state) {
1966
- const migrated = withComputerDisabled(state);
1967
- if (!Array.isArray(migrated.projects)) return migrated;
1968
- return {
1969
- ...migrated,
1970
- projects: migrated.projects.map(
1971
- (project) => project && typeof project === "object" && !Array.isArray(project) ? withComputerDisabled(project) : project
1972
- )
1973
- };
1974
- }
1975
- function persistedSettingsState(persisted) {
1976
- if (!persisted || typeof persisted !== "object" || Array.isArray(persisted)) return void 0;
1977
- const { state, version } = persisted;
1978
- if (!state || typeof state !== "object" || Array.isArray(state)) return void 0;
1979
- const current = typeof version === "number" ? version : 0;
1980
- const record2 = state;
1981
- const base = current < COMPUTER_DEFAULT_OFF_SETTINGS_VERSION ? addComputerDefaultOff(record2) : record2;
1982
- if (base.webSearchChain === void 0) return base;
1983
- return { ...base, webSearchChain: parseWebSearchChain(base.webSearchChain) };
1984
- }
1985
- function effectiveSubagentAllowedModes(configured, disabledBuiltinTools) {
1986
- if (Array.isArray(configured)) {
1987
- const selected = new Set(
1988
- configured.filter(
1989
- (mode) => mode === "task" || mode === "coworker"
1990
- )
1991
- );
1992
- return ["task", "coworker"].filter((mode) => selected.has(mode));
1993
- }
1994
- const disabled = new Set(
1995
- Array.isArray(disabledBuiltinTools) ? disabledBuiltinTools.filter((id) => typeof id === "string") : []
1996
- );
1997
- return ["task", "coworker"].filter(
1998
- (mode) => !disabled.has(mode === "task" ? "subagent" : "coworker")
1999
- );
2000
- }
2001
- function effectiveDisabledBuiltinTools(disabled) {
2002
- return Array.isArray(disabled) ? disabled.filter((id) => typeof id === "string") : [...DEFAULT_DISABLED_BUILTIN_TOOLS];
2003
- }
2004
- function resolveDisabledBuiltinTools(globalDisabled, project) {
2005
- return Array.isArray(project?.disabledBuiltinTools) ? effectiveDisabledBuiltinTools(project.disabledBuiltinTools) : effectiveDisabledBuiltinTools(globalDisabled);
2006
- }
2007
- function projectDisabledBuiltinTools(projects, projectId) {
2008
- if (!projectId || !Array.isArray(projects)) return void 0;
2009
- for (const entry of projects) {
2010
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
2011
- const record2 = entry;
2012
- if (record2.id === projectId) return record2.disabledBuiltinTools;
2013
- }
2014
- return void 0;
2015
- }
2016
- const SILENT_MARKER = "<secretary-silent/>";
2017
- const SILENCE_TURN_TOOL = "silence_turn";
2018
- function messageText(message) {
2019
- const content = message.content;
2020
- if (typeof content === "string") return content;
2021
- if (!Array.isArray(content)) return "";
2022
- return content.map((part) => {
2023
- if (!part || typeof part !== "object") return "";
2024
- const text = part.text;
2025
- return part.type === "text" && typeof text === "string" ? text : "";
2026
- }).join("");
2027
- }
2028
- function isPureSessionUpdate(text) {
2029
- if (!/<session-updates>|<secretary-schedule>|<secretary-message>/.test(text)) return false;
2030
- const stripped = text.replace(/<session-updates>[\s\S]*?<\/session-updates>/g, "").replace(/<secretary-schedule>[\s\S]*?<\/secretary-schedule>/g, "").replace(/<secretary-message>[\s\S]*?<\/secretary-message>/g, "").trim();
2031
- return stripped.length === 0;
2032
- }
2033
- function isSilentMarker(text) {
2034
- return text.trim() === SILENT_MARKER;
2035
- }
2036
- function calledSilenceTurn(message) {
2037
- if (message.toolName === SILENCE_TURN_TOOL) return true;
2038
- if (message.role !== "assistant" || !Array.isArray(message.content)) return false;
2039
- return message.content.some((part) => {
2040
- if (!part || typeof part !== "object") return false;
2041
- const record2 = part;
2042
- return record2.type === "toolCall" && record2.name === SILENCE_TURN_TOOL;
2043
- });
2044
- }
2045
- function turnCalledSilenceTurn(messages, fromIndex = 0) {
2046
- return messages.slice(Math.max(0, fromIndex)).some((message) => calledSilenceTurn(message));
2047
- }
2048
- function shouldSilenceTurn(userText, assistantText, calledSilence = false) {
2049
- return isPureSessionUpdate(userText) && (calledSilence || isSilentMarker(assistantText));
2050
- }
2051
- function turnRequestedSilence(messages, fromIndex = 0) {
2052
- const turn = messages.slice(Math.max(0, fromIndex));
2053
- let userText = "";
2054
- let assistantText = "";
2055
- let called = false;
2056
- for (const message of turn) {
2057
- if (calledSilenceTurn(message)) called = true;
2058
- if (message.role === "user") {
2059
- const text = messageText(message);
2060
- if (text) userText = userText ? `${userText}
2061
- ${text}` : text;
2062
- } else if (message.role === "assistant") {
2063
- const text = messageText(message).trim();
2064
- if (text) assistantText = text;
2065
- }
2066
- }
2067
- return shouldSilenceTurn(userText, assistantText, called);
2068
- }
2069
- function sessionIdsInUpdates(text) {
2070
- return [...text.matchAll(/session:([0-9a-z-]+)/gi)].map((match) => match[1]);
2071
- }
2072
- const SECRETARY_OPS = [
2073
- "project_list",
2074
- "project_info",
2075
- "repo_status",
2076
- "session_list",
2077
- "session_read",
2078
- "session_tasks",
2079
- "session_activity",
2080
- "session_create",
2081
- "session_send",
2082
- "session_queue_list",
2083
- "session_queue_cancel",
2084
- "session_stop",
2085
- "session_task_stop",
2086
- "session_archive",
2087
- "result_mark_done",
2088
- "result_mark_undo",
2089
- "session_answer",
2090
- "session_takeover_propose",
2091
- "image_view",
2092
- "contact_send_file",
2093
- "cleanup_list",
2094
- "cleanup_apply",
2095
- "todo_list",
2096
- "todo_item_add",
2097
- "todo_item_update",
2098
- "todo_item_dispatch",
2099
- "schedule_add",
2100
- "schedule_list",
2101
- "schedule_remove",
2102
- "secretary_profile_propose",
2103
- "skill_propose",
2104
- "tool_propose",
2105
- "secretary_list",
2106
- "secretary_message"
2107
- ];
2108
- const SECRETARY_SEND_MODES = ["queue", "steer"];
2109
- const SECRETARY_INTERNAL_OPS = ["tool_run"];
2110
- const SECRETARY_ID_MAX = 200;
2111
- const SECRETARY_SESSION_MESSAGE_MAX = 8e3;
2112
- const SECRETARY_ATTACHMENT_MAX = 5;
2113
- const SECRETARY_ATTACHMENT_PATH_MAX = 1024;
2114
- const SECRETARY_CONTACT_CAPTION_MAX = 2e3;
2115
- const SECRETARY_TOOL_ALLOWLIST = /* @__PURE__ */ new Set([
2116
- ...SECRETARY_OPS,
2117
- // worker 本地只读工具:按 spawn 时实际加载的 skill 表读 SKILL.md,不碰任意路径
2118
- "skill_read",
2119
- "ask_user",
2120
- SILENCE_TURN_TOOL,
2121
- "web_search",
2122
- "web_fetch",
2123
- "memory_search",
2124
- "memory_capture",
2125
- "memory_crystallize",
2126
- "memory_delete"
2127
- ]);
2128
- function isSecretaryToolAllowed(name, extraToolNames) {
2129
- return SECRETARY_TOOL_ALLOWLIST.has(name) || extraToolNames?.has(name) === true;
2130
- }
2131
- const ALLOWED_BUILTIN_GROUPS = /* @__PURE__ */ new Set(["ask_user", "web", "memory"]);
2132
- const SECRETARY_FORCED_DISABLED_TOOLS = [
2133
- ...BUILTIN_TOOLS.map((tool) => tool.id).filter((id) => !ALLOWED_BUILTIN_GROUPS.has(id)),
2134
- WORKSPACE_WRITE_TOOL_ID,
2135
- "goal"
2136
- ];
2137
- const SECRETARY_ALWAYS_ENABLED_TOOLS = ["memory"];
2138
- const SHELL_QUIET_MS = 15e3;
2139
- const SHELL_LIMITS = Object.freeze({
2140
- yieldDefaultMs: 45e3,
2141
- yieldBuildMs: 18e4,
2142
- yieldServerMs: 1e4,
2143
- quietMs: SHELL_QUIET_MS,
2144
- taskWaitMaxMs: 3e4,
2145
- maxTasks: 20,
2146
- logMaxBytes: 256 * 1024 * 1024,
2147
- killGraceMs: 5e3
2148
- });
2149
- const MAX_TIMER_MS = 2147483647;
2150
- const MS_KEYS = [
2151
- "yieldDefaultMs",
2152
- "yieldBuildMs",
2153
- "yieldServerMs",
2154
- "quietMs",
2155
- "taskWaitMaxMs",
2156
- "killGraceMs"
2157
- ];
2158
- const positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
2159
- function resolveShellLimits(raw) {
2160
- const limits = { ...SHELL_LIMITS };
2161
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return limits;
2162
- const record2 = raw;
2163
- for (const key of MS_KEYS) {
2164
- const value = record2[key];
2165
- if (positive(value) && value <= MAX_TIMER_MS) limits[key] = value;
2166
- }
2167
- if (positive(record2.maxTasks) && record2.maxTasks >= 1) {
2168
- limits.maxTasks = Math.floor(record2.maxTasks);
2169
- }
2170
- if (positive(record2.logMaxBytes)) limits.logMaxBytes = Math.floor(record2.logMaxBytes);
2171
- return limits;
2172
- }
2173
- const SMART_COMPACT_MODES = ["auto", "fast", "balanced", "thorough"];
2174
- function parseSmartCompactMode(value) {
2175
- return typeof value === "string" && SMART_COMPACT_MODES.includes(value) ? value : null;
2176
- }
2177
- const DEFAULT_SSH_TIMEOUT_SECONDS = 30;
2178
- const MIN_SSH_TIMEOUT_SECONDS = 5;
2179
- const MAX_SSH_TIMEOUT_SECONDS = 300;
2180
- function normalizeSshTimeoutSeconds(value) {
2181
- if (typeof value !== "number" || !Number.isInteger(value)) return DEFAULT_SSH_TIMEOUT_SECONDS;
2182
- return Math.min(MAX_SSH_TIMEOUT_SECONDS, Math.max(MIN_SSH_TIMEOUT_SECONDS, value));
2183
- }
2184
- function parseSshTimeoutSeconds(value) {
2185
- if (typeof value !== "number" || !Number.isInteger(value)) return null;
2186
- if (value < MIN_SSH_TIMEOUT_SECONDS || value > MAX_SSH_TIMEOUT_SECONDS) return null;
2187
- return value;
2188
- }
2189
- const TOOL_BATCH_LABEL_SYSTEM_PROMPT = `Write a short summary label describing what these tool calls accomplished. It appears as a single-line row in a mobile app and truncates around 30 characters, so think git-commit-subject, not sentence.
2190
-
2191
- Keep the verb in past tense and the most distinctive noun. Drop articles, connectors, and long location context first. Reply in the same language as the intent text when there is one.
2192
-
2193
- Examples:
2194
- - Searched in auth/
2195
- - Fixed NPE in UserService
2196
- - Created signup endpoint
2197
- - Read config.json
2198
- - Ran failing tests`;
2199
- const FIELD_CHARS = 300;
2200
- const INTENT_CHARS = 200;
2201
- const MAX_TOOLS = 8;
2202
- const LABEL_CHARS = 60;
2203
- const BOOKKEEPING_TOOLS = /* @__PURE__ */ new Set([
2204
- "todo",
2205
- "explore_mark",
2206
- "explore_fold",
2207
- "turn_discard",
2208
- "ask_user"
2209
- ]);
2210
- const clip = (text, max) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
2211
- const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2212
- function contentText(content) {
2213
- if (typeof content === "string") return content;
2214
- if (!Array.isArray(content)) return "";
2215
- return content.filter((part) => isRecord$2(part) && part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
2216
- }
2217
- function toolBatchDigest(message, toolResults) {
2218
- if (!isRecord$2(message) || message.role !== "assistant" || !Array.isArray(message.content))
2219
- return void 0;
2220
- const calls = message.content.filter(
2221
- (part) => isRecord$2(part) && part.type === "toolCall" && typeof part.id === "string" && part.id.length > 0 && typeof part.name === "string"
2222
- );
2223
- if (calls.length === 0 || calls.every((c) => BOOKKEEPING_TOOLS.has(c.name))) return void 0;
2224
- const results = /* @__PURE__ */ new Map();
2225
- for (const r of toolResults)
2226
- if (isRecord$2(r) && typeof r.toolCallId === "string") results.set(r.toolCallId, r);
2227
- const intent = contentText(message.content.filter((p) => isRecord$2(p) && p.type === "text")).trim().replace(/\s+/g, " ");
2228
- return {
2229
- callId: calls[0].id,
2230
- ...intent ? { intent: clip(intent, INTENT_CHARS) } : {},
2231
- tools: calls.slice(0, MAX_TOOLS).map((c) => {
2232
- const r = results.get(c.id);
2233
- let input;
2234
- try {
2235
- input = JSON.stringify(c.arguments ?? {});
2236
- } catch {
2237
- input = "";
2238
- }
2239
- const output = contentText(r?.content).trim();
2240
- return {
2241
- name: c.name,
2242
- input: clip(input, FIELD_CHARS),
2243
- output: clip(r?.isError === true ? `error: ${output}` : output, FIELD_CHARS)
2244
- };
2245
- })
2246
- };
2247
- }
2248
- function toolBatchLabelPrompt(digest) {
2249
- const tools = digest.tools.map((t) => `Tool: ${t.name}
2250
- Input: ${t.input}
2251
- Output: ${t.output}`).join("\n\n");
2252
- const intent = digest.intent ? `User's intent (from assistant's last message): ${digest.intent}
2253
-
2254
- ` : "";
2255
- return `${intent}Tools completed:
2256
-
2257
- ${tools}
2258
-
2259
- Label:`;
2260
- }
2261
- function parseToolBatchDigest(value) {
2262
- if (!isRecord$2(value) || typeof value.callId !== "string" || !value.callId) return null;
2263
- if (value.intent !== void 0 && (typeof value.intent !== "string" || value.intent.length > INTENT_CHARS))
2264
- return null;
2265
- if (!Array.isArray(value.tools) || value.tools.length === 0 || value.tools.length > MAX_TOOLS)
2266
- return null;
2267
- const fieldOk = (v) => typeof v === "string" && v.length <= FIELD_CHARS;
2268
- if (!value.tools.every(
2269
- (t) => isRecord$2(t) && typeof t.name === "string" && t.name.length > 0 && t.name.length <= FIELD_CHARS && fieldOk(t.input) && fieldOk(t.output)
2270
- ))
2271
- return null;
2272
- return value;
2273
- }
2274
- function cleanToolBatchLabel(text) {
2275
- const line = text.split("\n").map((l) => l.trim()).find(Boolean);
2276
- if (!line) return void 0;
2277
- const label = line.replace(/^label:\s*/i, "").replace(/^[-*•]\s+/, "").replace(/^["'`“”]+|["'`“”]+$/g, "").trim();
2278
- if (!label || /^(error\b|i cannot\b|i can't\b|sorry\b)/i.test(label)) return void 0;
2279
- return clip(label, LABEL_CHARS);
2280
- }
2281
- const EDIT_MODES = ["replace", "apply_patch"];
2282
- function isEditMode(value) {
2283
- return typeof value === "string" && EDIT_MODES.includes(value);
2284
- }
2285
- function resolveEditMode(editMode, _legacyHashlineEnabled) {
2286
- if (isEditMode(editMode)) return editMode;
2287
- return "apply_patch";
2288
- }
2289
- const PROJECTED_FILE_CHANGE_LIMIT = 256;
2290
- const PROJECTED_FILE_TEXT_LIMIT = 32768;
2291
- const PROJECTED_APPLY_PATCH_PATH_COUNT_LIMIT = 100;
2292
- const PROJECTED_APPLY_PATCH_PATH_TEXT_LIMIT = 4096;
2293
- const MODEL_API_KINDS = [
2294
- "openai-completions",
2295
- "openai-responses",
2296
- "anthropic-messages",
2297
- "google-generative-ai",
2298
- "ollama",
2299
- "typesafe-system-one"
2300
- ];
2301
- const MODEL_REASONING_OVERRIDES = ["on", "off"];
2302
- const MODEL_THINKING_LEVEL_OVERRIDES = [
2303
- "minimal",
2304
- "low",
2305
- "medium",
2306
- "high",
2307
- "xhigh",
2308
- "max"
2309
- ];
2310
- const hasProviderCredentials = (provider) => Boolean(provider.apiKey || provider.oauthAccountKey);
2311
- const isNonEmptyString$1 = (value) => typeof value === "string" && value.length > 0;
2312
- const hasExactKeys$1 = (value, keys) => {
2313
- const actual = Object.keys(value);
2314
- return actual.length === keys.length && actual.every((key) => keys.includes(key));
2315
- };
2316
- const isAttachedImage = (value) => {
2317
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2318
- const image = value;
2319
- return hasExactKeys$1(image, ["data", "mimeType"]) && isNonEmptyString$1(image.data) && isNonEmptyString$1(image.mimeType);
2320
- };
2321
- function parseFileMentionRef(value) {
2322
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2323
- const mention = value;
2324
- if (!hasExactKeys$1(mention, ["id", "relativePath"]) || !isNonEmptyString$1(mention.id) || !isNonEmptyString$1(mention.relativePath)) {
2325
- return null;
2326
- }
2327
- return { id: mention.id, relativePath: mention.relativePath };
2328
- }
2329
- function parseAgentDispatchTask(value) {
2330
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2331
- const task = value;
2332
- if (!hasExactKeys$1(task, ["text", "images", "fileMentions"]) || typeof task.text !== "string" || !Array.isArray(task.images) || task.images.some((image) => !isAttachedImage(image)) || !Array.isArray(task.fileMentions) || task.fileMentions.some((mention) => parseFileMentionRef(mention) === null) || !task.text.trim() && task.images.length === 0) {
2333
- return null;
2334
- }
2335
- return task;
2336
- }
2337
- function parseAgentDispatchRequest(value, knownTypeKeys) {
2338
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2339
- const request = value;
2340
- const typeKey = parseAgentTypeKey(request.typeKey);
2341
- if (!hasExactKeys$1(request, ["requestId", "selectionBindingId", "typeKey", "task"]) || !isNonEmptyString$1(request.requestId) || !isNonEmptyString$1(request.selectionBindingId) || !typeKey || !knownTypeKeys.has(typeKey) || parseAgentDispatchTask(request.task) === null) {
2342
- return null;
2343
- }
2344
- return request;
2345
- }
2346
- function parseParentModelSelectionRequest(value) {
2347
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2348
- const request = value;
2349
- if (!hasExactKeys$1(request, ["parentBindingId", "selection"]) || !isNonEmptyString$1(request.parentBindingId) || !request.selection || typeof request.selection !== "object" || Array.isArray(request.selection)) {
2350
- return null;
2351
- }
2352
- const selection = request.selection;
2353
- return hasExactKeys$1(selection, ["providerId", "modelId"]) && isNonEmptyString$1(selection.providerId) && isNonEmptyString$1(selection.modelId) ? request : null;
2354
- }
2355
- function parseParentSourceBindingRequest(value) {
2356
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2357
- const request = value;
2358
- return hasExactKeys$1(request, ["requestId"]) && isNonEmptyString$1(request.requestId) ? { requestId: request.requestId } : null;
2359
- }
2360
- const WORKFLOW_PRESET_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
2361
- const MAX_DISABLED_WORKFLOW_PRESETS = 64;
2362
- function isWorkflowPresetId(id) {
2363
- return WORKFLOW_PRESET_ID_RE.test(id);
2364
- }
2365
- function parseDisabledWorkflowPresets(value) {
2366
- if (!Array.isArray(value)) return [];
2367
- const ids = value.filter((id) => typeof id === "string" && isWorkflowPresetId(id));
2368
- return [...new Set(ids)].slice(0, MAX_DISABLED_WORKFLOW_PRESETS);
2369
- }
2370
- const RUN_STATUSES = /* @__PURE__ */ new Set(["running", "completed", "failed", "cancelled"]);
2371
- const MEMBER_STATUSES = /* @__PURE__ */ new Set(["running", "completed", "failed"]);
2372
- function isRecord$1(value) {
2373
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
2374
- }
2375
- function bounded(value, max) {
2376
- if (typeof value !== "string") return null;
2377
- const text = value.trim();
2378
- if (!text || text.length > max) return null;
2379
- return text;
2380
- }
2381
- function parseWorkflowRunSnapshot(value) {
2382
- if (!isRecord$1(value)) return null;
2383
- const runId = bounded(value.runId, 80);
2384
- const name = bounded(value.name, 80);
2385
- const description = bounded(value.description, 240);
2386
- if (!runId || !name || !description || !RUN_STATUSES.has(value.status)) {
2387
- return null;
2388
- }
2389
- const phase = value.phase === void 0 ? void 0 : bounded(value.phase, 80);
2390
- if (value.phase !== void 0 && !phase) return null;
2391
- const error = value.error === void 0 ? void 0 : bounded(value.error, 400);
2392
- if (value.error !== void 0 && !error) return null;
2393
- if (!Array.isArray(value.logs) || value.logs.length > 20) return null;
2394
- const logs = [];
2395
- for (const line of value.logs) {
2396
- const text = bounded(line, 160);
2397
- if (!text) return null;
2398
- logs.push(text);
2399
- }
2400
- if (!Array.isArray(value.members) || value.members.length > 32) return null;
2401
- const members = [];
2402
- for (const member of value.members) {
2403
- if (!isRecord$1(member) || !Number.isInteger(member.seq) || member.seq < 1) {
2404
- return null;
2405
- }
2406
- const label = bounded(member.label, 80);
2407
- const memberPhase = member.phase === void 0 ? void 0 : bounded(member.phase, 80);
2408
- const prompt = member.prompt === void 0 ? void 0 : bounded(member.prompt, 160);
2409
- const result = member.result === void 0 ? void 0 : bounded(member.result, 160);
2410
- const childId = member.childId === void 0 ? void 0 : bounded(member.childId, 80);
2411
- if (!label || !MEMBER_STATUSES.has(member.status)) return null;
2412
- if (member.phase !== void 0 && !memberPhase) return null;
2413
- if (!Number.isInteger(member.batch) || member.batch < 1) return null;
2414
- if (member.prompt !== void 0 && !prompt) return null;
2415
- if (member.result !== void 0 && !result) return null;
2416
- if (member.childId !== void 0 && !childId) return null;
2417
- members.push({
2418
- seq: member.seq,
2419
- label,
2420
- batch: member.batch,
2421
- status: member.status,
2422
- ...memberPhase ? { phase: memberPhase } : {},
2423
- ...prompt ? { prompt } : {},
2424
- ...result ? { result } : {},
2425
- ...childId ? { childId } : {}
2426
- });
2427
- }
2428
- return {
2429
- runId,
2430
- name,
2431
- description,
2432
- status: value.status,
2433
- logs,
2434
- members,
2435
- ...phase ? { phase } : {},
2436
- ...error ? { error } : {}
2437
- };
2438
- }
2439
- const TURN_REPORT_MAX_CHARS = 8e3;
2440
- const TITLE_SUMMARY_MAX_CANDIDATES = 3;
2441
- const THINKING_LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"];
2442
- const APPROVAL_MODES = ["supervised", "auto-edits", "full", "assistant"];
2443
- const PROTECTED_ACTION_CATEGORIES = [
2444
- "external-send",
2445
- "delete",
2446
- "payment",
2447
- "deploy",
2448
- "secret",
2449
- "destructive"
2450
- ];
2451
- const BROWSER_OPS = [
2452
- "navigate",
2453
- "snapshot",
2454
- "click",
2455
- "type",
2456
- "fill",
2457
- "press_key",
2458
- "scroll",
2459
- "select_option",
2460
- "click_xy",
2461
- "drag",
2462
- "highlight",
2463
- "bounding_box",
2464
- "screenshot",
2465
- "tabs",
2466
- "lock",
2467
- "close",
2468
- "cdp"
2469
- ];
2470
- const MEMORY_OPS = ["search", "capture", "crystallize", "delete"];
2471
- const COMPUTER_OPS = ["run"];
2472
- const ASK_ANSWER_BY = ["user", "relay", "timeout"];
2473
- const APPROVAL_DECISIONS = ["allow", "allowSession", "deny", "revise", "review"];
2474
- function isApprovalDecision(value) {
2475
- return APPROVAL_DECISIONS.includes(value);
2476
- }
2477
- const TASK_KEEP_REASON_MAX = 200;
2478
- const SHELL_FAILURE_KINDS = [
2479
- "exit_nonzero",
2480
- "deadline",
2481
- "stopped_by_user",
2482
- "tty_required",
2483
- "auth_required",
2484
- "not_found",
2485
- "not_executable",
2486
- "binary_output",
2487
- "output_truncated"
2488
- ];
2489
- function parseShellFailure(value) {
2490
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2491
- const record2 = value;
2492
- if (!SHELL_FAILURE_KINDS.includes(record2.kind)) return null;
2493
- if (typeof record2.retryable !== "boolean") return null;
2494
- if (record2.exitCode !== void 0 && !(typeof record2.exitCode === "number" && Number.isInteger(record2.exitCode))) {
2495
- return null;
2496
- }
2497
- return {
2498
- kind: record2.kind,
2499
- retryable: record2.retryable,
2500
- ...record2.exitCode === void 0 ? {} : { exitCode: record2.exitCode }
2501
- };
2502
- }
2503
- const AGENT_WAIT_DEFAULT_MS = 30 * 1e3;
2504
- const AGENT_WAIT_MAX_MS = 5 * 60 * 1e3;
2505
- const AGENT_TASK_MAX_RESUMES = 3;
2506
- function parseClosed(table, type, value) {
2507
- if (!Object.hasOwn(table, type)) return null;
2508
- return table[type](value);
2509
- }
2510
- function requireEventIdentity(kind, parse2) {
2511
- return (value) => {
2512
- const identity = kind === "child" ? parseChildSessionIdentity(value.identity) : kind === "parent" ? parseSessionIdentity(value.identity) : parseAnySessionIdentity(value.identity);
2513
- if (!identity || !isSequence(value.seq)) return null;
2514
- return parse2(value);
2515
- };
2516
- }
2517
- function parseAgentControlToolRequest(value) {
2518
- if (!isRecord(value) || typeof value.operation !== "string") return null;
2519
- const nonEmpty2 = (input) => typeof input === "string" && input.trim().length > 0;
2520
- const optionalString = (input) => input === void 0 || nonEmpty2(input);
2521
- const schemaValid = value.schema === void 0 || isRecord(value.schema);
2522
- const gateValid = (gate) => {
2523
- if (!isRecord(gate)) return false;
2524
- return hasExactKeys(gate, ["commandRef"]) && nonEmpty2(gate.commandRef);
2525
- };
2526
- const optionalGate = value.gate === void 0 || gateValid(value.gate);
2527
- const parseRunIdOperation = (value2) => {
2528
- return hasExactKeys(value2, ["operation", "runId"]) && nonEmpty2(value2.runId) ? value2 : null;
2529
- };
2530
- const parseAgentIdOperation = (value2) => {
2531
- return hasExactKeys(value2, ["operation", "agentId"]) && nonEmpty2(value2.agentId) ? value2 : null;
2532
- };
2533
- const parsers = {
2534
- spawn: (value2) => {
2535
- return hasOnlyKeys(value2, [
2536
- "operation",
2537
- "mode",
2538
- "name",
2539
- "description",
2540
- "prompt",
2541
- "agentType",
2542
- "model",
2543
- "thinking",
2544
- "wait",
2545
- "schema",
2546
- "gate"
2547
- ]) && (value2.mode === "task" || value2.mode === "coworker") && optionalString(value2.name) && nonEmpty2(value2.description) && nonEmpty2(value2.prompt) && optionalString(value2.agentType) && optionalString(value2.model) && (value2.thinking === void 0 || value2.thinking === "off" || THINKING_LEVELS.includes(value2.thinking)) && typeof value2.wait === "boolean" && schemaValid && optionalGate ? value2 : null;
2548
- },
2549
- send: (value2) => {
2550
- return hasOnlyKeys(value2, [
2551
- "operation",
2552
- "agentId",
2553
- "message",
2554
- "delivery",
2555
- "expectedRunId",
2556
- "wait",
2557
- "schema",
2558
- "gate"
2559
- ]) && nonEmpty2(value2.agentId) && nonEmpty2(value2.message) && (value2.delivery === "auto" || value2.delivery === "steer" || value2.delivery === "next") && optionalString(value2.expectedRunId) && typeof value2.wait === "boolean" && schemaValid && optionalGate ? value2 : null;
2560
- },
2561
- wait: (value2) => {
2562
- return hasOnlyKeys(value2, ["operation", "runIds", "until", "timeoutMs"]) && Array.isArray(value2.runIds) && value2.runIds.length > 0 && value2.runIds.every((runId) => nonEmpty2(runId)) && new Set(value2.runIds).size === value2.runIds.length && (value2.until === "all" || value2.until === "any") && (value2.timeoutMs === void 0 || Number.isInteger(value2.timeoutMs) && value2.timeoutMs >= 0 && value2.timeoutMs <= AGENT_WAIT_MAX_MS) ? value2 : null;
2563
- },
2564
- report: parseRunIdOperation,
2565
- stop: parseRunIdOperation,
2566
- list: (value2) => {
2567
- return hasOnlyKeys(value2, ["operation", "status", "cursor", "limit"]) && (value2.status === void 0 || ["creating", "ready", "active", "parked", "closed"].includes(value2.status)) && optionalString(value2.cursor) && Number.isInteger(value2.limit) && value2.limit >= 1 && value2.limit <= 100 ? value2 : null;
2568
- },
2569
- message: (value2) => {
2570
- return hasExactKeys(value2, ["operation", "to", "text"]) && nonEmpty2(value2.to) && nonEmpty2(value2.text) ? value2 : null;
2571
- },
2572
- dismiss: parseAgentIdOperation,
2573
- resume: parseAgentIdOperation
2574
- };
2575
- return parseClosed(parsers, value.operation, value);
2576
- }
2577
- function parseAgentControlToolResponse(value) {
2578
- if (!isRecord(value)) return null;
2579
- if (value.ok === true) {
2580
- return hasExactKeys(value, ["ok", "value"]) ? value : null;
2581
- }
2582
- const codes = [
2583
- "invalid-context",
2584
- "forbidden",
2585
- "mode-disabled",
2586
- "not-found",
2587
- "restart-lost",
2588
- "other-owner",
2589
- "invalid-state",
2590
- "run-mismatch",
2591
- "runtime-unavailable"
2592
- ];
2593
- return value.ok === false && hasExactKeys(value, ["ok", "code", "error"]) && codes.includes(value.code) && typeof value.error === "string" ? value : null;
2594
- }
2595
- const MCP_CONNECTION_STATES = [
2596
- "connecting",
2597
- "ready",
2598
- "unauthorized",
2599
- "error",
2600
- "idle"
2601
- ];
2602
- const CONTEXT_OCCUPANCY_BUCKETS = [
2603
- "system",
2604
- "instructions",
2605
- "skills",
2606
- "tools",
2607
- "conversation",
2608
- "compaction",
2609
- // 为已持久化的上下文占用快照保留;项目记忆功能已移除。
2610
- "projectMemory",
2611
- "reminders"
2612
- ];
2613
- const STALE_SESSION_ERROR = "unknown or stale session generation";
2614
- function workspaceBranchChangedNote(branch) {
2615
- return `<workspace-branch-changed>
2616
- The current workspace is now on Git branch ${JSON.stringify(branch)}. The directory is unchanged, but file contents may differ. Re-read relevant files before relying on earlier observations or edits. This is background information only, not a task or goal.
2617
- </workspace-branch-changed>`;
2618
- }
2619
- const RETRY_SKIPPED_REASONS = ["busy", "nothing-to-retry"];
2620
- const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
2621
- const isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
2622
- const isDeliveryId = (value) => isNonEmptyString(value) && value.length <= 128;
2623
- const hasOnlyKeys = (value, allowed) => Object.keys(value).every((key) => allowed.includes(key));
2624
- const PLUGIN_INJECT_KEYS = [
2625
- "type",
2626
- "identity",
2627
- "pluginId",
2628
- "pluginName",
2629
- "text",
2630
- "deliverAs",
2631
- "triggerTurn"
2632
- ];
2633
- const hasExactKeys = (value, keys) => Object.keys(value).length === keys.length && hasOnlyKeys(value, keys);
2634
- function isPluginToolList(value) {
2635
- if (!Array.isArray(value) || value.length > 200) return false;
2636
- const names = /* @__PURE__ */ new Set();
2637
- for (const tool of value) {
2638
- if (!isRecord(tool) || !hasOnlyKeys(tool, [
2639
- "name",
2640
- "description",
2641
- "parameters",
2642
- "pluginId",
2643
- "timeoutMs",
2644
- "readOnly"
2645
- ]) || tool.name === void 0 || tool.description === void 0 || tool.parameters === void 0 || tool.pluginId === void 0 || typeof tool.name !== "string" || typeof tool.description !== "string" || tool.description.length > 1024 || !isRecord(tool.parameters) || tool.timeoutMs !== void 0 && !isPluginToolTimeout(tool.timeoutMs) || tool.readOnly !== void 0 && typeof tool.readOnly !== "boolean" || parsePluginToolName(tool.name)?.pluginId !== tool.pluginId || names.has(tool.name))
2646
- return false;
2647
- names.add(tool.name);
2648
- }
2649
- return true;
2650
- }
2651
- const isPluginToolTimeout = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1e3 && value <= 6e5;
2652
- const isBoundedText = (value, max) => typeof value === "string" && value.length <= max;
2653
- function isPluginEventPlan(value) {
2654
- if (!isRecord(value) || !hasExactKeys(value, ["observe", "intercept", "inject"])) return false;
2655
- if (typeof value.inject !== "boolean" || !Array.isArray(value.observe)) return false;
2656
- if (value.observe.length > PLUGIN_EVENTS.length) return false;
2657
- if (!value.observe.every(
2658
- (event) => typeof event === "string" && PLUGIN_EVENTS.includes(event)
2659
- ))
2660
- return false;
2661
- if (new Set(value.observe).size !== value.observe.length) return false;
2662
- if (!Array.isArray(value.intercept) || value.intercept.length > PLUGIN_INTERCEPT_EVENTS.length)
2663
- return false;
2664
- const events = /* @__PURE__ */ new Set();
2665
- for (const item of value.intercept) {
2666
- if (!isRecord(item) || !hasOnlyKeys(item, ["event", "tools"]) || typeof item.event !== "string")
2667
- return false;
2668
- if (!isInterceptEvent(item.event) || events.has(item.event)) return false;
2669
- events.add(item.event);
2670
- if (item.tools === void 0) continue;
2671
- if (!Array.isArray(item.tools) || item.tools.length > 64 || !item.tools.every(
2672
- (name) => typeof name === "string" && name.length > 0 && name.length <= 256
2673
- ) || new Set(item.tools).size !== item.tools.length)
2674
- return false;
2675
- }
2676
- return true;
2677
- }
2678
- const hasPluginAgentKeys = (value, keys) => {
2679
- if (value.agent === void 0) return hasExactKeys(value, keys);
2680
- const identity = value.identity;
2681
- return hasExactKeys(value, [...keys, "agent"]) && typeof identity?.sessionId === "string" && parsePluginAgentSource(value.agent, identity.sessionId) !== null;
2682
- };
2683
- const isPluginObserveData = (event, data) => {
2684
- if (!isRecord(data)) return false;
2685
- if (isInterceptEvent(event)) return isPluginInterceptPayload(event, data);
2686
- if (event === "agent_start") return hasExactKeys(data, []);
2687
- if (event === "agent_end")
2688
- return hasOnlyKeys(data, ["text"]) && (data.text === void 0 || typeof data.text === "string" && data.text.length <= AGENT_END_TEXT_MAX);
2689
- if (event === "context_usage") return isContextUsagePayload(data);
2690
- if (event === "model_select") return isModelSelectPayload(data);
2691
- return (event === "session_start" || event === "session_end" || event === "after_compact") && hasExactKeys(data, ["reason"]) && isNonEmptyString(data.reason) && data.reason.length <= 64;
2692
- };
2693
- const isTokenCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
2694
- const isModelRefPart = (value) => typeof value === "string" && value.length > 0 && value.length <= 256;
2695
- const isModelSelectPayload = (data) => {
2696
- if (!hasOnlyKeys(data, ["provider", "modelId", "previous", "source"])) return false;
2697
- if (!isModelRefPart(data.provider) || !isModelRefPart(data.modelId)) return false;
2698
- if (data.source !== "set" && data.source !== "cycle" && data.source !== "restore") return false;
2699
- if (data.previous === void 0) return true;
2700
- return isRecord(data.previous) && hasExactKeys(data.previous, ["provider", "modelId"]) && isModelRefPart(data.previous.provider) && isModelRefPart(data.previous.modelId);
2701
- };
2702
- const isTokenRecord = (value, keys) => isRecord(value) && hasExactKeys(value, keys) && keys.every((key) => isTokenCount(value[key]));
2703
- const isContextUsagePayload = (data) => hasOnlyKeys(data, [
2704
- "used",
2705
- "estimated",
2706
- "contextWindow",
2707
- "percent",
2708
- "buckets",
2709
- "usage",
2710
- "parts",
2711
- "turns"
2712
- ]) && isTokenCount(data.used) && typeof data.estimated === "boolean" && (data.contextWindow === void 0 || isTokenCount(data.contextWindow)) && (data.percent === void 0 || isTokenCount(data.percent)) && isTokenRecord(data.buckets, CONTEXT_USAGE_BUCKETS) && (data.usage === void 0 || isTokenRecord(data.usage, ["input", "output", "cacheRead", "cacheWrite"])) && (data.turns === void 0 || isSequence(data.turns)) && (data.parts === void 0 || Array.isArray(data.parts) && data.parts.length <= CONTEXT_PART_KINDS.length && data.parts.every(isContextPart));
2713
- const isContextPartItem = (value) => isRecord(value) && hasOnlyKeys(value, ["name", "tag", "n", "tokens"]) && typeof value.name === "string" && value.name.length <= 1024 && typeof value.tag === "string" && value.tag.length <= 32 && (value.n === void 0 || isSequence(value.n)) && isTokenCount(value.tokens);
2714
- const isContextPart = (value) => isRecord(value) && hasExactKeys(value, ["kind", "tokens", "items"]) && CONTEXT_PART_KINDS.includes(value.kind) && isTokenCount(value.tokens) && Array.isArray(value.items) && value.items.length <= CONTEXT_PART_ITEMS && value.items.every(isContextPartItem);
2715
- const isPluginInterceptPayload = (event, payload) => {
2716
- if (!isRecord(payload)) return false;
2717
- if (event === "before_agent_start") {
2718
- return hasExactKeys(payload, ["prompt", "kind"]) && isBoundedText(payload.prompt, BEFORE_AGENT_START_PROMPT_MAX) && (payload.kind === "user" || payload.kind === "custom");
2719
- }
2720
- if (event === "before_compact") {
2721
- return hasExactKeys(payload, ["reason"]) && isNonEmptyString(payload.reason) && payload.reason.length <= 64;
2722
- }
2723
- if (event === "tool_call") {
2724
- return hasExactKeys(payload, ["toolCallId", "toolName", "input"]) && isNonEmptyString(payload.toolCallId) && payload.toolCallId.length <= 512 && isNonEmptyString(payload.toolName) && payload.toolName.length <= 256 && isRecord(payload.input);
2725
- }
2726
- if (event === "tool_result") {
2727
- return hasExactKeys(payload, ["toolCallId", "toolName", "input", "content", "isError"]) && isNonEmptyString(payload.toolCallId) && payload.toolCallId.length <= 512 && isNonEmptyString(payload.toolName) && payload.toolName.length <= 256 && isRecord(payload.input) && typeof payload.content === "string" && typeof payload.isError === "boolean";
2728
- }
2729
- return event === "input" && hasExactKeys(payload, ["text", "source"]) && typeof payload.text === "string" && isNonEmptyString(payload.source) && payload.source.length <= 32;
2730
- };
2731
- const isMcpScopeChallenge = (value) => isRecord(value) && hasOnlyKeys(value, ["scope", "resourceMetadataUrl"]) && (value.scope === void 0 || typeof value.scope === "string" && value.scope.length <= 2048) && (value.resourceMetadataUrl === void 0 || typeof value.resourceMetadataUrl === "string" && URL.canParse(value.resourceMetadataUrl));
2732
- const isSequence = (value) => Number.isInteger(value) && value >= 0;
2733
- function parseProjectedFileChanges(value) {
2734
- if (!Array.isArray(value) || value.length > PROJECTED_FILE_CHANGE_LIMIT) return null;
2735
- for (const item of value) {
2736
- if (!isRecord(item) || !hasOnlyKeys(item, ["path", "oldText", "newText", "type", "truncated"]) || !isNonEmptyString(item.path) || item.path.length > PROJECTED_APPLY_PATCH_PATH_TEXT_LIMIT || typeof item.oldText !== "string" || typeof item.newText !== "string" || item.type !== "add" && item.type !== "update" && item.type !== "delete" || item.truncated !== void 0 && item.truncated !== true || item.oldText.length > PROJECTED_FILE_TEXT_LIMIT + (item.truncated === true ? 2 : 0) || item.newText.length > PROJECTED_FILE_TEXT_LIMIT + (item.truncated === true ? 2 : 0) || item.truncated === true && !item.oldText.endsWith("\n…") && !item.newText.endsWith("\n…")) {
2737
- return null;
2738
- }
2739
- }
2740
- return value;
2741
- }
2742
- function parseProjectedApplyPatchOutcome(value) {
2743
- if (!isRecord(value) || !hasOnlyKeys(value, [
2744
- "status",
2745
- "applied",
2746
- "failed",
2747
- "unattempted",
2748
- "uncertain",
2749
- "error",
2750
- "errorTruncated",
2751
- "input",
2752
- "inputTruncated"
2753
- ]) || value.status !== "success" && value.status !== "partial" && value.status !== "failed") {
2754
- return null;
2755
- }
2756
- const lists = [value.applied, value.failed, value.unattempted, value.uncertain];
2757
- if (lists.some(
2758
- (list) => !Array.isArray(list) || list.some(
2759
- (path) => !isNonEmptyString(path) || path.length > PROJECTED_APPLY_PATCH_PATH_TEXT_LIMIT
2760
- )
2761
- )) {
2762
- return null;
2763
- }
2764
- const [applied, failed, unattempted, uncertain] = lists;
2765
- const allPaths = [...applied, ...failed, ...unattempted, ...uncertain];
2766
- const error = typeof value.error === "string" && value.error.length > 0 ? value.error : null;
2767
- const input = typeof value.input === "string" && value.input.length > 0 ? value.input : null;
2768
- if (allPaths.length > PROJECTED_APPLY_PATCH_PATH_COUNT_LIMIT || new Set(allPaths).size !== allPaths.length || value.error !== void 0 && error === null || value.errorTruncated !== void 0 && value.errorTruncated !== true || value.errorTruncated === true && (error === null || error.length > PROJECTED_FILE_TEXT_LIMIT + 2 || !error.endsWith("\n…")) || value.errorTruncated !== true && error !== null && error.length > PROJECTED_FILE_TEXT_LIMIT || value.input !== void 0 && input === null || value.inputTruncated !== void 0 && value.inputTruncated !== true || value.inputTruncated === true && (input === null || input.length > PROJECTED_FILE_TEXT_LIMIT + 2 || !input.endsWith("\n…")) || value.inputTruncated !== true && input !== null && input.length > PROJECTED_FILE_TEXT_LIMIT || value.status === "success" && (error !== null || input !== null || failed.length > 0 || unattempted.length > 0 || uncertain.length > 0) || value.status === "partial" && (applied.length === 0 || error === null) || value.status === "failed" && (applied.length > 0 || error === null)) {
2769
- return null;
2770
- }
2771
- return value;
2772
- }
2773
- function isBackgroundTaskId(value) {
2774
- return typeof value === "string" && value.length > 0 && value.length <= 128;
2775
- }
2776
- function isProjectedCodemodeCalls(value) {
2777
- return Array.isArray(value) && value.every(
2778
- (call) => isRecord(call) && isNonEmptyString(call.name) && typeof call.ok === "boolean" && (call.error === void 0 || typeof call.error === "string") && (call.summary === void 0 || typeof call.summary === "string")
2779
- );
2780
- }
2781
- function hasValidProjectedMetadata(value) {
2782
- if (value.generatedImages !== void 0 && !parseGeneratedImagePaths(value.generatedImages))
2783
- return false;
2784
- if (value.rtk !== void 0 && !parseRtkToolStats(value.rtk)) return false;
2785
- if (value.approvalReview !== void 0 && !parseApprovalReviewRecord(value.approvalReview))
2786
- return false;
2787
- if (value.privacyMask !== void 0 && !parseMaskReport(value.privacyMask)) return false;
2788
- if (value.codemodeCalls !== void 0 && !isProjectedCodemodeCalls(value.codemodeCalls)) {
2789
- return false;
2790
- }
2791
- if (value.backgroundTaskId !== void 0 && !isBackgroundTaskId(value.backgroundTaskId)) {
2792
- return false;
2793
- }
2794
- if (value.shellFailure !== void 0 && !parseShellFailure(value.shellFailure)) return false;
2795
- if (value.pluginSource !== void 0 && !parsePluginMessageSource(value.pluginSource))
2796
- return false;
2797
- if (value.pluginArtifacts !== void 0 && (!Array.isArray(value.pluginArtifacts) || !value.pluginArtifacts.every((item) => parsePluginArtifactInfo(item) !== null))) {
2798
- return false;
2799
- }
2800
- const fileChanges = value.fileChanges === void 0 ? void 0 : parseProjectedFileChanges(value.fileChanges);
2801
- if (fileChanges === null) return false;
2802
- if (value.applyPatchOutcome === void 0) return true;
2803
- const outcome = parseProjectedApplyPatchOutcome(value.applyPatchOutcome);
2804
- return outcome !== null && fileChanges !== void 0 && outcome.applied.length === fileChanges.length && outcome.applied.every((path, index) => path === fileChanges[index]?.path);
2805
- }
2806
- const isMcpOAuthAccess = (value) => isRecord(value) && hasOnlyKeys(value, ["access_token", "expires_at"]) && isNonEmptyString(value.access_token) && (value.expires_at === void 0 || typeof value.expires_at === "number" && Number.isFinite(value.expires_at));
2807
- const isMcpOAuthRefreshResult = (value) => isRecord(value) && (value.ok === true ? hasOnlyKeys(value, ["ok", "access"]) && isMcpOAuthAccess(value.access) : value.ok === false && hasOnlyKeys(value, ["ok", "unauthorized", "error"]) && typeof value.unauthorized === "boolean" && typeof value.error === "string");
2808
- function parseTurnDigest(value) {
2809
- if (!isRecord(value) || !hasOnlyKeys(value, ["firstUserText", "userText", "assistantText", "lastTool"])) {
2810
- return null;
2811
- }
2812
- if (typeof value.firstUserText !== "string" || typeof value.userText !== "string" || typeof value.assistantText !== "string") {
2813
- return null;
2814
- }
2815
- const digest = {
2816
- firstUserText: value.firstUserText,
2817
- userText: value.userText,
2818
- assistantText: value.assistantText
2819
- };
2820
- if (value.lastTool !== void 0) {
2821
- if (!isRecord(value.lastTool) || !hasExactKeys(value.lastTool, ["name", "ok"]) || typeof value.lastTool.name !== "string" || value.lastTool.name.trim().length === 0 || typeof value.lastTool.ok !== "boolean") {
2822
- return null;
2823
- }
2824
- digest.lastTool = { name: value.lastTool.name, ok: value.lastTool.ok };
2825
- }
2826
- return digest;
2827
- }
2828
- function parseTurnReport(value) {
2829
- if (!isRecord(value) || !hasOnlyKeys(value, ["text", "omitted"])) return null;
2830
- if (!isNonEmptyString(value.text) || value.text.length > TURN_REPORT_MAX_CHARS) return null;
2831
- if (value.omitted !== void 0 && !(typeof value.omitted === "number" && Number.isSafeInteger(value.omitted) && value.omitted > 0))
2832
- return null;
2833
- return value;
2834
- }
2835
- function parseTitleSummaryInput(value) {
2836
- if (!isRecord(value)) return null;
2837
- if (value.kind === "initial") {
2838
- return hasExactKeys(value, ["kind", "text"]) && typeof value.text === "string" && value.text.trim().length > 0 ? value : null;
2839
- }
2840
- if (value.kind === "rolling") {
2841
- return hasExactKeys(value, [
2842
- "kind",
2843
- "currentTitle",
2844
- "firstUserText",
2845
- "userText",
2846
- "assistantText"
2847
- ]) && isNonEmptyString(value.currentTitle) && typeof value.firstUserText === "string" && typeof value.userText === "string" && typeof value.assistantText === "string" && (value.userText.trim().length > 0 || value.assistantText.trim().length > 0) ? value : null;
2848
- }
2849
- return null;
2850
- }
2851
- function parseContextOccupancy(value) {
2852
- if (!isRecord(value) || !isRecord(value.buckets) || typeof value.estimated !== "boolean")
2853
- return null;
2854
- for (const id of CONTEXT_OCCUPANCY_BUCKETS) {
2855
- const tokens = value.buckets[id];
2856
- if (!isSequence(tokens)) return null;
2857
- }
2858
- const parts = value.parts === void 0 ? void 0 : parseContextParts(value.parts);
2859
- if (value.parts !== void 0 && !parts) return null;
2860
- if (!isSequence(value.used) || !isSequence(value.compactedMessageCount) || typeof value.compactionModelMismatch !== "boolean" || value.contextWindow !== void 0 && !(typeof value.contextWindow === "number" && value.contextWindow > 0) || value.percent !== void 0 && !isSequence(value.percent) || value.compactionEntryId !== void 0 && !isNonEmptyString(value.compactionEntryId) || value.compactionTokensAfter !== void 0 && !isSequence(value.compactionTokensAfter)) {
2861
- return null;
2862
- }
2863
- return { ...value, ...parts ? { parts } : {} };
2864
- }
2865
- function parseContextParts(value) {
2866
- if (!Array.isArray(value) || value.length > CONTEXT_PART_KINDS.length) return null;
2867
- const seen = /* @__PURE__ */ new Set();
2868
- for (const part of value) {
2869
- if (!isRecord(part) || !CONTEXT_PART_KINDS.includes(part.kind) || seen.has(part.kind) || !isSequence(part.tokens) || !Array.isArray(part.items) || part.items.length > CONTEXT_PART_ITEMS) {
2870
- return null;
2871
- }
2872
- seen.add(part.kind);
2873
- for (const item of part.items) {
2874
- if (!isRecord(item) || !isNonEmptyString(item.name) || typeof item.tag !== "string" || item.tag.length > 32 || !isSequence(item.tokens) || item.n !== void 0 && (!isSequence(item.n) || item.n < 1)) {
2875
- return null;
2876
- }
2877
- }
2878
- }
2879
- return value;
2880
- }
2881
- const isNonNegativeNumber = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
2882
- function parseSessionUsageTotals(value) {
2883
- if (!isRecord(value) || !isSequence(value.inputTokens) || !isSequence(value.outputTokens)) {
2884
- return void 0;
2885
- }
2886
- const out = {
2887
- inputTokens: value.inputTokens,
2888
- outputTokens: value.outputTokens
2889
- };
2890
- for (const key of ["cacheHitPercent", "ttftAvgMs", "tokensPerSecond"]) {
2891
- const field = value[key];
2892
- if (field === void 0) continue;
2893
- if (!isNonNegativeNumber(field)) return void 0;
2894
- out[key] = field;
2895
- }
2896
- return out;
2897
- }
2898
- const isProductSurfaceId = (value) => typeof value === "string" && Object.hasOwn(PRODUCT_SURFACE_INVENTORY, value);
2899
- function parseAttachedImages(value) {
2900
- if (!Array.isArray(value)) return null;
2901
- for (const item of value) {
2902
- if (!isRecord(item) || !hasOnlyKeys(item, ["data", "mimeType", "id"])) return null;
2903
- if (!isNonEmptyString(item.data) || !isNonEmptyString(item.mimeType)) return null;
2904
- if (item.id !== void 0 && !isNonEmptyString(item.id)) return null;
2905
- }
2906
- return value;
2907
- }
2908
- const parseAnySessionIdentity = (value) => parseChildSessionIdentity(value) ?? parseSessionIdentity(value);
2909
- function parseVirtualSpawnClassifier(value) {
2910
- if (!isRecord(value) || !hasOnlyKeys(value, ["source", "timeoutMs", "model", "classifier"])) {
2911
- return false;
2912
- }
2913
- if (typeof value.timeoutMs !== "number" || !(value.timeoutMs > 0)) return false;
2914
- if (value.source === "judge") {
2915
- return value.classifier === void 0 && parsePhysicalSpawnModelConfig(value.model) !== null;
2916
- }
2917
- if (value.source !== "pi-classifier" || value.model !== void 0) return false;
2918
- return parseClassifierCredentials(value.classifier);
2919
- }
2920
- function parseClassifierCredentials(value) {
2921
- return isRecord(value) && hasOnlyKeys(value, ["provider", "modelId", "apiKey", "baseUrl"]) && isNonEmptyString(value.provider) && isNonEmptyString(value.modelId) && (value.apiKey === void 0 || typeof value.apiKey === "string") && (value.baseUrl === void 0 || isNonEmptyString(value.baseUrl));
2922
- }
2923
- function parseVirtualSpawnConfig(value) {
2924
- if (!isRecord(value) || !hasOnlyKeys(value, ["name", "primary", "fast", "fallbacks", "classifier"]))
2925
- return false;
2926
- return isNonEmptyString(value.name) && parsePhysicalSpawnModelConfig(value.primary) !== null && (value.fast === void 0 || parsePhysicalSpawnModelConfig(value.fast) !== null) && Array.isArray(value.fallbacks) && value.fallbacks.every((item) => parsePhysicalSpawnModelConfig(item) !== null) && (value.classifier === void 0 || parseVirtualSpawnClassifier(value.classifier));
2927
- }
2928
- function parseSessionModelConfig(value) {
2929
- if (!isRecord(value)) return null;
2930
- if (value.virtual === void 0) return parsePhysicalSpawnModelConfig(value);
2931
- const { virtual, ...physical } = value;
2932
- return parseVirtualSpawnConfig(virtual) && parsePhysicalSpawnModelConfig(physical) ? value : null;
2933
- }
2934
- const parseSpawnModelConfig = (value) => parsePhysicalSpawnModelConfig(value);
2935
- function parsePhysicalSpawnModelConfig(value) {
2936
- if (!isRecord(value)) return null;
2937
- if (!hasOnlyKeys(value, [
2938
- "api",
2939
- "baseUrl",
2940
- "apiKey",
2941
- "modelId",
2942
- "settingsProviderId",
2943
- "oauthAccountKey",
2944
- "oauthAccountPool",
2945
- "reasoning",
2946
- "thinkingLevel",
2947
- "contextWindow",
2948
- "maxTokens",
2949
- "headers"
2950
- ]) || !MODEL_API_KINDS.includes(value.api) || typeof value.baseUrl !== "string" || typeof value.apiKey !== "string" || !isNonEmptyString(value.modelId) || !isNonEmptyString(value.settingsProviderId) || value.oauthAccountKey !== void 0 && !isNonEmptyString(value.oauthAccountKey) || value.oauthAccountPool !== void 0 && (!parseOauthAccountPool(value.oauthAccountPool) || !isCodexAccountKey(value.oauthAccountKey) || value.apiKey !== "")) {
2951
- return null;
2952
- }
2953
- if (value.headers !== void 0) {
2954
- const headers = parseProviderHeaders(value.headers);
2955
- if (headers) value.headers = headers;
2956
- else delete value.headers;
2957
- }
2958
- return value;
2959
- }
2960
- function parseSubagentModelOption(value) {
2961
- if (!isRecord(value) || !hasOnlyKeys(value, ["name", "config", "description"]) || !isNonEmptyString(value.name) || !parseSessionModelConfig(value.config) || value.description !== void 0 && typeof value.description !== "string") {
2962
- return null;
2963
- }
2964
- return value;
2965
- }
2966
- function parseModelRef(value) {
2967
- if (!isRecord(value) || !hasExactKeys(value, ["providerId", "modelId"])) return null;
2968
- return isNonEmptyString(value.providerId) && isNonEmptyString(value.modelId) ? { providerId: value.providerId, modelId: value.modelId } : null;
2969
- }
2970
- function isValidCreateProjectRemoteFields(value) {
2971
- if (value.kind === "ssh") return isUuid(value.sshConnectionId) && value.sshHost === void 0;
2972
- if (value.kind === "local" || value.kind === void 0) {
2973
- return value.sshHost === void 0 && value.sshConnectionId === void 0;
2974
- }
2975
- return false;
2976
- }
2977
- function parseAgentRemoteConfig(value) {
2978
- if (!isRecord(value) || !hasOnlyKeys(value, ["host", "auth", "port", "password", "timeoutSeconds"]) || !isNonEmptyString(value.host) || value.auth !== "key" && value.auth !== "password") {
2979
- return null;
2980
- }
2981
- if (value.timeoutSeconds !== void 0 && parseSshTimeoutSeconds(value.timeoutSeconds) === null) {
2982
- return null;
2983
- }
2984
- if (value.port !== void 0 && (!Number.isInteger(value.port) || value.port < 1 || value.port > 65535)) {
2985
- return null;
2986
- }
2987
- if (value.auth === "password") {
2988
- if (!isNonEmptyString(value.password)) return null;
2989
- } else if (value.password !== void 0) {
2990
- return null;
2991
- }
2992
- return value;
2993
- }
2994
- function parseCreateProjectAuthorityRequest(value) {
2995
- if (!isRecord(value) || !hasOnlyKeys(value, ["requestId", "path", "kind", "sshConnectionId"])) {
2996
- return null;
2997
- }
2998
- return isNonEmptyString(value.requestId) && isNonEmptyString(value.path) && isValidCreateProjectRemoteFields(value) ? value : null;
2999
- }
3000
- function parseSelectProjectAuthorityRequest(value) {
3001
- if (!isRecord(value) || !hasExactKeys(value, ["requestId", "projectId", "version"]) || !isNonEmptyString(value.requestId) || !isUuid(value.projectId) || !isSequence(value.version)) {
3002
- return null;
3003
- }
3004
- return value;
3005
- }
3006
- function parseRemoveProjectAuthorityRequest(value) {
3007
- if (!isRecord(value) || !hasExactKeys(value, ["requestId", "projectId", "version"]) || !isNonEmptyString(value.requestId) || !isUuid(value.projectId) || !isSequence(value.version)) {
3008
- return null;
3009
- }
3010
- return value;
3011
- }
3012
- function parseCreateConversationAuthorityRequest(value) {
3013
- if (!isRecord(value) || !hasOnlyKeys(value, [
3014
- "requestId",
3015
- "projectId",
3016
- "projectVersion",
3017
- "conversationId",
3018
- "forkedFrom"
3019
- ]) || !isNonEmptyString(value.requestId) || !isUuid(value.projectId) || !isSequence(value.projectVersion) || value.conversationId !== void 0 && !isUuid(value.conversationId)) {
3020
- return null;
3021
- }
3022
- if (value.forkedFrom !== void 0) {
3023
- if (!isRecord(value.forkedFrom) || !hasExactKeys(value.forkedFrom, ["conversationId", "entryId"]) || !isUuid(value.forkedFrom.conversationId) || !isNonEmptyString(value.forkedFrom.entryId)) {
3024
- return null;
3025
- }
3026
- }
3027
- return value;
3028
- }
3029
- function parseConversationAuthorityRequest(value) {
3030
- if (!isRecord(value) || !hasOnlyKeys(value, [
3031
- "requestId",
3032
- "conversationId",
3033
- "version",
3034
- "selectionEpoch",
3035
- "selectionBootId"
3036
- ]) || !isNonEmptyString(value.requestId) || !isUuid(value.conversationId) || !isSequence(value.version) || value.selectionEpoch !== void 0 && !isSequence(value.selectionEpoch) || value.selectionBootId !== void 0 && (!isNonEmptyString(value.selectionBootId) || value.selectionBootId.length > 128)) {
3037
- return null;
3038
- }
3039
- return value;
3040
- }
3041
- function parseUpdateConversationSelectionRequest(value) {
3042
- if (!isRecord(value) || !hasExactKeys(value, ["requestId", "conversationId", "version", "selection"]) || !parseConversationAuthorityRequest({
3043
- requestId: value.requestId,
3044
- conversationId: value.conversationId,
3045
- version: value.version
3046
- }) || !parseModelRef(value.selection)) {
3047
- return null;
3048
- }
3049
- return value;
3050
- }
3051
- function parseChildConversationMetadata(value) {
3052
- if (!isRecord(value)) return null;
3053
- if (!hasOnlyKeys(value, [
3054
- "parentId",
3055
- "childGeneration",
3056
- "agentTypeKey",
3057
- "agentInstanceId",
3058
- "agentInstanceName",
3059
- "dispatchOrigin",
3060
- "mode",
3061
- "lockedProfileId"
3062
- ]) || Object.keys(value).length < 6) {
3063
- return null;
3064
- }
3065
- const typeKey = parseAgentTypeKey(value.agentTypeKey);
3066
- if (!isNonEmptyString(value.parentId) || !isUuid(value.childGeneration) || !typeKey || !isUuid(value.agentInstanceId) || !isNonEmptyString(value.agentInstanceName) || value.dispatchOrigin !== "typed-mention" && value.dispatchOrigin !== "manual" && value.dispatchOrigin !== "agent-tool" || value.mode !== void 0 && value.mode !== "task" && value.mode !== "coworker" || !isValidLegacyProfile(typeKey, value.lockedProfileId)) {
3067
- return null;
3068
- }
3069
- return value;
3070
- }
3071
- function parseSafeChildRef(value) {
3072
- if (!isRecord(value) || !hasExactKeys(value, ["sessionId", "generation", "instanceId", "instanceName", "typeKey"])) {
3073
- return null;
3074
- }
3075
- const typeKey = parseAgentTypeKey(value.typeKey);
3076
- return isNonEmptyString(value.sessionId) && isUuid(value.generation) && isUuid(value.instanceId) && isNonEmptyString(value.instanceName) && typeKey ? value : null;
3077
- }
3078
- const agentSessionCustomEntryParsers = {
3079
- "oauth-account-selected": (value) => {
3080
- return hasOnlyKeys(value, [
3081
- "kind",
3082
- "accountKey",
3083
- "previousAccountKey",
3084
- "settingsProviderId",
3085
- "modelId",
3086
- "at"
3087
- ]) && isCodexAccountKey(value.accountKey) && (value.previousAccountKey === void 0 || isCodexAccountKey(value.previousAccountKey)) && (value.settingsProviderId === void 0 && value.modelId === void 0 || isNonEmptyString(value.settingsProviderId) && isNonEmptyString(value.modelId)) && typeof value.at === "number" && Number.isFinite(value.at) ? value : null;
3088
- },
3089
- "capability-receipt": (value) => {
3090
- if (!hasExactKeys(value, ["kind", "receipt"])) return null;
3091
- const receipt = parseCapabilityReceipt(value.receipt);
3092
- return receipt ? { kind: "capability-receipt", receipt } : null;
3093
- },
3094
- "task-wrap-up-nudge": (value) => {
3095
- return hasExactKeys(value, ["kind", "count", "at"]) && Number.isInteger(value.count) && value.count > 0 && typeof value.at === "number" && Number.isFinite(value.at) ? value : null;
3096
- },
3097
- "tool-batch-label": (value) => {
3098
- return hasExactKeys(value, ["kind", "callId", "label", "at"]) && isNonEmptyString(value.callId) && isNonEmptyString(value.label) && value.label.length <= 200 && typeof value.at === "number" && Number.isFinite(value.at) ? value : null;
3099
- },
3100
- "agent-dispatch": (value) => {
3101
- const child = parseSafeChildRef(value.child);
3102
- if (!child || typeof value.at !== "number" || !Number.isFinite(value.at)) return null;
3103
- return hasExactKeys(value, ["kind", "child", "at"]) ? value : null;
3104
- },
3105
- "agent-completed": (value) => {
3106
- const child = parseSafeChildRef(value.child);
3107
- if (!child || typeof value.at !== "number" || !Number.isFinite(value.at)) return null;
3108
- return hasOnlyKeys(value, ["kind", "child", "receiptSummary", "at"]) && (value.receiptSummary === void 0 || typeof value.receiptSummary === "string") ? value : null;
3109
- },
3110
- "agent-failed": (value) => {
3111
- const child = parseSafeChildRef(value.child);
3112
- if (!child || typeof value.at !== "number" || !Number.isFinite(value.at)) return null;
3113
- return hasExactKeys(value, ["kind", "child", "errorCode", "message", "at"]) && isNonEmptyString(value.errorCode) && isNonEmptyString(value.message) ? value : null;
3114
- }
3115
- };
3116
- function parseAgentSessionCustomEntry(value) {
3117
- if (!isRecord(value) || typeof value.kind !== "string") return null;
3118
- return parseClosed(agentSessionCustomEntryParsers, value.kind, value);
3119
- }
3120
- function parseResolvedChildProfileProof(value) {
3121
- if (!isRecord(value) || !hasExactKeys(value, [
3122
- "spawnSpecId",
3123
- "typeKey",
3124
- "model",
3125
- "toolIds",
3126
- "loadedSkillBindingIds",
3127
- "loadedMcpBindingIds",
3128
- "systemPromptHash"
3129
- ]) || !isUuid(value.spawnSpecId) || !parseAgentTypeKey(value.typeKey) || !parseModelRef(value.model) || !Array.isArray(value.toolIds) || !value.toolIds.every(isNonEmptyString) || !Array.isArray(value.loadedSkillBindingIds) || !value.loadedSkillBindingIds.every(isNonEmptyString) || !Array.isArray(value.loadedMcpBindingIds) || !value.loadedMcpBindingIds.every(isNonEmptyString) || !isNonEmptyString(value.systemPromptHash)) {
3130
- return null;
3131
- }
3132
- return value;
3133
- }
3134
- const parseSafeTextRecord = (value) => {
3135
- return hasExactKeys(value, ["type", "text", "at"]) && typeof value.text === "string" ? value : null;
3136
- };
3137
- const safeJournalRecordParsers = {
3138
- "safe-user-text": parseSafeTextRecord,
3139
- "safe-assistant-text": parseSafeTextRecord,
3140
- "enso-operation": (value) => {
3141
- return hasExactKeys(value, ["type", "operationId", "capabilityId", "toolCallId", "at"]) && isNonEmptyString(value.operationId) && isProductSurfaceId(value.capabilityId) && isNonEmptyString(value.toolCallId) ? value : null;
3142
- },
3143
- "safe-model-result": (value) => {
3144
- return hasExactKeys(value, ["type", "toolCallId", "modelResult", "at"]) && isNonEmptyString(value.toolCallId) && parseCapabilityResult(value.modelResult) ? value : null;
3145
- },
3146
- "capability-receipt": (value) => {
3147
- return hasExactKeys(value, ["type", "receipt", "at"]) && parseCapabilityReceipt(value.receipt) ? value : null;
3148
- }
3149
- };
3150
- function parseSafeJournalRecord(value) {
3151
- if (!isRecord(value) || typeof value.at !== "number" || !Number.isFinite(value.at)) return null;
3152
- if (typeof value.type !== "string") return null;
3153
- return parseClosed(safeJournalRecordParsers, value.type, value);
3154
- }
3155
- function parseSafeJournalProjection(value) {
3156
- if (!isRecord(value) || !hasExactKeys(value, ["records", "partial"]) || !Array.isArray(value.records) || value.records.some((record2) => parseSafeJournalRecord(record2) === null) || typeof value.partial !== "boolean") {
3157
- return null;
3158
- }
3159
- return value;
3160
- }
3161
- function parseResolvedAgentTypeSpawnConfig(value) {
3162
- if (!isRecord(value)) return null;
3163
- if (!hasOnlyKeys(value, [
3164
- "typeKey",
3165
- "displayName",
3166
- "description",
3167
- "spawnSpecId",
3168
- "systemPrompt",
3169
- "model",
3170
- "tools",
3171
- "reasoning",
3172
- "thinkingLevel",
3173
- "allowedToolIds",
3174
- "skillPaths",
3175
- "skillBindingIds",
3176
- "mcpServers",
3177
- "mcpBindingIds",
3178
- "systemPromptHash"
3179
- ]) || Object.keys(value).length < 12) {
3180
- return null;
3181
- }
3182
- const typeKey = parseAgentTypeKey(value.typeKey);
3183
- const model = parseSessionModelConfig(value.model);
3184
- const skillPaths = Array.isArray(value.skillPaths) ? value.skillPaths : null;
3185
- const mcpServers = Array.isArray(value.mcpServers) ? value.mcpServers : null;
3186
- const skillBindingIds = Array.isArray(value.skillBindingIds) ? value.skillBindingIds : null;
3187
- const mcpBindingIds = Array.isArray(value.mcpBindingIds) ? value.mcpBindingIds : null;
3188
- if (!typeKey || typeKey === LEGACY_ENSO_TYPE_KEY || !model || !isUuid(value.spawnSpecId) || !isNonEmptyString(value.displayName) || typeof value.description !== "string" || typeof value.systemPrompt !== "string" || value.tools !== "all" && value.tools !== "readonly" || value.allowedToolIds !== void 0 && (!Array.isArray(value.allowedToolIds) || !value.allowedToolIds.every(isNonEmptyString)) || !skillPaths || !skillPaths.every(isNonEmptyString) || !skillBindingIds || !skillBindingIds.every(isNonEmptyString) || !mcpServers || !mcpServers.every(isRecord) || !mcpBindingIds || !mcpBindingIds.every(isNonEmptyString) || skillBindingIds.length !== skillPaths.length || mcpBindingIds.length !== mcpServers.length || !isNonEmptyString(value.systemPromptHash)) {
3189
- return null;
3190
- }
3191
- if (value.reasoning !== void 0 && !MODEL_REASONING_OVERRIDES.includes(value.reasoning) || value.thinkingLevel !== void 0 && !MODEL_THINKING_LEVEL_OVERRIDES.includes(value.thinkingLevel)) {
3192
- return null;
3193
- }
3194
- return value;
3195
- }
3196
- function parseSessionSnapshot(value) {
3197
- if (!isRecord(value)) return null;
3198
- if (!hasOnlyKeys(value, [
3199
- "identity",
3200
- "status",
3201
- "messages",
3202
- "baseIndex",
3203
- "commands",
3204
- "pendingApprovals",
3205
- "pendingAsks",
3206
- "backgroundTasks",
3207
- "subagents",
3208
- "safeJournal",
3209
- "child",
3210
- "customEntries",
3211
- "compaction",
3212
- "compactionNoticeAt",
3213
- "planState",
3214
- "requestBody"
3215
- ]) || !parseAnySessionIdentity(value.identity) || value.status !== "idle" && value.status !== "running" && value.status !== "failed" || !Array.isArray(value.messages) || value.messages.some((message) => !isRecord(message) || !hasValidProjectedMetadata(message)) || !Array.isArray(value.commands) || value.commands.some(
3216
- (command) => !isRecord(command) || !isNonEmptyString(command.name) || typeof command.description !== "string"
3217
- ) || value.child !== void 0 && parseChildConversationMetadata(value.child) === null || value.planState !== void 0 && parsePlanState(value.planState) === null || value.requestBody !== void 0 && parseRequestBodyUsage(value.requestBody) === null || value.safeJournal !== void 0 && parseSafeJournalProjection(value.safeJournal) === null || value.customEntries !== void 0 && (!Array.isArray(value.customEntries) || value.customEntries.some((entry) => parseAgentSessionCustomEntry(entry) === null)) || value.baseIndex !== void 0 && (typeof value.baseIndex !== "number" || !Number.isInteger(value.baseIndex) || value.baseIndex < 0)) {
3218
- return null;
3219
- }
3220
- return value;
3221
- }
3222
- const parseWorkspaceLockCommand = (value) => {
3223
- return hasOnlyKeys(
3224
- value,
3225
- value.type === "lock-workspace" ? ["type", "requestId", "conversationIds"] : ["type", "requestId", "conversationIds", "branch"]
3226
- ) && isNonEmptyString(value.requestId) && Array.isArray(value.conversationIds) && value.conversationIds.length > 0 && value.conversationIds.every(isNonEmptyString) && new Set(value.conversationIds).size === value.conversationIds.length && (value.branch === void 0 || isNonEmptyString(value.branch)) ? value : null;
3227
- };
3228
- const parsePromptOrSteer = (value) => {
3229
- const images = value.images === void 0 ? [] : parseAttachedImages(value.images);
3230
- return hasOnlyKeys(value, [
3231
- "type",
3232
- "identity",
3233
- "text",
3234
- "images",
3235
- "deliveryId",
3236
- "activeOnly",
3237
- "resume",
3238
- "instanceId"
3239
- ]) && parseAnySessionIdentity(value.identity) && typeof value.text === "string" && images !== null && (value.text.length > 0 || images.length > 0) && (value.activeOnly === void 0 || value.type === "steer" && value.activeOnly === true && isDeliveryId(value.deliveryId)) && (value.resume === void 0 || value.type === "prompt" && value.resume === true) && (value.type === "steer" && value.deliveryId === void 0 || isDeliveryId(value.deliveryId)) && (value.instanceId === void 0 || isUuid(value.instanceId) && parseSessionIdentity(value.identity) !== null) ? value : null;
3240
- };
3241
- const parseHostResultCommand = (value) => {
3242
- if (!hasOnlyKeys(value, ["type", "identity", "requestId", "ok", "result", "error"]) || !parseAnySessionIdentity(value.identity) || !isNonEmptyString(value.requestId) || typeof value.ok !== "boolean") {
3243
- return null;
3244
- }
3245
- const shapeOk = value.ok ? value.error === void 0 : isNonEmptyString(value.error) && value.result === void 0;
3246
- return shapeOk ? value : null;
3247
- };
3248
- const parseIdentityOnlyCommand = (value) => {
3249
- return hasExactKeys(value, ["type", "identity"]) && parseAnySessionIdentity(value.identity) ? value : null;
3250
- };
3251
- const agentCommandParsers = {
3252
- "oauth-pool-result": (value) => {
3253
- return hasOnlyKeys(value, ["type", "requestId", "accountKey", "selectionReceipt", "error"]) && isNonEmptyString(value.requestId) && (isCodexAccountKey(value.accountKey) && value.error === void 0 && (value.selectionReceipt === void 0 || isUuid(value.selectionReceipt)) || value.accountKey === void 0 && value.selectionReceipt === void 0 && isNonEmptyString(value.error)) ? value : null;
3254
- },
3255
- "mcp-oauth-refresh-result": (value) => {
3256
- return hasOnlyKeys(value, ["type", "requestId", "result"]) && isNonEmptyString(value.requestId) && isMcpOAuthRefreshResult(value.result) ? value : null;
3257
- },
3258
- "lock-workspace": parseWorkspaceLockCommand,
3259
- "unlock-workspace": parseWorkspaceLockCommand,
3260
- "spawn-parent": (value) => {
3261
- if (!hasOnlyKeys(value, [
3262
- "type",
3263
- "identity",
3264
- "cwd",
3265
- "model",
3266
- "resumeFile",
3267
- "reasoningEnabled",
3268
- "thinkingLevel",
3269
- "loadLocalSkills",
3270
- "loadHarnessAssets",
3271
- "trustedProjectCode",
3272
- "exploreFoldEnabled",
3273
- "editMode",
3274
- "hashlineEditEnabled",
3275
- "compactStrategy",
3276
- "smartCompactEnabled",
3277
- "smartCompactSummaryModel",
3278
- "smartCompactMode",
3279
- "memoryLanguage",
3280
- "skillPaths",
3281
- "mcpServers",
3282
- "pluginTools",
3283
- "secretaryTools",
3284
- "workflowPresetFiles",
3285
- "pluginEvents",
3286
- "instruction",
3287
- "approvalMode",
3288
- "autoRejectApprovals",
3289
- "askRelay",
3290
- "approvalReviewer",
3291
- "approvalReviewerClassifier",
3292
- "approvalReviewerManaged",
3293
- "approvalReviewerAllowThreshold",
3294
- "agentTypes",
3295
- "subagentModels",
3296
- "disabledTools",
3297
- "windowsLocalShell",
3298
- "rtkEnabled",
3299
- "dcgPath",
3300
- "remote",
3301
- "rolePrompt",
3302
- "systemPrompt",
3303
- "systemPromptAppend",
3304
- "systemPromptBoost",
3305
- "refusalRetryPrompt",
3306
- "botMode",
3307
- "botGroupTasks",
3308
- "botDiscussMode",
3309
- "botRoutines",
3310
- "secretaryMode",
3311
- "botDelegationTask",
3312
- "botWriteLock",
3313
- "protectedActions",
3314
- "planMode",
3315
- "instanceId"
3316
- ]) || !parseSessionIdentity(value.identity) || typeof value.cwd !== "string" || !parseSessionModelConfig(value.model) || value.resumeFile !== void 0 && !isNonEmptyString(value.resumeFile) || value.loadHarnessAssets !== void 0 && typeof value.loadHarnessAssets !== "boolean" || value.trustedProjectCode !== void 0 && !(Array.isArray(value.trustedProjectCode) && value.trustedProjectCode.length <= 500 && value.trustedProjectCode.every(
3317
- (entry) => typeof entry === "string" && entry.length > 0 && entry.length <= 1024
3318
- )) || value.pluginTools !== void 0 && !isPluginToolList(value.pluginTools) || value.secretaryTools !== void 0 && parseSecretaryToolDescriptors(value.secretaryTools) === null || value.workflowPresetFiles !== void 0 && !(Array.isArray(value.workflowPresetFiles) && value.workflowPresetFiles.length <= 500 && value.workflowPresetFiles.every(
3319
- (entry) => typeof entry === "string" && entry.length > 0 && entry.length <= 1024
3320
- )) || value.pluginEvents !== void 0 && !isPluginEventPlan(value.pluginEvents) || value.rtkEnabled !== void 0 && typeof value.rtkEnabled !== "boolean" || value.dcgPath !== void 0 && !isNonEmptyString(value.dcgPath) || value.planMode !== void 0 && typeof value.planMode !== "boolean" || value.windowsLocalShell !== void 0 && !WINDOWS_LOCAL_SHELLS.includes(value.windowsLocalShell) || value.exploreFoldEnabled !== void 0 && typeof value.exploreFoldEnabled !== "boolean" || value.editMode !== void 0 && !isEditMode(value.editMode) || value.hashlineEditEnabled !== void 0 && typeof value.hashlineEditEnabled !== "boolean" || value.compactStrategy !== void 0 && parseCompactStrategy(value.compactStrategy) === null || value.smartCompactEnabled !== void 0 && typeof value.smartCompactEnabled !== "boolean" || value.smartCompactSummaryModel !== void 0 && parseSpawnModelConfig(value.smartCompactSummaryModel) === null || value.smartCompactMode !== void 0 && parseSmartCompactMode(value.smartCompactMode) === null || value.memoryLanguage !== void 0 && typeof value.memoryLanguage !== "string" || value.remote !== void 0 && parseAgentRemoteConfig(value.remote) === null || value.subagentModels !== void 0 && (!Array.isArray(value.subagentModels) || value.subagentModels.some((entry) => parseSubagentModelOption(entry) === null)) || value.approvalReviewer !== void 0 && parseSpawnModelConfig(value.approvalReviewer) === null || value.askRelay !== void 0 && (!isRecord(value.askRelay) || !isNonEmptyString(value.askRelay.name)) || value.approvalReviewerAllowThreshold !== void 0 && (!isApprovalAllowThreshold(value.approvalReviewerAllowThreshold) || value.approvalReviewerClassifier === void 0) || value.approvalReviewerManaged !== void 0 && (value.approvalReviewerManaged !== true || value.approvalReviewerClassifier === void 0) || value.approvalReviewerClassifier !== void 0 && (value.approvalReviewer !== void 0 || !parseClassifierCredentials(value.approvalReviewerClassifier)) || value.rolePrompt !== void 0 && !isNonEmptyString(value.rolePrompt) || value.systemPrompt !== void 0 && !isNonEmptyString(value.systemPrompt) || value.systemPromptAppend !== void 0 && !isNonEmptyString(value.systemPromptAppend) || value.systemPromptBoost !== void 0 && !isNonEmptyString(value.systemPromptBoost) || value.refusalRetryPrompt !== void 0 && !isNonEmptyString(value.refusalRetryPrompt) || value.botMode !== void 0 && typeof value.botMode !== "boolean" || value.botGroupTasks !== void 0 && typeof value.botGroupTasks !== "boolean" || value.botDiscussMode !== void 0 && typeof value.botDiscussMode !== "boolean" || value.botDiscussMode === true && (value.botMode !== true || value.botGroupTasks !== true) || value.botRoutines !== void 0 && typeof value.botRoutines !== "boolean" || value.secretaryMode !== void 0 && typeof value.secretaryMode !== "boolean" || value.botDelegationTask !== void 0 && typeof value.botDelegationTask !== "boolean" || value.botWriteLock !== void 0 && (!isRecord(value.botWriteLock) || !isNonEmptyString(value.botWriteLock.label) || !Array.isArray(value.botWriteLock.ancestors) || !value.botWriteLock.ancestors.every(isNonEmptyString)) || value.protectedActions !== void 0 && typeof value.protectedActions !== "boolean" || value.instanceId !== void 0 && !isUuid(value.instanceId)) {
3321
- return null;
3322
- }
3323
- return value;
3324
- },
3325
- "spawn-child": (value) => {
3326
- return hasOnlyKeys(value, ["type", "identity", "cwd", "config", "resumeFile"]) && parseChildSessionIdentity(value.identity) && typeof value.cwd === "string" && parseResolvedAgentTypeSpawnConfig(value.config) && (value.resumeFile === void 0 || isNonEmptyString(value.resumeFile)) ? value : null;
3327
- },
3328
- "prompt-child": (value) => {
3329
- return hasOnlyKeys(value, ["type", "identity", "requestId", "task", "requestBudget"]) && parseChildSessionIdentity(value.identity) && isNonEmptyString(value.requestId) && parseAgentDispatchTask(value.task) && (value.requestBudget === void 0 || value.requestBudget === true) ? value : null;
3330
- },
3331
- "agent-control-result": (value) => {
3332
- return hasExactKeys(value, ["type", "identity", "requestId", "response"]) && parseAnySessionIdentity(value.identity) && isNonEmptyString(value.requestId) && parseAgentControlToolResponse(value.response) ? value : null;
3333
- },
3334
- "dismiss-child": (value) => {
3335
- const parent = parseSessionIdentity(value.parent);
3336
- const child = parseChildSessionIdentity(value.child);
3337
- return hasOnlyKeys(value, ["type", "parent", "child", "notify"]) && parent && child && child.parent.sessionId === parent.sessionId && child.parent.generation === parent.generation && (value.notify === void 0 || typeof value.notify === "boolean") ? value : null;
3338
- },
3339
- "dismiss-coworker": (value) => {
3340
- const parent = parseSessionIdentity(value.parent);
3341
- return hasOnlyKeys(value, ["type", "parent", "coworkerId", "notify"]) && parent && isNonEmptyString(value.coworkerId) && // 归属校验:coworker id 恒为 `父id::cw-…`,防跨会话误解雇
3342
- value.coworkerId.startsWith(`${parent.sessionId}::cw-`) && (value.notify === void 0 || typeof value.notify === "boolean") ? value : null;
3343
- },
3344
- "resume-coworker": (value) => {
3345
- const parent = parseSessionIdentity(value.parent);
3346
- return hasOnlyKeys(value, [
3347
- "type",
3348
- "parent",
3349
- "coworkerId",
3350
- "name",
3351
- "agentType",
3352
- "resumeFile"
3353
- ]) && parent && isNonEmptyString(value.coworkerId) && value.coworkerId.startsWith(`${parent.sessionId}::cw-`) && isNonEmptyString(value.name) && (value.agentType === void 0 || isNonEmptyString(value.agentType)) && isNonEmptyString(value.resumeFile) ? value : null;
3354
- },
3355
- "complete-text": (value) => {
3356
- return hasOnlyKeys(value, [
3357
- "type",
3358
- "requestId",
3359
- "systemPrompt",
3360
- "userText",
3361
- "candidates",
3362
- "timeoutMs",
3363
- "maxTokens",
3364
- "stream",
3365
- "reasoning",
3366
- "probe"
3367
- ]) && isNonEmptyString(value.requestId) && typeof value.systemPrompt === "string" && typeof value.userText === "string" && typeof value.timeoutMs === "number" && Number.isFinite(value.timeoutMs) && value.timeoutMs > 0 && (value.maxTokens === void 0 || typeof value.maxTokens === "number" && Number.isInteger(value.maxTokens) && value.maxTokens > 0) && (value.stream === void 0 || value.stream === true) && (value.reasoning === void 0 || value.reasoning === "off" || THINKING_LEVELS.includes(value.reasoning)) && (value.probe === void 0 || value.probe === true) && Array.isArray(value.candidates) && value.candidates.length >= 1 && value.candidates.length <= TITLE_SUMMARY_MAX_CANDIDATES && value.candidates.every((candidate) => parseSpawnModelConfig(candidate)) ? value : null;
3368
- },
3369
- "abort-complete-text": (value) => {
3370
- return hasExactKeys(value, ["type", "requestId"]) && isNonEmptyString(value.requestId) ? value : null;
3371
- },
3372
- "classify-choice": (value) => {
3373
- return hasExactKeys(value, [
3374
- "type",
3375
- "requestId",
3376
- "classifier",
3377
- "state",
3378
- "instructions",
3379
- "criteria",
3380
- "timeoutMs"
3381
- ]) && isNonEmptyString(value.requestId) && parseClassifierCredentials(value.classifier) && isRecord(value.state) && isNonEmptyString(value.instructions) && isRecord(value.criteria) && Object.keys(value.criteria).length > 0 && Object.values(value.criteria).every(isNonEmptyString) && typeof value.timeoutMs === "number" && Number.isFinite(value.timeoutMs) && value.timeoutMs > 0 ? value : null;
3382
- },
3383
- "abort-classify-choice": (value) => {
3384
- return hasExactKeys(value, ["type", "requestId"]) && isNonEmptyString(value.requestId) ? value : null;
3385
- },
3386
- "summarize-title": (value) => {
3387
- return hasExactKeys(value, ["type", "conversationId", "input", "candidates"]) && isNonEmptyString(value.conversationId) && parseTitleSummaryInput(value.input) && Array.isArray(value.candidates) && value.candidates.length >= 1 && value.candidates.length <= TITLE_SUMMARY_MAX_CANDIDATES && value.candidates.every((candidate) => parseSpawnModelConfig(candidate)) ? value : null;
3388
- },
3389
- prompt: parsePromptOrSteer,
3390
- steer: parsePromptOrSteer,
3391
- "set-model": (value) => {
3392
- return hasExactKeys(value, ["type", "identity", "model"]) && parseAnySessionIdentity(value.identity) && parseSessionModelConfig(value.model) ? value : null;
3393
- },
3394
- "set-thinking": (value) => {
3395
- return hasExactKeys(value, ["type", "identity", "level"]) && parseAnySessionIdentity(value.identity) && THINKING_LEVELS.includes(value.level) ? value : null;
3396
- },
3397
- "set-system-prompt": (value) => {
3398
- return hasExactKeys(value, ["type", "identity", "systemPrompt"]) && parseSessionIdentity(value.identity) && isNonEmptyString(value.systemPrompt) ? value : null;
3399
- },
3400
- "set-reasoning": (value) => {
3401
- return hasOnlyKeys(value, ["type", "identity", "enabled", "level"]) && parseAnySessionIdentity(value.identity) && typeof value.enabled === "boolean" && (value.level === void 0 || THINKING_LEVELS.includes(value.level)) ? value : null;
3402
- },
3403
- "approval-respond": (value) => {
3404
- return hasExactKeys(value, ["type", "identity", "requestId", "decision"]) && parseAnySessionIdentity(value.identity) && isNonEmptyString(value.requestId) && isApprovalDecision(value.decision) ? value : null;
3405
- },
3406
- "request-timeout": (value) => {
3407
- return hasExactKeys(value, ["type", "identity", "kind", "requestId"]) && parseAnySessionIdentity(value.identity) && (value.kind === "approval" || value.kind === "ask") && isNonEmptyString(value.requestId) ? value : null;
3408
- },
3409
- "agent-notify": (value) => {
3410
- return hasExactKeys(value, ["type", "identity", "text", "urgent"]) && parseSessionIdentity(value.identity) && isNonEmptyString(value.text) && typeof value.urgent === "boolean" ? value : null;
3411
- },
3412
- "set-approval-mode": (value) => {
3413
- return hasOnlyKeys(value, ["type", "identity", "mode", "autoReject"]) && parseAnySessionIdentity(value.identity) && APPROVAL_MODES.includes(value.mode) && (value.autoReject === void 0 || typeof value.autoReject === "boolean") ? value : null;
3414
- },
3415
- "set-ask-relay": (value) => {
3416
- return hasOnlyKeys(value, ["type", "identity", "relay"]) && parseAnySessionIdentity(value.identity) && (value.relay === void 0 || isRecord(value.relay) && isNonEmptyString(value.relay.name)) ? value : null;
3417
- },
3418
- "set-plan-mode": (value) => {
3419
- return hasExactKeys(value, ["type", "identity", "active"]) && parseSessionIdentity(value.identity) && typeof value.active === "boolean" ? value : null;
3420
- },
3421
- "plan-respond": (value) => {
3422
- return hasOnlyKeys(value, ["type", "identity", "planId", "action", "feedback"]) && parseSessionIdentity(value.identity) && isNonEmptyString(value.planId) && PLAN_RESPOND_ACTIONS.includes(value.action) && (value.feedback === void 0 || typeof value.feedback === "string" && value.feedback.length <= PLAN_FEEDBACK_MAX) ? value : null;
3423
- },
3424
- "set-approval-reviewer": (value) => {
3425
- return hasOnlyKeys(value, ["type", "model", "classifier", "managed", "allowThreshold"]) && (value.allowThreshold === void 0 || isApprovalAllowThreshold(value.allowThreshold) && value.classifier !== void 0) && (value.model === void 0 || parseSpawnModelConfig(value.model)) && (value.classifier === void 0 || value.model === void 0 && parseClassifierCredentials(value.classifier)) && (value.managed === void 0 || value.managed === true && value.classifier !== void 0) ? value : null;
3426
- },
3427
- "set-compact-route": (value) => {
3428
- return hasOnlyKeys(value, ["type", "model", "mode"]) && (value.model === void 0 || parseSpawnModelConfig(value.model) !== null) && (value.mode === void 0 || parseSmartCompactMode(value.mode) !== null) ? value : null;
3429
- },
3430
- "set-max-active-coworkers": (value) => {
3431
- return hasExactKeys(value, ["type", "limit"]) && parseMaxActiveCoworkers(value.limit) !== null ? value : null;
3432
- },
3433
- "set-auto-retry-limit": (value) => {
3434
- return hasExactKeys(value, ["type", "limit"]) && parseAutoRetryLimit(value.limit) !== null ? value : null;
3435
- },
3436
- "set-long-cache-retention": (value) => {
3437
- return hasExactKeys(value, ["type", "enabled"]) && typeof value.enabled === "boolean" ? value : null;
3438
- },
3439
- "set-shell-limits": (value) => {
3440
- return hasExactKeys(value, ["type", "limits"]) && isRecord(value.limits) && JSON.stringify(resolveShellLimits(value.limits)) === JSON.stringify(value.limits) ? value : null;
3441
- },
3442
- "set-privacy-masking": (value) => {
3443
- return hasExactKeys(value, ["type", "settings"]) && JSON.stringify(parsePrivacyMaskSettings(value.settings)) === JSON.stringify(value.settings) ? value : null;
3444
- },
3445
- "set-image-generation-config": (value) => {
3446
- return hasOnlyKeys(value, ["type", "config", "error"]) && (value.config === null || parseImageGenerationConfig(value.config) !== null) && (value.error === void 0 || typeof value.error === "string" && value.error.length <= 1024) ? value : null;
3447
- },
3448
- "set-web-search-config": (value) => {
3449
- return hasOnlyKeys(value, ["type", "chain", "configured"]) && (value.configured === void 0 || typeof value.configured === "boolean") && Array.isArray(value.chain) && value.chain.length <= WEB_SEARCH_CHAIN_MAX && value.chain.every(isWebSearchChainEntry) ? value : null;
3450
- },
3451
- "set-disabled-workflow-presets": (value) => {
3452
- return hasExactKeys(value, ["type", "ids"]) && Array.isArray(value.ids) && value.ids.length <= 64 && value.ids.every((id) => typeof id === "string" && isWorkflowPresetId(id)) ? value : null;
3453
- },
3454
- "set-builtin-tools": (value) => {
3455
- return hasExactKeys(value, ["type", "identity", "disabledTools"]) && parseSessionIdentity(value.identity) && Array.isArray(value.disabledTools) && value.disabledTools.length <= 64 && value.disabledTools.every((id) => typeof id === "string" && id.length > 0 && id.length <= 64) ? value : null;
3456
- },
3457
- "set-model-directory": (value) => {
3458
- return hasExactKeys(value, ["type", "snapshot", "customProviders"]) ? value : null;
3459
- },
3460
- "ask-respond": (value) => {
3461
- return hasOnlyKeys(value, ["type", "identity", "requestId", "answer", "by", "name"]) && parseAnySessionIdentity(value.identity) && isNonEmptyString(value.requestId) && isNonEmptyString(value.answer) && (value.by === void 0 || value.by === "user" || value.by === "relay") && (value.name === void 0 || isNonEmptyString(value.name)) ? value : null;
3462
- },
3463
- "browser-result": parseHostResultCommand,
3464
- "memory-result": parseHostResultCommand,
3465
- "delegation-result": parseHostResultCommand,
3466
- "computer-result": parseHostResultCommand,
3467
- "plugin-tool-result": parseHostResultCommand,
3468
- "secretary-result": (value) => {
3469
- if (!hasOnlyKeys(value, ["type", "identity", "requestId", "ok", "result", "error"]) || !parseSessionIdentity(value.identity) || !isNonEmptyString(value.requestId) || typeof value.ok !== "boolean") {
3470
- return null;
3471
- }
3472
- const shapeOk = value.ok ? value.error === void 0 : isNonEmptyString(value.error) && value.result === void 0;
3473
- return shapeOk ? value : null;
3474
- },
3475
- "plugin-intercept-result": (value) => {
3476
- if (!hasOnlyKeys(value, ["type", "identity", "requestId", "ok", "result", "error"]) || !parseSessionIdentity(value.identity) || !isNonEmptyString(value.requestId) || typeof value.ok !== "boolean") {
3477
- return null;
3478
- }
3479
- const shapeOk = value.ok ? value.error === void 0 : isNonEmptyString(value.error) && value.result === void 0;
3480
- return shapeOk ? value : null;
3481
- },
3482
- "plugin-tool-progress": (value) => {
3483
- return hasExactKeys(value, ["type", "identity", "requestId", "text"]) && parseSessionIdentity(value.identity) && isNonEmptyString(value.requestId) && isBoundedText(value.text, PLUGIN_PROGRESS_MAX_CHARS) ? value : null;
3484
- },
3485
- "plugin-inject": (value) => {
3486
- return hasOnlyKeys(value, [...PLUGIN_INJECT_KEYS, "images"]) && PLUGIN_INJECT_KEYS.every((key) => key in value) && parsePluginInjectImages(value.images) !== null && parseSessionIdentity(value.identity) && isNonEmptyString(value.pluginId) && value.pluginId.length <= 128 && isNonEmptyString(value.pluginName) && value.pluginName.length <= 256 && isNonEmptyString(value.text) && isBoundedText(value.text, PLUGIN_INJECT_MAX_CHARS) && (value.deliverAs === "steer" || value.deliverAs === "followUp" || value.deliverAs === "nextTurn") && typeof value.triggerTurn === "boolean" ? value : null;
3487
- },
3488
- "workflow-stop": (value) => {
3489
- return hasExactKeys(value, ["type", "identity", "runId"]) && parseAnySessionIdentity(value.identity) && isNonEmptyString(value.runId) && value.runId.length <= 80 ? value : null;
3490
- },
3491
- "task-stop": (value) => {
3492
- return hasExactKeys(value, ["type", "sessionId", "taskId"]) && isNonEmptyString(value.sessionId) && isNonEmptyString(value.taskId) ? value : null;
3493
- },
3494
- "task-keep": (value) => {
3495
- return hasExactKeys(value, ["type", "sessionId", "taskId", "reason"]) && isNonEmptyString(value.sessionId) && isNonEmptyString(value.taskId) && (value.reason === null || typeof value.reason === "string" && value.reason.length <= TASK_KEEP_REASON_MAX) ? value : null;
3496
- },
3497
- "tool-background": (value) => {
3498
- return hasExactKeys(value, ["type", "identity", "toolCallId"]) && parseAnySessionIdentity(value.identity) && isNonEmptyString(value.toolCallId) && value.toolCallId.length <= 512 ? value : null;
3499
- },
3500
- "subagent-stop": (value) => {
3501
- return hasExactKeys(value, ["type", "identity", "agentId"]) && parseAnySessionIdentity(value.identity) && isNonEmptyString(value.agentId) ? value : null;
3502
- },
3503
- compact: (value) => {
3504
- return hasOnlyKeys(value, ["type", "identity", "instructions"]) && parseAnySessionIdentity(value.identity) && (value.instructions === void 0 || isNonEmptyString(value.instructions)) ? value : null;
3505
- },
3506
- rewind: (value) => {
3507
- return hasOnlyKeys(value, [
3508
- "type",
3509
- "identity",
3510
- "entryId",
3511
- "userIndexFromEnd",
3512
- "restoreFiles"
3513
- ]) && parseAnySessionIdentity(value.identity) && (value.entryId !== void 0 ? isNonEmptyString(value.entryId) && value.entryId.trim().length > 0 && value.userIndexFromEnd === void 0 : isSequence(value.userIndexFromEnd)) && (value.restoreFiles === void 0 || typeof value.restoreFiles === "boolean") ? value : null;
3514
- },
3515
- fork: (value) => {
3516
- const hasEntry = typeof value.entryId === "string";
3517
- const hasIndex = typeof value.userIndexFromEnd === "number";
3518
- return hasOnlyKeys(value, [
3519
- "type",
3520
- "identity",
3521
- "targetConversationId",
3522
- "entryId",
3523
- "userIndexFromEnd"
3524
- ]) && parseAnySessionIdentity(value.identity) && isUuid(value.targetConversationId) && (hasEntry ? !hasIndex && isNonEmptyString(value.entryId) : hasIndex && isSequence(value.userIndexFromEnd)) ? value : null;
3525
- },
3526
- abort: parseIdentityOnlyCommand,
3527
- "abort-retry": parseIdentityOnlyCommand,
3528
- "release-parent": parseIdentityOnlyCommand,
3529
- "withdraw-steer": (value) => {
3530
- return hasExactKeys(value, ["type", "identity", "deliveryId"]) && parseAnySessionIdentity(value.identity) && isDeliveryId(value.deliveryId) ? value : null;
3531
- },
3532
- retry: (value) => {
3533
- return hasOnlyKeys(value, [
3534
- "type",
3535
- "identity",
3536
- "instanceId",
3537
- "unfinishedOnly",
3538
- "turnId",
3539
- "requestBudget",
3540
- "requestsUsed"
3541
- ]) && parseAnySessionIdentity(value.identity) && (value.unfinishedOnly === void 0 || value.unfinishedOnly === true) && (value.turnId === void 0 || isNonEmptyString(value.turnId)) && (value.requestBudget === void 0 || value.requestBudget === true) && (value.requestsUsed === void 0 || Number.isInteger(value.requestsUsed) && value.requestsUsed >= 0) && (value.instanceId === void 0 || isUuid(value.instanceId) && parseSessionIdentity(value.identity) !== null) ? value : null;
3542
- },
3543
- "append-session-custom-entry": (value) => {
3544
- return hasExactKeys(value, ["type", "identity", "entry"]) && parseAnySessionIdentity(value.identity) && parseAgentSessionCustomEntry(value.entry) ? value : null;
3545
- },
3546
- "reload-session": (value) => {
3547
- return hasExactKeys(value, ["type", "requestId", "sessionId"]) && isNonEmptyString(value.requestId) && isNonEmptyString(value.sessionId) ? value : null;
3548
- },
3549
- snapshot: (value) => {
3550
- if (hasExactKeys(value, ["type"])) return { type: "snapshot" };
3551
- return hasExactKeys(value, ["type", "sessionId"]) && isNonEmptyString(value.sessionId) ? { type: "snapshot", sessionId: value.sessionId } : null;
3552
- },
3553
- "pin-sessions": (value) => {
3554
- return hasExactKeys(value, ["type", "sessionIds"]) && Array.isArray(value.sessionIds) && value.sessionIds.every((id) => typeof id === "string") ? { type: "pin-sessions", sessionIds: value.sessionIds } : null;
3555
- },
3556
- "graceful-restart": (value) => {
3557
- if (hasExactKeys(value, ["type"])) return { type: "graceful-restart" };
3558
- return hasExactKeys(value, ["type", "keepBackgroundTasks"]) && value.keepBackgroundTasks === true ? { type: "graceful-restart", keepBackgroundTasks: true } : null;
3559
- },
3560
- "detach-background-tasks": (value) => {
3561
- return hasExactKeys(value, ["type"]) ? { type: "detach-background-tasks" } : null;
3562
- },
3563
- "warm-mcp": (value) => {
3564
- return hasExactKeys(value, ["type", "servers"]) && Array.isArray(value.servers) ? value : null;
3565
- },
3566
- "plugin-mcp-list": (value) => {
3567
- return hasExactKeys(value, ["type", "requestId", "servers"]) && isNonEmptyString(value.requestId) && Array.isArray(value.servers) ? value : null;
3568
- },
3569
- "plugin-mcp-call": (value) => {
3570
- return hasExactKeys(value, ["type", "requestId", "servers", "server", "tool", "args"]) && isNonEmptyString(value.requestId) && Array.isArray(value.servers) && isNonEmptyString(value.server) && isNonEmptyString(value.tool) && isRecord(value.args) ? value : null;
3571
- },
3572
- "plugin-mcp-cancel": (value) => {
3573
- return hasExactKeys(value, ["type", "requestId"]) && isNonEmptyString(value.requestId) ? { type: "plugin-mcp-cancel", requestId: value.requestId } : null;
3574
- },
3575
- "plugin-agent-run": (value) => {
3576
- return hasOnlyKeys(value, [
3577
- "type",
3578
- "requestId",
3579
- "identity",
3580
- "prompt",
3581
- "systemPrompt",
3582
- "context",
3583
- "timeoutMs",
3584
- "model"
3585
- ]) && isNonEmptyString(value.requestId) && parseSessionIdentity(value.identity) && isNonEmptyString(value.prompt) && isBoundedText(value.prompt, PLUGIN_AGENT_PROMPT_MAX_CHARS) && (value.systemPrompt === void 0 || typeof value.systemPrompt === "string" && isBoundedText(value.systemPrompt, PLUGIN_AGENT_SYSTEM_MAX_CHARS)) && (value.context === "conversation" || value.context === "fork" || value.context === "none") && Number.isInteger(value.timeoutMs) && value.timeoutMs > 0 && value.timeoutMs <= PLUGIN_AGENT_MAX_TIMEOUT_MS && (value.model === void 0 || parseSpawnModelConfig(value.model) !== null) ? value : null;
3586
- },
3587
- "plugin-agent-cancel": (value) => {
3588
- return hasExactKeys(value, ["type", "requestId"]) && isNonEmptyString(value.requestId) ? { type: "plugin-agent-cancel", requestId: value.requestId } : null;
3589
- },
3590
- "set-proxy-env": (value) => {
3591
- if (!hasExactKeys(value, ["type", "env"]) || !isRecord(value.env)) return null;
3592
- for (const entry of Object.values(value.env)) {
3593
- if (entry !== null && typeof entry !== "string") return null;
3594
- }
3595
- return value;
3596
- }
3597
- };
3598
- function parseAgentCommand(value) {
3599
- if (!isRecord(value) || !isNonEmptyString(value.type)) return null;
3600
- return parseClosed(agentCommandParsers, value.type, value);
3601
- }
3602
- const isOptionalTimestamp = (value) => value === void 0 || typeof value === "number" && Number.isFinite(value);
3603
- const DEFERRED_SESSION_KEYS = /* @__PURE__ */ new Set([
3604
- "identity",
3605
- "reason",
3606
- "toolsInFlight",
3607
- "toolNames",
3608
- "undetachableTasks",
3609
- "reply"
3610
- ]);
3611
- function isRestartReplyProgress(value) {
3612
- return isRecord(value) && Object.keys(value).every(
3613
- (key) => key === "requestStartMs" || key === "firstTokenMs" || key === "lastOutputMs"
3614
- ) && isNonNegativeNumber(value.requestStartMs) && (value.firstTokenMs === void 0 || isNonNegativeNumber(value.firstTokenMs)) && (value.lastOutputMs === void 0 || isNonNegativeNumber(value.lastOutputMs));
3615
- }
3616
- const parseWorkspaceLockResult = (value) => {
3617
- return hasOnlyKeys(value, ["type", "requestId", "ok", "error"]) && isNonEmptyString(value.requestId) && (value.ok === true ? value.error === void 0 : value.ok === false && isNonEmptyString(value.error)) ? value : null;
3618
- };
3619
- const parseParentLifecycleEnd = requireEventIdentity(
3620
- "parent",
3621
- (value) => {
3622
- return hasOnlyKeys(value, ["type", "identity", "seq", "reason", "instanceId"]) && isNonEmptyString(value.reason) && (value.instanceId === void 0 || isUuid(value.instanceId)) ? value : null;
3623
- }
3624
- );
3625
- const parseChildLifecycleEnd = requireEventIdentity(
3626
- "child",
3627
- (value) => {
3628
- return isNonEmptyString(value.reason) ? value : null;
3629
- }
3630
- );
3631
- const parseDeliveryOutcome = requireEventIdentity(
3632
- "any",
3633
- (value) => {
3634
- return hasExactKeys(value, ["type", "identity", "seq", "deliveryId"]) && isDeliveryId(value.deliveryId) ? value : null;
3635
- }
3636
- );
3637
- const parseTaskEvent = requireEventIdentity(
3638
- "any",
3639
- (value) => {
3640
- return isNonEmptyString(value.taskId) ? value : null;
3641
- }
3642
- );
3643
- const agentWorkerEventParsers = {
3644
- "privacy-mask-ledger": (value) => {
3645
- const record2 = parsePrivacyMaskRecord(value.record);
3646
- return hasExactKeys(value, ["type", "record"]) && record2 ? { type: "privacy-mask-ledger", record: record2 } : null;
3647
- },
3648
- "oauth-pool-select": (value) => {
3649
- return hasOnlyKeys(value, [
3650
- "type",
3651
- "requestId",
3652
- "settingsProviderId",
3653
- "modelId",
3654
- "failed",
3655
- "excludedAccountKeys"
3656
- ]) && isNonEmptyString(value.requestId) && isNonEmptyString(value.settingsProviderId) && isNonEmptyString(value.modelId) && (value.excludedAccountKeys === void 0 || Array.isArray(value.excludedAccountKeys) && value.excludedAccountKeys.length <= 100 && value.excludedAccountKeys.every(isCodexAccountKey)) && (value.failed === void 0 || parseOauthPoolFailure(value.failed) !== null) ? value : null;
3657
- },
3658
- "workspace-lock-result": parseWorkspaceLockResult,
3659
- "workspace-unlock-result": parseWorkspaceLockResult,
3660
- "plugin-mcp-result": (value) => {
3661
- if (!isNonEmptyString(value.requestId)) return null;
3662
- if (value.ok === true)
3663
- return hasExactKeys(value, ["type", "requestId", "ok", "value"]) ? value : null;
3664
- return value.ok === false && hasExactKeys(value, ["type", "requestId", "ok", "error"]) && isNonEmptyString(value.error) ? value : null;
3665
- },
3666
- "plugin-agent-event": (value) => {
3667
- if (!hasExactKeys(value, ["type", "requestId", "event"]) || !isNonEmptyString(value.requestId))
3668
- return null;
3669
- const event = parsePluginAgentRunEvent(value.event);
3670
- return event ? { type: "plugin-agent-event", requestId: value.requestId, event } : null;
3671
- },
3672
- "session-reloaded": (value) => {
3673
- if (!hasExactKeys(value, ["type", "requestId", "result"]) || !isNonEmptyString(value.requestId) || !isRecord(value.result))
3674
- return null;
3675
- const result = value.result;
3676
- const valid = result.ok === true ? hasExactKeys(result, ["ok", "snapshot", "seq"]) && parseSessionSnapshot(result.snapshot) !== null && isSequence(result.seq) : result.ok === false && hasExactKeys(result, ["ok", "error"]) && isNonEmptyString(result.error);
3677
- return valid ? value : null;
3678
- },
3679
- snapshot: (value) => {
3680
- return Array.isArray(value.sessions) && value.sessions.every((session) => parseSessionSnapshot(session) !== null) ? value : null;
3681
- },
3682
- "mcp-status": (value) => {
3683
- return hasOnlyKeys(value, [
3684
- "type",
3685
- "serverId",
3686
- "serverName",
3687
- "state",
3688
- "toolCount",
3689
- "error",
3690
- "scopeChallenge"
3691
- ]) && (value.scopeChallenge === void 0 || isMcpScopeChallenge(value.scopeChallenge)) && isNonEmptyString(value.serverName) && (value.serverId === void 0 || isNonEmptyString(value.serverId)) && (value.toolCount === void 0 || isSequence(value.toolCount)) && (value.error === void 0 || typeof value.error === "string") && MCP_CONNECTION_STATES.includes(value.state) ? value : null;
3692
- },
3693
- "mcp-oauth-refresh": (value) => {
3694
- return hasOnlyKeys(value, ["type", "requestId", "serverId", "rejected"]) && isNonEmptyString(value.requestId) && isNonEmptyString(value.serverId) && (value.rejected === void 0 || isNonEmptyString(value.rejected)) ? value : null;
3695
- },
3696
- "title-generated": (value) => {
3697
- return hasExactKeys(value, ["type", "conversationId", "title"]) && isNonEmptyString(value.conversationId) && isNonEmptyString(value.title) ? value : null;
3698
- },
3699
- "title-failed": (value) => {
3700
- return hasExactKeys(value, ["type", "conversationId", "error"]) && isNonEmptyString(value.conversationId) && isNonEmptyString(value.error) ? value : null;
3701
- },
3702
- "tool-batch-completed": (value) => {
3703
- return hasExactKeys(value, ["type", "identity", "digest"]) && parseSessionIdentity(value.identity) && parseToolBatchDigest(value.digest) ? value : null;
3704
- },
3705
- "graceful-restart-deferred": (value) => {
3706
- return hasExactKeys(value, ["type", "sessions"]) && Array.isArray(value.sessions) && value.sessions.every(
3707
- (entry) => isRecord(entry) && Object.keys(entry).every((key) => DEFERRED_SESSION_KEYS.has(key)) && (entry.undetachableTasks === void 0 || Array.isArray(entry.undetachableTasks) && entry.undetachableTasks.every(isNonEmptyString)) && (entry.toolNames === void 0 || Array.isArray(entry.toolNames) && entry.toolNames.every(isNonEmptyString)) && (entry.reply === void 0 || isRestartReplyProgress(entry.reply)) && parseSessionIdentity(entry.identity) && (entry.reason === "tool-in-flight" || entry.reason === "turn-in-progress" || entry.reason === "session-starting") && Array.isArray(entry.toolsInFlight) && entry.toolsInFlight.every(isNonEmptyString)
3708
- ) ? value : null;
3709
- },
3710
- // 断点内容由 Main 用 parseRestartCheckpoint 细验(该函数带 node:fs,渲染层不能引)
3711
- "graceful-restart-ready": (value) => {
3712
- return hasExactKeys(value, ["type", "checkpoint"]) && isRecord(value.checkpoint) && Array.isArray(value.checkpoint.sessions) ? value : null;
3713
- },
3714
- "background-tasks-detached": (value) => {
3715
- return hasExactKeys(value, ["type", "detached"]) && typeof value.detached === "number" && Number.isInteger(value.detached) && value.detached >= 0 ? value : null;
3716
- },
3717
- "session-wake-requested": (value) => {
3718
- return hasExactKeys(value, ["type", "sessionId"]) && isNonEmptyString(value.sessionId) ? value : null;
3719
- },
3720
- "unopened-background-tasks": (value) => {
3721
- return hasExactKeys(value, ["type", "sessionId", "tasks"]) && isNonEmptyString(value.sessionId) && Array.isArray(value.tasks) && value.tasks.every((task) => isRecord(task) && isNonEmptyString(task.taskId)) ? value : null;
3722
- },
3723
- "text-delta": (value) => {
3724
- return hasOnlyKeys(value, ["type", "requestId", "text", "thinking"]) && isNonEmptyString(value.requestId) && typeof value.text === "string" && (value.thinking === void 0 || typeof value.thinking === "string") ? value : null;
3725
- },
3726
- "text-completed": (value) => {
3727
- return hasExactKeys(value, ["type", "requestId", "text"]) && isNonEmptyString(value.requestId) && typeof value.text === "string" ? value : null;
3728
- },
3729
- "text-failed": (value) => {
3730
- return hasExactKeys(value, ["type", "requestId", "error"]) && isNonEmptyString(value.requestId) && isNonEmptyString(value.error) ? value : null;
3731
- },
3732
- "choice-classified": (value) => {
3733
- return hasExactKeys(value, ["type", "requestId", "probabilities"]) && isNonEmptyString(value.requestId) && isRecord(value.probabilities) && Object.values(value.probabilities).every((p) => typeof p === "number" && Number.isFinite(p)) ? value : null;
3734
- },
3735
- "choice-failed": (value) => {
3736
- return hasExactKeys(value, ["type", "requestId", "error"]) && isNonEmptyString(value.requestId) && isNonEmptyString(value.error) ? value : null;
3737
- },
3738
- "parent-ready": requireEventIdentity(
3739
- "parent",
3740
- (value) => {
3741
- return isNonEmptyString(value.sessionFile) && parseModelRef(value.model) && (value.imageInput === void 0 || typeof value.imageInput === "boolean") ? value : null;
3742
- }
3743
- ),
3744
- "model-changed": requireEventIdentity(
3745
- "parent",
3746
- (value) => {
3747
- return parseModelRef(value.model) && (value.imageInput === void 0 || typeof value.imageInput === "boolean") ? value : null;
3748
- }
3749
- ),
3750
- "parent-rejected": parseParentLifecycleEnd,
3751
- "parent-ended": parseParentLifecycleEnd,
3752
- "child-rejected": parseChildLifecycleEnd,
3753
- "child-ended": parseChildLifecycleEnd,
3754
- "child-reserved": requireEventIdentity(
3755
- "child",
3756
- (value) => {
3757
- return isNonEmptyString(value.requestId) && parseChildConversationMetadata(value.metadata) ? value : null;
3758
- }
3759
- ),
3760
- "child-ready": requireEventIdentity(
3761
- "child",
3762
- (value) => {
3763
- const proof = parseResolvedChildProfileProof(value.proof);
3764
- const identity = parseChildSessionIdentity(value.identity);
3765
- if (!identity) return null;
3766
- if (!hasExactKeys(value, ["type", "identity", "seq", "sessionFile", "proof"]) || !isNonEmptyString(value.sessionFile) || !proof || !("typeKey" in identity) || proof.typeKey !== identity.typeKey) {
3767
- return null;
3768
- }
3769
- return value;
3770
- }
3771
- ),
3772
- "request-body": requireEventIdentity(
3773
- "any",
3774
- (value) => {
3775
- const identity = parseAnySessionIdentity(value.identity);
3776
- if (!identity || !isSequence(value.seq)) return null;
3777
- const usage = parseRequestBodyUsage(value.usage);
3778
- return hasExactKeys(value, ["type", "identity", "seq", "usage"]) && usage ? { type: "request-body", identity, seq: value.seq, usage } : null;
3779
- }
3780
- ),
3781
- "agent-control-invoke": requireEventIdentity(
3782
- "any",
3783
- (value) => {
3784
- return hasExactKeys(value, ["type", "identity", "seq", "requestId", "request"]) && isNonEmptyString(value.requestId) && parseAgentControlToolRequest(value.request) ? value : null;
3785
- }
3786
- ),
3787
- "agent-control-cancel": requireEventIdentity(
3788
- "any",
3789
- (value) => {
3790
- return hasExactKeys(value, ["type", "identity", "seq", "requestId", "kind"]) && isNonEmptyString(value.requestId) && (value.kind === "abort" || value.kind === "detach") ? value : null;
3791
- }
3792
- ),
3793
- "browser-invoke": requireEventIdentity(
3794
- "any",
3795
- (value) => {
3796
- return hasExactKeys(value, ["type", "identity", "seq", "requestId", "op", "params"]) && isNonEmptyString(value.requestId) && BROWSER_OPS.includes(value.op) ? value : null;
3797
- }
3798
- ),
3799
- "memory-invoke": requireEventIdentity(
3800
- "any",
3801
- (value) => {
3802
- return hasExactKeys(value, ["type", "identity", "seq", "requestId", "op", "params"]) && isNonEmptyString(value.requestId) && MEMORY_OPS.includes(value.op) ? value : null;
3803
- }
3804
- ),
3805
- "delegation-invoke": requireEventIdentity(
3806
- "any",
3807
- (value) => {
3808
- return hasExactKeys(value, ["type", "identity", "seq", "requestId", "op", "params"]) && parseSessionIdentity(value.identity) && isNonEmptyString(value.requestId) && (value.op === "delegate" || value.op === "check_delegation" || value.op === "retry_delegation" || value.op === "group_tasks" || value.op === "group_history" || value.op === "routine_propose" || value.op === "send_image" || value.op === "report_blocked") ? value : null;
3809
- }
3810
- ),
3811
- "secretary-invoke": requireEventIdentity(
3812
- "any",
3813
- (value) => {
3814
- return hasExactKeys(value, ["type", "identity", "seq", "requestId", "op", "params"]) && parseSessionIdentity(value.identity) && isNonEmptyString(value.requestId) && (SECRETARY_OPS.includes(value.op) || SECRETARY_INTERNAL_OPS.includes(value.op)) ? value : null;
3815
- }
3816
- ),
3817
- "computer-invoke": requireEventIdentity(
3818
- "any",
3819
- (value) => {
3820
- return hasExactKeys(value, ["type", "identity", "seq", "requestId", "op", "params"]) && isNonEmptyString(value.requestId) && COMPUTER_OPS.includes(value.op) ? value : null;
3821
- }
3822
- ),
3823
- "computer-cancel": requireEventIdentity(
3824
- "any",
3825
- (value) => {
3826
- return hasExactKeys(value, ["type", "identity", "seq", "requestId"]) && isNonEmptyString(value.requestId) ? value : null;
3827
- }
3828
- ),
3829
- "plugin-tool-invoke": requireEventIdentity(
3830
- "any",
3831
- (value) => {
3832
- return hasPluginAgentKeys(value, [
3833
- "type",
3834
- "identity",
3835
- "seq",
3836
- "requestId",
3837
- "toolName",
3838
- "args"
3839
- ]) && isNonEmptyString(value.requestId) && typeof value.toolName === "string" && parsePluginToolName(value.toolName) !== null ? value : null;
3840
- }
3841
- ),
3842
- "plugin-tool-cancel": requireEventIdentity(
3843
- "any",
3844
- (value) => {
3845
- return hasExactKeys(value, ["type", "identity", "seq", "requestId"]) && isNonEmptyString(value.requestId) ? value : null;
3846
- }
3847
- ),
3848
- "plugin-event": requireEventIdentity(
3849
- "any",
3850
- (value) => {
3851
- return hasPluginAgentKeys(value, ["type", "identity", "seq", "event", "data"]) && parseSessionIdentity(value.identity) && typeof value.event === "string" && PLUGIN_EVENTS.includes(value.event) && // 主会话的 before_compact 要等插件,走 plugin-intercept;只有子会话的只通知
3852
- (value.event === "before_compact" ? value.agent !== void 0 && isPluginInterceptPayload(value.event, value.data) : isPluginObserveData(value.event, value.data)) ? value : null;
3853
- }
3854
- ),
3855
- "plugin-intercept": requireEventIdentity(
3856
- "any",
3857
- (value) => {
3858
- return hasPluginAgentKeys(value, [
3859
- "type",
3860
- "identity",
3861
- "seq",
3862
- "requestId",
3863
- "event",
3864
- "payload"
3865
- ]) && parseSessionIdentity(value.identity) && isNonEmptyString(value.requestId) && (value.event === "before_compact" || typeof value.event === "string" && isInterceptEvent(value.event)) && typeof value.event === "string" && (value.agent === void 0 || isChildInterceptEvent(value.event)) && isPluginInterceptPayload(value.event, value.payload) ? value : null;
3866
- }
3867
- ),
3868
- "workspace-branch-context-consumed": requireEventIdentity(
3869
- "any",
3870
- (value) => {
3871
- return hasExactKeys(value, ["type", "identity", "seq", "requestId"]) && isNonEmptyString(value.requestId) ? value : null;
3872
- }
3873
- ),
3874
- "delivery-settled": parseDeliveryOutcome,
3875
- "delivery-rejected": (value) => {
3876
- const { reason, ...rest } = value;
3877
- return (reason === void 0 || reason === "turn-stuck") && parseDeliveryOutcome(rest) ? value : null;
3878
- },
3879
- "delivery-deferred": parseDeliveryOutcome,
3880
- status: requireEventIdentity("any", (value) => {
3881
- return (value.status === "idle" || value.status === "running" || value.status === "failed") && (value.turnId === void 0 || isNonEmptyString(value.turnId)) ? value : null;
3882
- }),
3883
- "message-upsert": requireEventIdentity(
3884
- "any",
3885
- (value) => {
3886
- return isSequence(value.index) && isRecord(value.message) && hasValidProjectedMetadata(value.message) ? value : null;
3887
- }
3888
- ),
3889
- "turn-completed": requireEventIdentity(
3890
- "any",
3891
- (value) => {
3892
- return isNonEmptyString(value.turnId) && (value.digest === void 0 || parseTurnDigest(value.digest)) && (value.report === void 0 || parseTurnReport(value.report)) && (value.aborted === void 0 || value.aborted === true) && (value.silent === void 0 || value.silent === true) && (value.requestBudgetStop === void 0 || value.requestBudgetStop === true) && (value.requestBudgetError === void 0 || value.requestBudgetStop === true && isNonEmptyString(value.requestBudgetError)) && (value.continues === void 0 || isNonEmptyString(value.continues)) && (value.awaitingTasks === void 0 || value.awaitingTasks === true) ? value : null;
3893
- }
3894
- ),
3895
- "turn-failed": requireEventIdentity(
3896
- "any",
3897
- (value) => {
3898
- return isNonEmptyString(value.turnId) && isNonEmptyString(value.error) && (value.retryExhausted === void 0 || value.retryExhausted === true) && (value.aborted === void 0 || value.aborted === true) && (value.continues === void 0 || isNonEmptyString(value.continues)) ? value : null;
3899
- }
3900
- ),
3901
- "turn-retry": requireEventIdentity(
3902
- "any",
3903
- (value) => {
3904
- return Number.isInteger(value.attempt) && value.attempt >= 1 && Number.isInteger(value.maxAttempts) && value.maxAttempts >= 0 && isSequence(value.delayMs) && isNonEmptyString(value.error) ? value : null;
3905
- }
3906
- ),
3907
- "retry-skipped": requireEventIdentity(
3908
- "any",
3909
- (value) => {
3910
- return hasExactKeys(value, ["type", "identity", "seq", "reason"]) && RETRY_SKIPPED_REASONS.includes(value.reason) ? value : null;
3911
- }
3912
- ),
3913
- "messages-truncated": requireEventIdentity(
3914
- "any",
3915
- (value) => {
3916
- return isSequence(value.length) ? value : null;
3917
- }
3918
- ),
3919
- "rewind-done": requireEventIdentity(
3920
- "any",
3921
- (value) => {
3922
- const editorImages = value.editorImages === void 0 ? void 0 : parseAttachedImages(value.editorImages);
3923
- return (value.editorText === void 0 || typeof value.editorText === "string") && editorImages !== null && (value.filesRestored === void 0 || typeof value.filesRestored === "boolean") ? value : null;
3924
- }
3925
- ),
3926
- "fork-done": requireEventIdentity(
3927
- "any",
3928
- (value) => {
3929
- return isUuid(value.targetConversationId) && (value.sessionFile === void 0 || typeof value.sessionFile === "string") && (value.entryId === void 0 || isNonEmptyString(value.entryId)) && (value.error === void 0 || typeof value.error === "string") ? value : null;
3930
- }
3931
- ),
3932
- compaction: requireEventIdentity(
3933
- "any",
3934
- (value) => {
3935
- return (value.state === "queued" || value.state === "start" || value.state === "end") && (value.error === void 0 || typeof value.error === "string") && (value.abandoned === void 0 || value.abandoned === true) ? value : null;
3936
- }
3937
- ),
3938
- commands: requireEventIdentity(
3939
- "any",
3940
- (value) => {
3941
- return Array.isArray(value.commands) ? value : null;
3942
- }
3943
- ),
3944
- "session-meta": requireEventIdentity(
3945
- "any",
3946
- (value) => {
3947
- const occupancy = value.occupancy === void 0 ? void 0 : parseContextOccupancy(value.occupancy);
3948
- if (value.occupancy !== void 0 && !occupancy) return null;
3949
- const { usageTotals: rawTotals, ...rest } = value;
3950
- const usageTotals = parseSessionUsageTotals(rawTotals);
3951
- return (value.sessionFile === void 0 || typeof value.sessionFile === "string") && (value.contextWindow === void 0 || typeof value.contextWindow === "number" && value.contextWindow > 0) ? {
3952
- ...rest,
3953
- ...occupancy ? { occupancy } : {},
3954
- ...usageTotals ? { usageTotals } : {}
3955
- } : null;
3956
- }
3957
- ),
3958
- "approval-request": requireEventIdentity(
3959
- "any",
3960
- (value) => {
3961
- return isRecord(value.request) && isNonEmptyString(value.request.requestId) && isNonEmptyString(value.request.tool) && (value.request.kind === "command" || value.request.kind === "file-edit" || value.request.kind === "file-write" || value.request.kind === "mcp") && typeof value.request.summary === "string" && (value.request.filePaths === void 0 || Array.isArray(value.request.filePaths) && value.request.filePaths.every(isNonEmptyString)) && (value.request.protected === void 0 || PROTECTED_ACTION_CATEGORIES.includes(value.request.protected)) && isOptionalTimestamp(value.request.expiresAt) && (value.request.reviewFallback === void 0 || APPROVAL_REVIEW_FALLBACKS.includes(value.request.reviewFallback)) && (value.request.guard === void 0 || isRecord(value.request.guard) && hasOnlyKeys(value.request.guard, ["ruleId", "reason"]) && isNonEmptyString(value.request.guard.ruleId) && isNonEmptyString(value.request.guard.reason)) ? value : null;
3962
- }
3963
- ),
3964
- "approval-resolved": requireEventIdentity(
3965
- "any",
3966
- (value) => {
3967
- return isNonEmptyString(value.requestId) ? value : null;
3968
- }
3969
- ),
3970
- "ask-resolved": requireEventIdentity(
3971
- "any",
3972
- (value) => {
3973
- return isNonEmptyString(value.requestId) && (value.by === void 0 || ASK_ANSWER_BY.includes(value.by)) && (value.answer === void 0 || typeof value.answer === "string") && (value.name === void 0 || isNonEmptyString(value.name)) ? value : null;
3974
- }
3975
- ),
3976
- "ask-request": requireEventIdentity(
3977
- "any",
3978
- (value) => {
3979
- return isRecord(value.ask) && isNonEmptyString(value.ask.requestId) && isNonEmptyString(value.ask.question) && isOptionalTimestamp(value.ask.expiresAt) && (value.ask.recommended === void 0 || Array.isArray(value.ask.options) && value.ask.options.includes(value.ask.recommended)) && (value.ask.relay === void 0 || isRecord(value.ask.relay) && isNonEmptyString(value.ask.relay.name)) ? value : null;
3980
- }
3981
- ),
3982
- "subagent-update": requireEventIdentity(
3983
- "any",
3984
- (value) => {
3985
- return isRecord(value.agent) ? value : null;
3986
- }
3987
- ),
3988
- "coworker-update": requireEventIdentity(
3989
- "any",
3990
- (value) => {
3991
- return isRecord(value.coworker) && isNonEmptyString(value.coworker.id) ? value : null;
3992
- }
3993
- ),
3994
- "goal-signal": requireEventIdentity(
3995
- "any",
3996
- (value) => {
3997
- return (value.kind === "complete" || value.kind === "blocked" || value.kind === "wait") && typeof value.note === "string" ? value : null;
3998
- }
3999
- ),
4000
- "plan-state": requireEventIdentity(
4001
- "any",
4002
- (value) => {
4003
- const state = parsePlanState(value.state);
4004
- return hasExactKeys(value, ["type", "identity", "seq", "state"]) && state ? { ...value, state } : null;
4005
- }
4006
- ),
4007
- "workflow-status": requireEventIdentity(
4008
- "any",
4009
- (value) => {
4010
- const run = parseWorkflowRunSnapshot(value.run);
4011
- return hasExactKeys(value, ["type", "identity", "seq", "run"]) && run ? { ...value, run } : null;
4012
- }
4013
- ),
4014
- "tool-output": requireEventIdentity(
4015
- "any",
4016
- (value) => {
4017
- return isNonEmptyString(value.toolCallId) && typeof value.output === "string" && (value.startedAt === void 0 || typeof value.startedAt === "number") && (value.deadlineAt === void 0 || Number.isFinite(value.deadlineAt)) ? value : null;
4018
- }
4019
- ),
4020
- "task-started": requireEventIdentity(
4021
- "any",
4022
- (value) => {
4023
- return isRecord(value.task) ? value : null;
4024
- }
4025
- ),
4026
- "task-output": parseTaskEvent,
4027
- "task-ended": parseTaskEvent,
4028
- "background-tasks-level": requireEventIdentity(
4029
- "any",
4030
- (value) => {
4031
- return Array.isArray(value.tasks) && value.tasks.every((task) => isRecord(task) && isNonEmptyString(task.taskId)) ? value : null;
4032
- }
4033
- ),
4034
- "session-custom-entry": requireEventIdentity(
4035
- "any",
4036
- (value) => {
4037
- return parseAgentSessionCustomEntry(value.entry) ? value : null;
4038
- }
4039
- )
4040
- };
4041
- function parseAgentWorkerEvent(value) {
4042
- if (!isRecord(value) || !isNonEmptyString(value.type)) return null;
4043
- return parseClosed(agentWorkerEventParsers, value.type, value);
4044
- }
4045
- export {
4046
- isClassifierOnlyProvider as $,
4047
- AGENT_END_TEXT_MAX as A,
4048
- BEFORE_AGENT_START_PROMPT_MAX as B,
4049
- CONTEXT_OCCUPANCY_BUCKETS as C,
4050
- SILENCE_TURN_TOOL as D,
4051
- workspaceBranchChangedNote as E,
4052
- DEFAULT_MAX_ACTIVE_COWORKERS as F,
4053
- DEFAULT_AUTO_RETRY_LIMIT as G,
4054
- isSameChildSessionIdentity as H,
4055
- resolveCompactStrategy as I,
4056
- DEFAULT_SSH_TIMEOUT_SECONDS as J,
4057
- isSecretaryToolAllowed as K,
4058
- PLAN_ENTRY_TYPE as L,
4059
- MODEL_API_KINDS as M,
4060
- autoRetryOverrides as N,
4061
- parseAgentSessionCustomEntry as O,
4062
- PLUGIN_MESSAGE_TYPE as P,
4063
- PLUGIN_AGENT_ARGS_MAX_CHARS as Q,
4064
- PLUGIN_AGENT_TEXT_MAX_CHARS as R,
4065
- SECRETARY_OPS as S,
4066
- THINKING_LEVELS as T,
4067
- toolBatchDigest as U,
4068
- turnRequestedSilence as V,
4069
- turnCalledSilenceTurn as W,
4070
- STALE_SESSION_ERROR as X,
4071
- WORKSPACE_WRITE_TOOL_ID as Y,
4072
- parsePlanMessage as Z,
4073
- PLUGIN_AGENT_OUTPUT_MAX_CHARS as _,
4074
- parseSessionIdentity as a,
4075
- BOT_AVATAR_HOST as a$,
4076
- isOauthAccountPool as a0,
4077
- resolveEditMode as a1,
4078
- EMPTY_PLAN_STATE as a2,
4079
- mergeMaskReports as a3,
4080
- PRIVACY_MASK_ENTRY as a4,
4081
- parseAgentCommand as a5,
4082
- effectiveDisabledBuiltinTools as a6,
4083
- pluginToolName as a7,
4084
- APPROVAL_MODES as a8,
4085
- parseChildConversationMetadata as a9,
4086
- PLUGIN_PROGRESS_MAX_CHARS as aA,
4087
- MCP_TRANSPORTS as aB,
4088
- persistedSettingsState as aC,
4089
- parsePrivacyMaskRecord as aD,
4090
- hasProviderCredentials as aE,
4091
- parseAgentWorkerEvent as aF,
4092
- SECRETARY_FORCED_DISABLED_TOOLS as aG,
4093
- parseWindowsLocalShell as aH,
4094
- parseSmartCompactMode as aI,
4095
- SECRETARY_ALWAYS_ENABLED_TOOLS as aJ,
4096
- resolveImageGenerationConfig as aK,
4097
- normalizeMaxActiveCoworkers as aL,
4098
- normalizeAutoRetryLimit as aM,
4099
- parsePrivacyMaskSettings as aN,
4100
- parseDisabledWorkflowPresets as aO,
4101
- DEFAULT_APPROVAL_ALLOW_THRESHOLD as aP,
4102
- visibleMemberAgentTypes as aQ,
4103
- buildAgentTypeRegistrySnapshot as aR,
4104
- resolveShellLimits as aS,
4105
- parseWebSearchChain as aT,
4106
- DEFAULT_PRESET_ID as aU,
4107
- childProfileToolIds as aV,
4108
- AGENT_TASK_MAX_RESUMES as aW,
4109
- AGENT_WAIT_DEFAULT_MS as aX,
4110
- AGENT_WAIT_MAX_MS as aY,
4111
- LOCAL_IMAGE_SCHEME as aZ,
4112
- REMOTE_FETCH_HOST as a_,
4113
- eligibleOauthPoolAccountKeys as aa,
4114
- normalizeSshTimeoutSeconds as ab,
4115
- isEditMode as ac,
4116
- resolveDisabledBuiltinTools as ad,
4117
- projectDisabledBuiltinTools as ae,
4118
- isReservedAgentTypeName as af,
4119
- BUILTIN_AGENT_TYPES as ag,
4120
- PLUGIN_HOST_APIS as ah,
4121
- PLUGIN_INJECT_MAX_CHARS as ai,
4122
- PLUGIN_AGENT_RUN_ID as aj,
4123
- PLUGIN_AGENT_PROMPT_MAX_CHARS as ak,
4124
- PLUGIN_AGENT_SYSTEM_MAX_CHARS as al,
4125
- PLUGIN_AGENT_DEFAULT_TIMEOUT_MS as am,
4126
- PLUGIN_AGENT_MAX_TIMEOUT_MS as an,
4127
- parsePluginInjectImages as ao,
4128
- isHostPluginEvent as ap,
4129
- parsePluginToolName as aq,
4130
- initialInterceptState as ar,
4131
- CHILD_INTERCEPT_TOTAL_TIMEOUT_MS as as,
4132
- INTERCEPT_TOTAL_TIMEOUT_MS as at,
4133
- CHILD_INTERCEPT_TIMEOUT_MS as au,
4134
- INTERCEPT_TIMEOUT_MS as av,
4135
- applyInterceptResult as aw,
4136
- failClosedResult as ax,
4137
- OBSERVE_TIMEOUT_MS as ay,
4138
- BEFORE_COMPACT_TIMEOUT_MS as az,
4139
- parseApprovalAllowThreshold as b,
4140
- planFeedbackText as b$,
4141
- SECRETARY_AVATAR_HOST as b0,
4142
- PLUGIN_ASSET_HOST as b1,
4143
- SECRETARY_REPORT_HOST as b2,
4144
- mediaExtension as b3,
4145
- localImageUrlToPath as b4,
4146
- isMediaPath as b5,
4147
- isVideoPath as b6,
4148
- IMAGE_EXTENSIONS as b7,
4149
- isDeliveryId as b8,
4150
- splitPlanPrefix as b9,
4151
- SHELL_LIMITS as bA,
4152
- TITLE_SUMMARY_MAX_CANDIDATES as bB,
4153
- parseCreateProjectAuthorityRequest as bC,
4154
- parseSelectProjectAuthorityRequest as bD,
4155
- parseRemoveProjectAuthorityRequest as bE,
4156
- withVersionSegment as bF,
4157
- DEFAULT_BASE_URLS as bG,
4158
- shouldSilenceTurn as bH,
4159
- sessionIdsInUpdates as bI,
4160
- messageText as bJ,
4161
- isPureSessionUpdate as bK,
4162
- PROJECTED_FILE_TEXT_LIMIT as bL,
4163
- imageGenerationPreviewPaths as bM,
4164
- parseGeneratedImagePaths as bN,
4165
- parseMaskReport as bO,
4166
- parsePluginMessageSource as bP,
4167
- parseRtkToolStats as bQ,
4168
- isBackgroundTaskId as bR,
4169
- parseShellFailure as bS,
4170
- pluginArtifactsFromToolDetails as bT,
4171
- parseApprovalReviewRecord as bU,
4172
- PROJECTED_FILE_CHANGE_LIMIT as bV,
4173
- PROJECTED_APPLY_PATCH_PATH_TEXT_LIMIT as bW,
4174
- PROJECTED_APPLY_PATCH_PATH_COUNT_LIMIT as bX,
4175
- foldPlanState as bY,
4176
- PLAN_MODE_ON_NOTE as bZ,
4177
- PLAN_MODE_OFF_NOTE as b_,
4178
- parseSecretarySkillDraft as ba,
4179
- parseSecretaryToolDraft as bb,
4180
- TURN_REPORT_MAX_CHARS as bc,
4181
- isSecretarySlug as bd,
4182
- secretaryToolScriptFile as be,
4183
- parseSecretaryToolFile as bf,
4184
- renderSecretaryToolFile as bg,
4185
- secretaryToolDescriptor as bh,
4186
- TOOL_TIMEOUT_DEFAULT as bi,
4187
- TOOL_OUTPUT_MAX as bj,
4188
- isSecretarySkillName as bk,
4189
- parseSecretarySkillFile as bl,
4190
- renderSecretarySkillFile as bm,
4191
- effectiveSubagentAllowedModes as bn,
4192
- parseCreateConversationAuthorityRequest as bo,
4193
- parseConversationAuthorityRequest as bp,
4194
- parseUpdateConversationSelectionRequest as bq,
4195
- parseTitleSummaryInput as br,
4196
- parseParentSourceBindingRequest as bs,
4197
- parseParentModelSelectionRequest as bt,
4198
- parseAgentDispatchRequest as bu,
4199
- isApprovalDecision as bv,
4200
- TASK_KEEP_REASON_MAX as bw,
4201
- cleanToolBatchLabel as bx,
4202
- toolBatchLabelPrompt as by,
4203
- TOOL_BATCH_LABEL_SYSTEM_PROMPT as bz,
4204
- isProbability as c,
4205
- planKickoffText as c0,
4206
- activePlanNote as c1,
4207
- PLAN_TITLE_MAX as c2,
4208
- PLAN_TEXT_MAX as c3,
4209
- planPhase as c4,
4210
- parsePlanEntry as c5,
4211
- parseAgentControlToolRequest as c6,
4212
- nativeSearchKindFor as c7,
4213
- isWorkflowPresetId as c8,
4214
- PLUGIN_EVENTS as c9,
4215
- isInterceptEvent as ca,
4216
- APPEND_ONLY_INTERCEPT_EVENTS as cb,
4217
- CONTEXT_PART_ITEMS as d,
4218
- parseProviderHeaders as e,
4219
- escapePiConfigValue as f,
4220
- MODEL_REASONING_OVERRIDES as g,
4221
- MODEL_THINKING_LEVEL_OVERRIDES as h,
4222
- isApprovalReviewReason as i,
4223
- isCodexAccountKey as j,
4224
- classifyCodexPoolFailure as k,
4225
- isUuid as l,
4226
- isChildInterceptEvent as m,
4227
- CONTEXT_USAGE_BUCKETS as n,
4228
- BEFORE_AGENT_START_APPEND_MAX as o,
4229
- parseChildSessionIdentity as p,
4230
- MaskReportBuilder as q,
4231
- resolvePiProviderBaseUrl as r,
4232
- childProfileShell as s,
4233
- SECRETARY_ID_MAX as t,
4234
- SECRETARY_CONTACT_CAPTION_MAX as u,
4235
- SECRETARY_ATTACHMENT_PATH_MAX as v,
4236
- SECRETARY_SEND_MODES as w,
4237
- SECRETARY_SESSION_MESSAGE_MAX as x,
4238
- SECRETARY_ATTACHMENT_MAX as y,
4239
- TOOL_RUN_TIMEOUT_MS as z
4240
- };
4241
- //# sourceMappingURL=agent-BbNq8i9j.js.map