nolo-cli 0.226.0-alpha.1 → 0.226.0

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 (259) hide show
  1. package/README.md +3 -5
  2. package/{_executeModel-UE2NJPZD.js → _executeModel-IZ2MCXHO.js} +89 -83
  3. package/{action-CK64LS6S.js → action-VDEW6WLI.js} +9 -6
  4. package/{addContentAction-EQXMFNPR.js → addContentAction-7YVXHIPQ.js} +15 -14
  5. package/{addDialogAgentAction-RSDZDASD.js → addDialogAgentAction-BX7B47HF.js} +18 -17
  6. package/{agentDeleteCommand-SOI25WK7.js → agentDeleteCommand-N7ELXPLD.js} +145 -138
  7. package/{agentEmailCommands-UGWQQNKM.js → agentEmailCommands-OFS477PV.js} +144 -133
  8. package/{agentFavoriteCommands-2LKGKSUD.js → agentFavoriteCommands-7LOP3HUD.js} +5 -5
  9. package/{agentGrantCommands-QQV4N4JW.js → agentGrantCommands-L6O2HVJI.js} +5 -5
  10. package/agentListCommands-IQQHJSXP.js +644 -0
  11. package/{agentMachineCommands-M6IKO7XE.js → agentMachineCommands-NS65BEW7.js} +75 -66
  12. package/{agentProviderCommands-7BSJH7TO.js → agentProviderCommands-SS6M6VGY.js} +6 -6
  13. package/{agentPullCommand-XN6ZPBUW.js → agentPullCommand-QQQZSC6S.js} +6 -6
  14. package/agentRecordCommands-4VE7CNLC.js +188 -0
  15. package/agentRunCommand-2MUXHKNW.js +223 -0
  16. package/{agentRunControl-DFEEOFC7.js → agentRunControl-55GL6Q3M.js} +23 -15
  17. package/{agentRuntimeLocal-GSTYFEX4.js → agentRuntimeLocal-5DB2P4MU.js} +63 -49
  18. package/{agentSlice-7PTNWEED.js → agentSlice-5VTAFG43.js} +19 -18
  19. package/{appDeleteCommands-L7HL4AWF.js → appDeleteCommands-EDKUPHJM.js} +67 -58
  20. package/{appDeployCommands-SGSUNFZR.js → appDeployCommands-JO74GW4L.js} +67 -58
  21. package/{appDeployStatusCommands-AAA3XD54.js → appDeployStatusCommands-U77ZUHX7.js} +67 -58
  22. package/{appGetCommands-LN72GAOA.js → appGetCommands-QCMHBYPX.js} +67 -58
  23. package/{appListCommands-IJQQ3VND.js → appListCommands-ZQJYEXI6.js} +67 -58
  24. package/{authCommand-7JXW54U4.js → authCommand-W4KXRZLI.js} +33 -28
  25. package/{authCommands-YDNAIDEY.js → authCommands-6AUYO65N.js} +15 -10
  26. package/{builtinSkillRegistry-PXH7EGQB.js → builtinSkillRegistry-GHE3RD3V.js} +8 -8
  27. package/{chromeCommands-G5UDKVSV.js → chromeCommands-S7AW3AOD.js} +383 -6
  28. package/{chromeOpsCommands-YKX2QX3A.js → chromeOpsCommands-TBPM6MR4.js} +6 -6
  29. package/{chunk-7Z6EW7AH.js → chunk-247AAJRK.js} +13 -6
  30. package/{chunk-P2ZLUIW2.js → chunk-2BSLGODA.js} +350 -25
  31. package/{chunk-4HFTBHBF.js → chunk-2N4UBHUU.js} +8 -8
  32. package/chunk-2SXN7LAY.js +15 -0
  33. package/{chunk-GSAS72AN.js → chunk-2T5BHLID.js} +2871 -1565
  34. package/{chunk-XI2BWJM5.js → chunk-324FWHUA.js} +20 -3
  35. package/{chunk-VFBVA3U2.js → chunk-3OQFXODL.js} +131 -40
  36. package/{chunk-BGGHA5DV.js → chunk-3ORFJP2Z.js} +1 -1
  37. package/{chunk-OWH2BLNU.js → chunk-3UNAGTBW.js} +32 -95
  38. package/{chunk-LM2PS3YS.js → chunk-4F7SWSWO.js} +26 -13
  39. package/{chunk-SBVTHMEG.js → chunk-4FE3IWRE.js} +1 -1
  40. package/{chunk-GOAPXKQU.js → chunk-4UK6UBXF.js} +4 -4
  41. package/{chunk-4JVNURX4.js → chunk-4YFC3DWW.js} +68 -16
  42. package/chunk-4ZCTKB27.js +31 -0
  43. package/chunk-53W5BXLN.js +340 -0
  44. package/{chunk-TD6QCQ5G.js → chunk-5GRWWUB4.js} +4 -4
  45. package/{chunk-JWXITTQB.js → chunk-5HUO7SEX.js} +9 -107
  46. package/{chunk-ZH6MUQEO.js → chunk-6326DRQY.js} +1 -1
  47. package/{chunk-AVHRSJUH.js → chunk-6MQWGA5F.js} +31 -24
  48. package/{chunk-67BE44IS.js → chunk-6MX6S6TE.js} +3 -3
  49. package/chunk-6RSNVJGO.js +279 -0
  50. package/{chunk-BRW24CTE.js → chunk-6S6CZUXK.js} +42 -33
  51. package/{chunk-PDCV7P5W.js → chunk-6XIE5ZGI.js} +1 -1
  52. package/{chunk-CVS5IMJ5.js → chunk-6XLWUNZB.js} +25 -25
  53. package/{chunk-YGMBIXCF.js → chunk-6XRPBZRS.js} +4 -2
  54. package/{chunk-62HXNQVV.js → chunk-776CXKMX.js} +1 -1
  55. package/{chunk-6J4TTPS2.js → chunk-7AWKDRXG.js} +5 -5
  56. package/{chunk-3KNEE64G.js → chunk-7GTXPS3D.js} +16 -16
  57. package/{chunk-FS3RA7D2.js → chunk-7HUHOCIY.js} +147 -162
  58. package/{chunk-PWTNI4N7.js → chunk-ANUP75N2.js} +22 -0
  59. package/chunk-BEM6LPD2.js +734 -0
  60. package/{chunk-AGP3YSEC.js → chunk-BH7CEVOH.js} +46 -1
  61. package/chunk-BIDSIRTS.js +307 -0
  62. package/{chunk-VTW7VKZX.js → chunk-C4KX626C.js} +15 -15
  63. package/chunk-C5A54QS7.js +108 -0
  64. package/{chunk-4PMZVBDU.js → chunk-CHYYSFFM.js} +6 -6
  65. package/{chunk-VREDDN25.js → chunk-CJTB3OYB.js} +14 -9
  66. package/{chunk-YFLVRVYK.js → chunk-DLT2DN4M.js} +1 -1
  67. package/{chunk-LKA64WH4.js → chunk-DMPZMYH4.js} +37 -1
  68. package/{chunk-EOWLBDY6.js → chunk-DOK7GDRU.js} +1 -1
  69. package/{chunk-5NC6A2RZ.js → chunk-DPAIQLAL.js} +105 -102
  70. package/{chunk-KFHREHUQ.js → chunk-DXWGFL2Z.js} +89 -1
  71. package/{chunk-XN23AUVU.js → chunk-EKXPHL7M.js} +8 -5
  72. package/{chunk-DISQCYPE.js → chunk-ENYTIRIO.js} +6 -6
  73. package/{chunk-2TIQO6TC.js → chunk-ER3P6MBT.js} +206 -308
  74. package/{chunk-M3JEW6N6.js → chunk-F26GAEH3.js} +10 -0
  75. package/{chunk-JM5C4EUA.js → chunk-F4MCAOWN.js} +6 -6
  76. package/chunk-FDZ2GBWO.js +166 -0
  77. package/{chunk-PMDVQBGA.js → chunk-GAHJLSDO.js} +14 -7
  78. package/{chunk-N5PQJKCY.js → chunk-GES5GIAU.js} +14 -13
  79. package/{chunk-HYHIAM6T.js → chunk-HQVNO7FH.js} +66 -35
  80. package/chunk-HSWEFHFS.js +103 -0
  81. package/{chunk-S2NTVGA2.js → chunk-I2OYPD3Y.js} +1 -1
  82. package/{chunk-F7DU25CE.js → chunk-IIG3TT73.js} +460 -123
  83. package/{chunk-AK5O76CC.js → chunk-IZJFTY4R.js} +3 -3
  84. package/{chunk-2VA6TU4I.js → chunk-J25ESVUW.js} +22 -19
  85. package/{chunk-TUIWP2LF.js → chunk-J2XZZXIH.js} +4 -4
  86. package/{chunk-JVRQ6YVK.js → chunk-JBWXPACD.js} +1 -1
  87. package/{chunk-D726I5AZ.js → chunk-JVJ53XCH.js} +2 -2
  88. package/{chunk-TXGQ4O5S.js → chunk-KC2QVCI7.js} +20 -174
  89. package/{chunk-UKS7D2NL.js → chunk-KF2DWSAH.js} +113 -28
  90. package/chunk-KK3FCYZM.js +647 -0
  91. package/{chunk-ZZ4M2I3R.js → chunk-KLD7K5FD.js} +349 -16
  92. package/{chunk-JIADJPUV.js → chunk-KMW5CRRM.js} +1564 -2955
  93. package/{chunk-N5Z2V73W.js → chunk-LELADM5Q.js} +1 -1
  94. package/{chunk-4NA3YTBC.js → chunk-LMFMV5UC.js} +8 -8
  95. package/{chunk-KZU52OJ5.js → chunk-LZOOUQAZ.js} +6 -6
  96. package/{chunk-VV7TXWOC.js → chunk-M5EA44QU.js} +6 -6
  97. package/{chunk-UYOICCYG.js → chunk-MEDPR36J.js} +64 -89
  98. package/chunk-MFXJY44K.js +133 -0
  99. package/chunk-MVOZ22RZ.js +26 -0
  100. package/{chunk-3QFLXA24.js → chunk-N6EN3HK3.js} +3 -3
  101. package/{chunk-SOF4OWDM.js → chunk-NEG5LYK5.js} +1 -3
  102. package/{chunk-HJAO2NAL.js → chunk-ODGSLWLO.js} +593 -370
  103. package/{chunk-OB6DVWPF.js → chunk-OGZE6BZG.js} +331 -99
  104. package/{chunk-KYH7XW3K.js → chunk-OJRTTERA.js} +77 -2
  105. package/{chunk-2VUZSVAS.js → chunk-OKPC4QNX.js} +57 -20
  106. package/{chunk-SOG7OEXX.js → chunk-ONFFUQYM.js} +1 -1
  107. package/{chunk-KNIIRXHF.js → chunk-P244EH4W.js} +46 -8
  108. package/chunk-P27E22MA.js +203 -0
  109. package/{chunk-YDBMZ7FV.js → chunk-PK7VT4ZU.js} +3 -3
  110. package/{chunk-EUCFKKDM.js → chunk-PVFYPUIM.js} +40 -10
  111. package/{chunk-HOCHUZQ7.js → chunk-QJTZ76CP.js} +24 -6
  112. package/{chunk-5RKUPJYL.js → chunk-QLUYDJST.js} +11 -3
  113. package/{chunk-EVPIBQ5I.js → chunk-QUJKDFZW.js} +17 -17
  114. package/{chunk-C4VAR65S.js → chunk-QXUVCIPB.js} +204 -124
  115. package/{chunk-X4OVEYPX.js → chunk-QYNABNNQ.js} +13 -13
  116. package/{chunk-MK2Q7ZJD.js → chunk-R7XWZDOH.js} +58 -24
  117. package/{chunk-5FUN7EG4.js → chunk-RD3QLZQV.js} +83 -47
  118. package/{chunk-KC4SCKXO.js → chunk-RGUWOMXU.js} +1234 -1451
  119. package/{chunk-IZIN2UNJ.js → chunk-RH44TIHX.js} +206 -27
  120. package/{chunk-GNHMRBYZ.js → chunk-RIMFTQMC.js} +282 -58
  121. package/{chunk-VQUWV3YR.js → chunk-S25VJYXV.js} +9 -3
  122. package/{chunk-X7YC2OHB.js → chunk-SBRJOYND.js} +723 -355
  123. package/{chunk-UEKXWO7A.js → chunk-SBRSXY67.js} +18 -7
  124. package/chunk-SR4FE5VD.js +9 -0
  125. package/{chunk-4WVJLODK.js → chunk-T23G6PXQ.js} +8 -3
  126. package/chunk-T3WSFTBS.js +62 -0
  127. package/{chunk-KEN3N2TN.js → chunk-TB5KTLNB.js} +15 -12
  128. package/{chunk-VP3BINY7.js → chunk-TOK555CQ.js} +31 -1
  129. package/{chunk-OBSEKCVK.js → chunk-U4VSBDO5.js} +88 -0
  130. package/{chunk-PPJYZRSQ.js → chunk-U5LOKQ2R.js} +30 -14
  131. package/{chunk-GGKNJ42M.js → chunk-UDT4SI37.js} +18 -108
  132. package/{chunk-CKT6QUE2.js → chunk-UHW6SCVK.js} +1 -1
  133. package/{chunk-GVGOEMNV.js → chunk-UQXOORR3.js} +5 -5
  134. package/{chunk-GS4OTYCH.js → chunk-UR7555FE.js} +9 -9
  135. package/{chunk-QLFCTYRH.js → chunk-UWOCASVL.js} +20 -13
  136. package/{chunk-C4WTX5TU.js → chunk-V2V5Q6DU.js} +2 -2
  137. package/{chunk-2ZKFCIJJ.js → chunk-VCU5GV42.js} +1 -1
  138. package/{chunk-FTQWYWUI.js → chunk-VMWY7TUA.js} +1 -1
  139. package/chunk-VNALJT32.js +33394 -0
  140. package/{chunk-HGDKT2D6.js → chunk-VTHWBTRE.js} +177 -1
  141. package/chunk-WBSJAIZP.js +170 -0
  142. package/chunk-WDWZPASX.js +29 -0
  143. package/chunk-WFGNWWJI.js +326 -0
  144. package/{chunk-UJKTI5PG.js → chunk-WRKMXMU7.js} +2 -1
  145. package/chunk-WVOZ35E4.js +1438 -0
  146. package/{chunk-FIYSMXHY.js → chunk-WWTSEBDF.js} +1 -1
  147. package/{chunk-E2BESSAW.js → chunk-X4O7FJF5.js} +2 -0
  148. package/{chunk-GIABSSWQ.js → chunk-XDNXKFWF.js} +6 -6
  149. package/{chunk-GBZ4YKEO.js → chunk-XLN2GD6Z.js} +7 -7
  150. package/{chunk-45LZIYXB.js → chunk-XNEDFWT4.js} +2 -2
  151. package/{chunk-EWPDMS4N.js → chunk-Y22P6ASC.js} +32 -17
  152. package/{chunk-LJSNEV7M.js → chunk-Y3DOUQQQ.js} +8 -8
  153. package/{chunk-KOXKKHFE.js → chunk-Y5EBOURK.js} +10 -5
  154. package/{chunk-L5I543VB.js → chunk-YGDYYFRX.js} +20 -24
  155. package/{chunk-6OVNSQHN.js → chunk-YLAHYLDQ.js} +5 -0
  156. package/{chunk-PVZY6P3S.js → chunk-YTEY27GN.js} +2 -2
  157. package/chunk-YUZ2DAIH.js +34 -0
  158. package/chunk-Z6YTCDU4.js +24 -0
  159. package/{chunk-MOMR7NMG.js → chunk-ZCVBIIUE.js} +4 -4
  160. package/{chunk-AZQZ5XPM.js → chunk-ZCZLTJEW.js} +98 -57
  161. package/{chunk-KN3HEZIQ.js → chunk-ZVOL2MAJ.js} +1 -1
  162. package/{cliAgentConfigHelpers-KICKKNYQ.js → cliAgentConfigHelpers-6OFDHJFT.js} +13 -13
  163. package/{cliAuthorityBrokerClient-XHH7MH2P.js → cliAuthorityBrokerClient-SFPC3WVK.js} +1 -1
  164. package/{cliEnvHelpers-VPSJ4XWC.js → cliEnvHelpers-CNMP3RDX.js} +1 -1
  165. package/{cliExecutor-4MAX3PZL.js → cliExecutor-K6FDZTQ2.js} +3 -1
  166. package/cliLocalAgentRecordReader-FHIMCBUK.js +102 -0
  167. package/{commandRegistry-XSMTI5PG.js → commandRegistry-OKIWAJIS.js} +113 -101
  168. package/{contentThunks-S4NNC7R2.js → contentThunks-VF2DCU46.js} +41 -38
  169. package/{cooldownCommands-X7P5M2V5.js → cooldownCommands-QL6DWGVU.js} +4 -4
  170. package/{createAgentAutomationAction-TH7ZEACJ.js → createAgentAutomationAction-BGET7Q6K.js} +41 -38
  171. package/{createDialogAction-SYZAYIIQ.js → createDialogAction-XYDQZETK.js} +42 -40
  172. package/{createPageAction-7Y4U6TXO.js → createPageAction-74S5RO7U.js} +46 -43
  173. package/{db-CS4ZJQKV.js → db-6NRZLEW2.js} +10 -7
  174. package/{dbSlice-ZJPDIFER.js → dbSlice-FI7VNDR5.js} +14 -13
  175. package/{deleteFile-Q3YDB4ML.js → deleteFile-GD62MPZW.js} +10 -7
  176. package/{dialogCommands-V5IYEOQP.js → dialogCommands-Y6DHZUAM.js} +71 -64
  177. package/dialogMessageRecord-OAV77LT7.js +7 -0
  178. package/{dialogNotifyCommand-77B57PL6.js → dialogNotifyCommand-MKXL4NGL.js} +15 -15
  179. package/{dialogSlice-O3RHDAWK.js → dialogSlice-XAUKSWZ4.js} +41 -38
  180. package/{dialogUsageCommand-HTVPR2CX.js → dialogUsageCommand-BZPKR3DW.js} +6 -6
  181. package/{docCreateCommands-36WS33BK.js → docCreateCommands-PHDFOQBM.js} +66 -57
  182. package/{docDeleteCommands-C4CS4XLF.js → docDeleteCommands-OSHJM67Y.js} +69 -60
  183. package/{docReadCommands-QZMSFMPN.js → docReadCommands-E6QYCFMS.js} +66 -57
  184. package/{docStore-PYNEODAH.js → docStore-ZZT2BEBU.js} +16 -15
  185. package/{docUpdateCommands-BYI64HVV.js → docUpdateCommands-DHIOPK2C.js} +66 -57
  186. package/fetchMessages-TQEUZD7H.js +2 -2
  187. package/{getPricing-VNGFM4PN.js → getPricing-RNRITFOP.js} +6 -6
  188. package/{handleSendMessageAction-Z43FP2E2.js → handleSendMessageAction-ARUU6CNF.js} +83 -78
  189. package/{hostCredentialCreate-Y7YIGKP4.js → hostCredentialCreate-SNQT73H4.js} +131 -119
  190. package/index.js +56 -18
  191. package/keys-RWF7UCB4.js +1 -1
  192. package/{lib-OT5OTXRU.js → lib-62SWPXNF.js} +3 -7
  193. package/{localDialogRead-SVTPA5GY.js → localDialogRead-3T2KMCRC.js} +1 -1
  194. package/{localRuntimeAdapter-ZLJONQZS.js → localRuntimeAdapter-MHI6Y2IZ.js} +143 -130
  195. package/{localRuntimeAuthority-IBJAT62G.js → localRuntimeAuthority-7DKIT7UH.js} +4 -2
  196. package/{localRuntimeDb-N7KHDXS2.js → localRuntimeDb-5WZ4RJJO.js} +1 -1
  197. package/{machineCommands-4ZLMRIA3.js → machineCommands-3O6Y27R4.js} +283 -348
  198. package/machineWsRunDispatch-5PFLR5XC.js +203 -0
  199. package/markdownToSlate-KIYM7B3P.js +8 -0
  200. package/mcpLocalAuthorizeCommand-BQCQ2KRJ.js +106 -0
  201. package/{memberThunks-JRYNONYV.js → memberThunks-TU6A6OBV.js} +24 -19
  202. package/{memoryCommands-5WC3T66U.js → memoryCommands-BC6REPQB.js} +4 -4
  203. package/{models-H5NNZRLH.js → models-CINY5UZR.js} +2 -2
  204. package/{overlay-THLKYIWY.js → overlay-JA3SPVUS.js} +7 -3
  205. package/package.json +1 -1
  206. package/{projectArchive-JBX6HNK6.js → projectArchive-X2EVXU3N.js} +47 -44
  207. package/{providerPresetApply-J3WMRPD2.js → providerPresetApply-HUWNV2NI.js} +7 -7
  208. package/{providerRegistry-KJGB5XWS.js → providerRegistry-7FWKDKZJ.js} +7 -7
  209. package/{read-Q7GOHGNP.js → read-QAHEQID5.js} +9 -8
  210. package/{readDocTool-Z5OQ6422.js → readDocTool-KG5DP6EM.js} +1 -1
  211. package/{readlineWorkspace-WFPIAAAT.js → readlineWorkspace-SO3APHVP.js} +8125 -6196
  212. package/rememberExplicit-CPAPONSI.js +15 -0
  213. package/{removeDialogAgentAction-U3F2MNAY.js → removeDialogAgentAction-QZCCVK2G.js} +20 -19
  214. package/{runAgentClientLoop-STI5TKDJ.js → runAgentClientLoop-FLHHCOVH.js} +106 -81
  215. package/{runtimeDoctorCommands-UXKXYBW6.js → runtimeDoctorCommands-DN3I52C6.js} +17 -17
  216. package/{secretCommands-LJXOOYA7.js → secretCommands-36BCE3UE.js} +4 -4
  217. package/{setDialogExtraReferencesAction-G3WSJ7EM.js → setDialogExtraReferencesAction-PDPTYSEW.js} +17 -16
  218. package/{setPrimaryDialogAgentAction-6FHAHZBB.js → setPrimaryDialogAgentAction-DOUIPR66.js} +20 -19
  219. package/{settingThunks-AXTBX3Q5.js → settingThunks-MHGGP6UE.js} +186 -67
  220. package/{skillDiscovery-B5V23AXP.js → skillDiscovery-MDDKPTW3.js} +4 -3
  221. package/{spaceCommands-GUKMDRWN.js → spaceCommands-JH7UYE3K.js} +70 -61
  222. package/{store-JRVN62NM.js → store-Z53ICFL3.js} +3 -1
  223. package/{streamAgentChatTurn-A2WL5OOF.js → streamAgentChatTurn-VDDA2TX6.js} +200 -195
  224. package/{switchDialogAgentAction-UOFIAGPL.js → switchDialogAgentAction-7USK3DAP.js} +18 -17
  225. package/{tableCommands-HITDSLHS.js → tableCommands-UONBFC7L.js} +15 -12
  226. package/{toolApiClient-OGQEBQVX.js → toolApiClient-53YMJ2G6.js} +8 -6
  227. package/{tools-6NU5E6BN.js → tools-MIOCXKMG.js} +72 -68
  228. package/tuiRestart-ET3QISZ5.js +41 -0
  229. package/{tuiSummaryLlmCaller-7WLUKNP2.js → tuiSummaryLlmCaller-MSINBP3M.js} +21 -20
  230. package/{updateCommands-RJVCRSBP.js → updateCommands-5OYND6EF.js} +8 -6
  231. package/{updateDialogTitleAction-VMKU2Y67.js → updateDialogTitleAction-2L4CC4YO.js} +43 -40
  232. package/{usageCommand-YPJ2ZI2F.js → usageCommand-JTKDAG6I.js} +3 -3
  233. package/{usageRebuildCommand-FERQO74C.js → usageRebuildCommand-4TFZCKXM.js} +4 -4
  234. package/webapi-24RZDIIQ.js +2488 -0
  235. package/{windowsSelfUpdate-KERHIAB4.js → windowsSelfUpdate-HIYNL3VR.js} +2 -2
  236. package/workContext-Y3ADAPZU.js +14 -0
  237. package/workContextAccess-UZHDLBUR.js +11 -0
  238. package/workContextWriteNotice-YCSSMHN4.js +7 -0
  239. package/{workloadLifecycle-O2I3NZ2Q.js → workloadLifecycle-ZCSQCHG3.js} +9 -9
  240. package/agentListCommands-YBNOQ5T3.js +0 -991
  241. package/agentRecordCommands-3HL7Z4X6.js +0 -177
  242. package/agentRunCommand-C64A6MPL.js +0 -208
  243. package/chunk-2THCNKE4.js +0 -147
  244. package/chunk-2WZXXAQD.js +0 -57
  245. package/chunk-5ZMIIR23.js +0 -265
  246. package/chunk-652XYZGP.js +0 -352
  247. package/chunk-BJF2MHJ3.js +0 -118
  248. package/chunk-KEPOVMF4.js +0 -91
  249. package/chunk-QVBXJNZ2.js +0 -81
  250. package/chunk-QZI44GWV.js +0 -776
  251. package/cliLocalAgentRecordReader-6FXGFBI3.js +0 -90
  252. package/machineWsRunDispatch-L7Z3ULDF.js +0 -192
  253. package/{accountResolver-EK2S4PWF.js → accountResolver-QETKNC7T.js} +3 -3
  254. package/{chunk-W6RFEDN4.js → chunk-AETZ7AD6.js} +3 -3
  255. package/{chunk-BLVSFYQ3.js → chunk-LISC7BD4.js} +3 -3
  256. package/{chunk-SNBZZPYH.js → chunk-OQHIVPG4.js} +3 -3
  257. package/{chunk-47ITIXO7.js → chunk-USGHJSGO.js} +3 -3
  258. package/{chunk-FJ23FZXF.js → chunk-VIYVRPMJ.js} +0 -0
  259. package/{offlineMarxistsAgentCommand-4IC3Y4C6.js → offlineMarxistsAgentCommand-XVXUE6G5.js} +3 -3
@@ -0,0 +1,1438 @@
1
+ import {
2
+ resolveObservedSpeed
3
+ } from "./chunk-AMWMV56B.js";
4
+ import {
5
+ fnv1a32Hex
6
+ } from "./chunk-UEILX4EV.js";
7
+ import {
8
+ compareAgentSelection,
9
+ resolveModelTier
10
+ } from "./chunk-QXUVCIPB.js";
11
+ import {
12
+ DEFAULT_PROVIDER_RETRY_MS,
13
+ isAgentUnavailableNow,
14
+ resolveAgentAvailability
15
+ } from "./chunk-QJTZ76CP.js";
16
+ import {
17
+ LIST_AGENTS_PAGE_BUDGET,
18
+ sanitizeToolOutputText,
19
+ scrubSecrets
20
+ } from "./chunk-WFGNWWJI.js";
21
+ import {
22
+ isOAuthApiKeyRef
23
+ } from "./chunk-UKZX3NHN.js";
24
+ import {
25
+ createKey,
26
+ createTokenKey
27
+ } from "./chunk-SYTHYBMI.js";
28
+ import {
29
+ isOwnedAgentKey,
30
+ ownedAgentKey,
31
+ publicAgentKey
32
+ } from "./chunk-M2EJHDJP.js";
33
+ import {
34
+ getModelAbility
35
+ } from "./chunk-776CXKMX.js";
36
+ import {
37
+ isAntigravityOAuthAgent,
38
+ isSubscriptionEndpoint,
39
+ isSubscriptionOAuthCredential
40
+ } from "./chunk-Y22P6ASC.js";
41
+ import {
42
+ asTrimmedLowercaseString
43
+ } from "./chunk-QSJ3HFEF.js";
44
+
45
+ // packages/core/gptProTier.ts
46
+ var GPT_PRO_REQUIRED_RECHARGE_AMOUNT = 199;
47
+ var SUPPORTED_TIER_PROVIDERS = /* @__PURE__ */ new Set([
48
+ "nolo",
49
+ "openai",
50
+ "deepinfra"
51
+ ]);
52
+ var CLAUDE_PREMIUM_RE = /^(?:anthropic\/)?claude-(opus|fable)(?:-\d+(?:[.-]\d+)*(?:-[a-z0-9]+)*)?$/i;
53
+ var GPT_PRO_RE = /^(?:openai\/)?gpt-[a-z0-9.-]+-pro(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?$/i;
54
+ var GPT_SOL_RE = /^(?:openai\/)?gpt-\d+(?:\.\d+)*-sol(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?$/i;
55
+ var GPT_ASTRA_RE = /^(?:openai\/)?gpt-\d+(?:\.\d+)*-astra(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?$/i;
56
+ var KIMI_K3_MODELS = /* @__PURE__ */ new Set([
57
+ "kimi-k3",
58
+ "moonshotai/kimi-k3"
59
+ ]);
60
+ function classifyPremiumModel(model) {
61
+ const normalizedModel = asTrimmedLowercaseString(model);
62
+ if (!normalizedModel) return void 0;
63
+ const claudeMatch = CLAUDE_PREMIUM_RE.exec(normalizedModel);
64
+ if (claudeMatch) {
65
+ return claudeMatch[1].toLowerCase() === "opus" ? "claude-opus" : "claude-fable";
66
+ }
67
+ if (GPT_PRO_RE.test(normalizedModel)) {
68
+ return "gpt-pro";
69
+ }
70
+ if (GPT_SOL_RE.test(normalizedModel)) {
71
+ return "gpt-sol";
72
+ }
73
+ if (GPT_ASTRA_RE.test(normalizedModel)) {
74
+ return "gpt-astra";
75
+ }
76
+ if (KIMI_K3_MODELS.has(normalizedModel)) {
77
+ return "kimi-k3";
78
+ }
79
+ return void 0;
80
+ }
81
+ function isGptProModel(provider, model) {
82
+ const normalizedProvider = asTrimmedLowercaseString(provider);
83
+ if (!SUPPORTED_TIER_PROVIDERS.has(normalizedProvider)) {
84
+ return false;
85
+ }
86
+ return classifyPremiumModel(model) !== void 0;
87
+ }
88
+ var GPT_PRO_BLOCKED_MESSAGE = `GPT Pro / Kimi K3 \u7B49\u9AD8\u7EA7\u6A21\u578B\u9700\u8981\u5148\u5F00\u901A ${GPT_PRO_REQUIRED_RECHARGE_AMOUNT} \u79EF\u5206\u6863\u4F4D\u3002`;
89
+ function shouldBlockForGptPro(input) {
90
+ if (input?.premium !== true || input?.platformPaid !== true) {
91
+ return { blocked: false };
92
+ }
93
+ if (asTrimmedLowercaseString(input.gptProStatus) === "active") {
94
+ return { blocked: false };
95
+ }
96
+ return { blocked: true, message: GPT_PRO_BLOCKED_MESSAGE };
97
+ }
98
+
99
+ // packages/ai/agent/agentBilling.ts
100
+ function resolveBillingSource(candidate) {
101
+ if (candidate?.local === true || candidate?.isLocal === true || candidate?.cliProvider === "local" || candidate?.apiSource === "local" || candidate?.provider === "local" || candidate?.billingSource === "local") return "local";
102
+ if (candidate?.isOwned !== true) {
103
+ const ownerUserId = typeof candidate?.userId === "string" && candidate.userId.trim() ? candidate.userId.trim() : typeof candidate?.ownerId === "string" && candidate.ownerId.trim() ? candidate.ownerId.trim() : "";
104
+ if (ownerUserId && (candidate?.isOAuth === true || isOAuthApiKeyRef(candidate?.apiKeyRef) || isAntigravityOAuthAgent({
105
+ key: "billing-source-probe",
106
+ apiKeyRef: candidate?.apiKeyRef ?? void 0,
107
+ provider: candidate?.provider ?? void 0,
108
+ customProviderUrl: candidate?.customProviderUrl ?? void 0
109
+ }))) {
110
+ return "owner_subscription";
111
+ }
112
+ return "platform_credits";
113
+ }
114
+ if (candidate?.isOAuth === true || candidate?.billingSource === "user_subscription" || candidate?.apiSource === "oauth" || isOAuthApiKeyRef(candidate?.apiKeyRef)) return "user_subscription";
115
+ if (candidate?.apiSource === "custom" || candidate?.billingSource === "user_api") {
116
+ if (isSubscriptionEndpoint(candidate?.customProviderUrl) || isSubscriptionOAuthCredential(candidate?.apiKeyRef)) {
117
+ return "user_subscription";
118
+ }
119
+ return "user_api";
120
+ }
121
+ return "platform_credits";
122
+ }
123
+
124
+ // packages/ai/economics/economicsPolicy.ts
125
+ var DEEPSEEK_PRICING_DOC = "https://api-docs.deepseek.com/quick_start/pricing";
126
+ var BIGMODEL_CODING_PLAN_USAGE_NOTES = "https://docs.bigmodel.cn/cn/coding-plan/usage-notes";
127
+ var WEEKDAYS_MON_FRI = [1, 2, 3, 4, 5];
128
+ var DEEPSEEK_API_POLICY = {
129
+ id: "deepseek_api",
130
+ version: "2026-09-weekday-utc-peak-2x",
131
+ windows: [
132
+ { timezone: "UTC", weekdays: WEEKDAYS_MON_FRI, startMinute: 60, endMinute: 240 },
133
+ { timezone: "UTC", weekdays: WEEKDAYS_MON_FRI, startMinute: 360, endMinute: 600 }
134
+ ],
135
+ effectiveFrom: Date.UTC(2026, 7, 16, 16, 0, 0),
136
+ peakPriceMultiplier: 2,
137
+ offPeakPriceMultiplier: 1,
138
+ sourceUrl: DEEPSEEK_PRICING_DOC
139
+ };
140
+ var BIGMODEL_GLM_CODING_PLAN_POLICY = {
141
+ id: "bigmodel_glm_coding_plan",
142
+ version: "2026-09-coding-plan-sh-peak-14-18",
143
+ windows: [
144
+ { timezone: "Asia/Shanghai", weekdays: WEEKDAYS_MON_FRI, startMinute: 840, endMinute: 1080 }
145
+ ],
146
+ peakQuotaMultiplier: 1,
147
+ offPeakQuotaMultiplier: 0.5,
148
+ sourceUrl: BIGMODEL_CODING_PLAN_USAGE_NOTES
149
+ };
150
+ var ECONOMICS_POLICIES = [
151
+ DEEPSEEK_API_POLICY,
152
+ BIGMODEL_GLM_CODING_PLAN_POLICY
153
+ ];
154
+ function resolveEconomicsSourceId(input) {
155
+ const provider = typeof input?.provider === "string" ? input.provider.trim().toLowerCase() : "";
156
+ if (input?.apiSource?.trim().toLowerCase() === "platform") return null;
157
+ const rawUrl = typeof input?.customProviderUrl === "string" ? input.customProviderUrl.trim() : "";
158
+ let hostname = "";
159
+ let pathname = "";
160
+ if (rawUrl) {
161
+ try {
162
+ const parsed = new URL(rawUrl);
163
+ hostname = parsed.hostname.toLowerCase();
164
+ pathname = parsed.pathname;
165
+ } catch {
166
+ return null;
167
+ }
168
+ }
169
+ if (provider === "deepseek") {
170
+ if (rawUrl && hostname !== "api.deepseek.com") return null;
171
+ return rawUrl ? "deepseek_api" : null;
172
+ }
173
+ if (provider === "bigmodel") {
174
+ if (hostname === "open.bigmodel.cn" && pathname.startsWith("/api/coding/")) {
175
+ return "bigmodel_glm_coding_plan";
176
+ }
177
+ return null;
178
+ }
179
+ return null;
180
+ }
181
+
182
+ // packages/ai/economics/economicsSnapshot.ts
183
+ var wallClockFormatterCache = /* @__PURE__ */ new Map();
184
+ function getWallClockFormatter(timezone) {
185
+ let formatter = wallClockFormatterCache.get(timezone);
186
+ if (!formatter) {
187
+ formatter = new Intl.DateTimeFormat("en-US", {
188
+ timeZone: timezone,
189
+ hourCycle: "h23",
190
+ year: "numeric",
191
+ month: "2-digit",
192
+ day: "2-digit",
193
+ hour: "2-digit",
194
+ minute: "2-digit",
195
+ second: "2-digit"
196
+ });
197
+ wallClockFormatterCache.set(timezone, formatter);
198
+ }
199
+ return formatter;
200
+ }
201
+ function getZonedWallClock(timezone, at) {
202
+ const parts = getWallClockFormatter(timezone).formatToParts(new Date(at));
203
+ const values = {};
204
+ for (const part of parts) {
205
+ if (part.type !== "literal") values[part.type] = Number(part.value);
206
+ }
207
+ const year = values.year;
208
+ const month = values.month;
209
+ const day = values.day;
210
+ const hour = values.hour;
211
+ const minute = values.minute;
212
+ const second = values.second;
213
+ const weekday = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
214
+ return { year, month, day, hour, minute, second, weekday, minutesOfDay: hour * 60 + minute };
215
+ }
216
+ function getTimeZoneOffsetMs(timezone, at) {
217
+ const atSecond = Math.floor(at / 1e3) * 1e3;
218
+ const clock = getZonedWallClock(timezone, atSecond);
219
+ return Date.UTC(clock.year, clock.month - 1, clock.day, clock.hour, clock.minute, clock.second) - atSecond;
220
+ }
221
+ function zonedWallClockToEpochMs(timezone, year, month, day, minutesOfDay) {
222
+ const guess = Date.UTC(year, month - 1, day, Math.floor(minutesOfDay / 60), minutesOfDay % 60);
223
+ let instant = guess - getTimeZoneOffsetMs(timezone, guess);
224
+ instant = guess - getTimeZoneOffsetMs(timezone, instant);
225
+ return instant;
226
+ }
227
+ function resolveEconomicsPeriod(policy, at) {
228
+ for (const window of policy.windows) {
229
+ const clock = getZonedWallClock(window.timezone, at);
230
+ if (!window.weekdays.includes(clock.weekday)) continue;
231
+ if (clock.minutesOfDay >= window.startMinute && clock.minutesOfDay < window.endMinute) {
232
+ return "peak";
233
+ }
234
+ }
235
+ return "off_peak";
236
+ }
237
+ function findNextEconomicsBoundary(policy, at) {
238
+ let best;
239
+ for (const window of policy.windows) {
240
+ const anchor = getZonedWallClock(window.timezone, at);
241
+ for (let dayOffset = 0; dayOffset <= 7; dayOffset++) {
242
+ const dayUtc = new Date(Date.UTC(anchor.year, anchor.month - 1, anchor.day + dayOffset));
243
+ const weekday = dayUtc.getUTCDay();
244
+ if (!window.weekdays.includes(weekday)) continue;
245
+ const year = dayUtc.getUTCFullYear();
246
+ const month = dayUtc.getUTCMonth() + 1;
247
+ const day = dayUtc.getUTCDate();
248
+ for (const edge of [window.startMinute, window.endMinute]) {
249
+ const instant = zonedWallClockToEpochMs(window.timezone, year, month, day, edge);
250
+ if (instant > at && (best === void 0 || instant < best)) best = instant;
251
+ }
252
+ }
253
+ }
254
+ return best;
255
+ }
256
+ function selectEconomicsPolicyVersion(policies, sourceId, at) {
257
+ const applicable = policies.filter(
258
+ (policy) => policy.id === sourceId && (policy.effectiveFrom === void 0 || policy.effectiveFrom <= at) && (policy.effectiveUntil === void 0 || at < policy.effectiveUntil)
259
+ );
260
+ if (applicable.length === 0) return null;
261
+ return applicable.reduce(
262
+ (latest, candidate) => (candidate.effectiveFrom ?? -Infinity) >= (latest.effectiveFrom ?? -Infinity) ? candidate : latest
263
+ );
264
+ }
265
+ function findNextPolicyBoundary(policy, at, policies) {
266
+ const boundaries = [
267
+ policy.effectiveUntil,
268
+ ...policies.filter((candidate) => candidate.id === policy.id).map((candidate) => candidate.effectiveFrom).filter((value) => value !== void 0 && value > at)
269
+ ].filter((value) => value !== void 0 && value > at);
270
+ return boundaries.length > 0 ? Math.min(...boundaries) : void 0;
271
+ }
272
+ function resolveEconomicsSnapshot(input, at, policies = ECONOMICS_POLICIES) {
273
+ const sourceId = resolveEconomicsSourceId(input);
274
+ if (!sourceId) return null;
275
+ const policy = selectEconomicsPolicyVersion(policies, sourceId, at);
276
+ if (!policy) return null;
277
+ const period = resolveEconomicsPeriod(policy, at);
278
+ const priceMultiplier = period === "peak" ? policy.peakPriceMultiplier : policy.offPeakPriceMultiplier;
279
+ const quotaMultiplier = period === "peak" ? policy.peakQuotaMultiplier : policy.offPeakQuotaMultiplier;
280
+ const windowBoundary = findNextEconomicsBoundary(policy, at);
281
+ const policyBoundary = findNextPolicyBoundary(policy, at, policies);
282
+ const changesAt = [windowBoundary, policyBoundary].filter((value) => value !== void 0).sort((a, b) => a - b)[0];
283
+ return {
284
+ source: sourceId,
285
+ policyVersion: policy.version,
286
+ period,
287
+ ...priceMultiplier !== void 0 ? { priceMultiplier } : {},
288
+ ...quotaMultiplier !== void 0 ? { quotaMultiplier } : {},
289
+ ...changesAt !== void 0 ? { changesAt } : {}
290
+ };
291
+ }
292
+
293
+ // packages/ai/agent/safeAgentSummary.ts
294
+ function deriveCredentialGroup(ref) {
295
+ if (!ref || typeof ref !== "string") return void 0;
296
+ const trimmed = ref.trim();
297
+ if (!trimmed) return void 0;
298
+ if (isOAuthApiKeyRef(trimmed)) {
299
+ return {
300
+ credentialGroup: trimmed.toLowerCase(),
301
+ credentialKind: "oauth"
302
+ };
303
+ }
304
+ const hash = fnv1a32Hex(trimmed);
305
+ return {
306
+ credentialGroup: `cred-${hash}`,
307
+ credentialKind: "api-key"
308
+ };
309
+ }
310
+ function deriveCustomProviderCredentialGroup(userId, customProviderUrl) {
311
+ if (typeof customProviderUrl !== "string" || !customProviderUrl.trim()) {
312
+ return void 0;
313
+ }
314
+ const basis = `${userId ?? ""}|${customProviderUrl.trim().toLowerCase()}`;
315
+ return {
316
+ credentialGroup: `custom-${fnv1a32Hex(basis)}`,
317
+ credentialKind: "api-key"
318
+ };
319
+ }
320
+ function summarizeCredentialGroups(agents, now = Date.now()) {
321
+ const groups = /* @__PURE__ */ new Map();
322
+ for (const agent of agents) {
323
+ if (!agent.credentialGroup || !agent.credentialKind) continue;
324
+ if (agent.isOwned === false) continue;
325
+ const existing = groups.get(agent.credentialGroup);
326
+ const at = typeof agent.nextAvailableAt === "number" && agent.nextAvailableAt > now ? agent.nextAvailableAt : void 0;
327
+ if (!existing) {
328
+ groups.set(agent.credentialGroup, {
329
+ credentialGroup: agent.credentialGroup,
330
+ credentialKind: agent.credentialKind,
331
+ agentCount: 1,
332
+ ...at !== void 0 ? { availableAt: at } : {}
333
+ });
334
+ } else {
335
+ existing.agentCount += 1;
336
+ if (at !== void 0) {
337
+ existing.availableAt = Math.max(existing.availableAt ?? 0, at);
338
+ }
339
+ }
340
+ }
341
+ return Array.from(groups.values()).sort(
342
+ (a, b) => a.credentialGroup.localeCompare(b.credentialGroup)
343
+ );
344
+ }
345
+ function parseTimestamp(val) {
346
+ if (typeof val === "number" && Number.isFinite(val)) return val;
347
+ if (typeof val === "string") return Date.parse(val) || 0;
348
+ return 0;
349
+ }
350
+ function safeTimestamp(val) {
351
+ if (typeof val === "number" && Number.isFinite(val)) return val;
352
+ if (typeof val === "string") return val;
353
+ return null;
354
+ }
355
+ function parseAgentRecordId(privateKey, explicitId) {
356
+ if (explicitId && typeof explicitId === "string" && explicitId.trim()) {
357
+ return explicitId.trim();
358
+ }
359
+ if (privateKey && typeof privateKey === "string") {
360
+ const match = privateKey.match(/^agent-[^-]+-(.+)$/i);
361
+ if (match?.[1]) return match[1];
362
+ }
363
+ return null;
364
+ }
365
+ function resolveFavoriteStatus(record2, options) {
366
+ if (options?.isFavorite !== void 0) {
367
+ return {
368
+ isFavorite: !!options.isFavorite,
369
+ favoritedAt: safeTimestamp(options.favoritedAt)
370
+ };
371
+ }
372
+ if (record2?.isFavorite === true) {
373
+ return {
374
+ isFavorite: true,
375
+ favoritedAt: safeTimestamp(record2?.favoritedAt)
376
+ };
377
+ }
378
+ const favoritesMap = options?.favoritesMap;
379
+ if (!favoritesMap) {
380
+ return { isFavorite: false, favoritedAt: null };
381
+ }
382
+ const candidateKeys = [];
383
+ if (typeof record2?.dbKey === "string" && record2.dbKey) candidateKeys.push(record2.dbKey);
384
+ if (typeof record2?.privateKey === "string" && record2.privateKey) candidateKeys.push(record2.privateKey);
385
+ if (typeof record2?.publicKey === "string" && record2.publicKey) candidateKeys.push(record2.publicKey);
386
+ if (typeof record2?.verifiedAgentKey === "string" && record2.verifiedAgentKey) {
387
+ candidateKeys.push(record2.verifiedAgentKey);
388
+ }
389
+ if (typeof record2?.id === "string" && record2.id) {
390
+ candidateKeys.push(record2.id);
391
+ candidateKeys.push(publicAgentKey(record2.id));
392
+ if (options?.userId) {
393
+ candidateKeys.push(ownedAgentKey(options.userId, record2.id));
394
+ }
395
+ }
396
+ let matched = false;
397
+ let highestFavAt = null;
398
+ let highestFavTime = -1;
399
+ for (const key of candidateKeys) {
400
+ const val = favoritesMap instanceof Map ? favoritesMap.get(key) : favoritesMap[key];
401
+ if (val !== void 0 && val !== false && val !== null) {
402
+ const favAt = val === true ? 1 : safeTimestamp(val);
403
+ if (favAt === null) continue;
404
+ matched = true;
405
+ const time = parseTimestamp(favAt);
406
+ if (time > highestFavTime) {
407
+ highestFavTime = time;
408
+ highestFavAt = favAt;
409
+ }
410
+ }
411
+ }
412
+ if (matched) {
413
+ return {
414
+ isFavorite: true,
415
+ favoritedAt: highestFavAt ?? 1
416
+ };
417
+ }
418
+ return { isFavorite: false, favoritedAt: null };
419
+ }
420
+ function isOwnedAgentRecord(record2, userId) {
421
+ if (!userId) return false;
422
+ if (typeof record2?.userId === "string" && record2.userId === userId || typeof record2?.ownerId === "string" && record2.ownerId === userId) {
423
+ return true;
424
+ }
425
+ return [record2?.dbKey, record2?.privateKey].some(
426
+ (key) => isOwnedAgentKey(key, userId)
427
+ );
428
+ }
429
+ function toSafeAgentSummary(record2, options) {
430
+ const rawId = parseAgentRecordId(
431
+ typeof record2?.privateKey === "string" ? record2.privateKey : record2?.dbKey,
432
+ typeof record2?.id === "string" ? record2.id : void 0
433
+ );
434
+ const id = rawId ?? (typeof record2?.id === "string" ? record2.id : null);
435
+ const publicRecordDenied = record2?.publicRecordExists === false || options?.publicRecordExists === false;
436
+ const publicRecordConfirmed = record2?.publicRecordExists === true || options?.publicRecordExists === true;
437
+ let publicKey;
438
+ if (typeof record2?.publicKey === "string" && record2.publicKey && !publicRecordDenied) {
439
+ publicKey = record2.publicKey;
440
+ } else if (publicRecordConfirmed && id) {
441
+ publicKey = publicAgentKey(id);
442
+ }
443
+ const name = typeof record2?.name === "string" && record2.name ? record2.name : "(unnamed)";
444
+ const handle = typeof record2?.handle === "string" && record2.handle ? record2.handle : null;
445
+ const introduction = typeof record2?.introduction === "string" && record2.introduction ? record2.introduction : typeof record2?.description === "string" && record2.description ? record2.description : null;
446
+ const model = typeof record2?.model === "string" && record2.model ? record2.model : null;
447
+ const provider = typeof record2?.provider === "string" && record2.provider ? record2.provider : typeof record2?.apiSource === "string" && record2.apiSource ? record2.apiSource : null;
448
+ const apiSource = typeof record2?.apiSource === "string" && record2.apiSource ? record2.apiSource : null;
449
+ const cliProvider = typeof record2?.cliProvider === "string" && record2.cliProvider ? record2.cliProvider : null;
450
+ const tools = Array.isArray(record2?.tools) ? record2.tools.filter((t) => typeof t === "string") : [];
451
+ const inputPrice = typeof record2?.inputPrice === "number" && Number.isFinite(record2.inputPrice) ? record2.inputPrice : null;
452
+ const outputPrice = typeof record2?.outputPrice === "number" && Number.isFinite(record2.outputPrice) ? record2.outputPrice : null;
453
+ const modelAbility = model ? getModelAbility(model) ?? null : null;
454
+ const favStatus = resolveFavoriteStatus(record2, options);
455
+ const isPublic = record2?.isPublic === true || record2?.isPublicFlag === true || record2?.publicRecordExists === true;
456
+ const updatedAt = safeTimestamp(record2?.updatedAt ?? record2?.createdAt ?? record2?.created);
457
+ const nextAvailableAt = typeof record2?.nextAvailableAt === "number" && Number.isFinite(record2.nextAvailableAt) ? record2.nextAvailableAt : void 0;
458
+ const quotaExhaustion = record2?.quotaExhaustion && typeof record2.quotaExhaustion.observedAt === "number" && Number.isFinite(record2.quotaExhaustion.observedAt) ? { observedAt: record2.quotaExhaustion.observedAt } : void 0;
459
+ const rawQuota = record2?.quota;
460
+ const quota = rawQuota && typeof rawQuota === "object" && Array.isArray(rawQuota.windows) && typeof rawQuota.observedAt === "number" && Number.isFinite(rawQuota.observedAt) ? rawQuota : void 0;
461
+ const currentUserId = options?.userId;
462
+ const ownedKey = currentUserId ? [record2?.dbKey, record2?.privateKey].find(
463
+ (key) => isOwnedAgentKey(key, currentUserId)
464
+ ) : void 0;
465
+ const isOwned = isOwnedAgentRecord(record2, currentUserId);
466
+ const isOAuth = isOAuthApiKeyRef(record2?.apiKeyRef);
467
+ const billingSource = resolveBillingSource({
468
+ ...record2,
469
+ isOAuth,
470
+ isOwned,
471
+ apiSource,
472
+ cliProvider,
473
+ provider,
474
+ isPublic
475
+ });
476
+ const economics = resolveEconomicsSnapshot(
477
+ {
478
+ provider,
479
+ apiSource,
480
+ customProviderUrl: typeof record2?.customProviderUrl === "string" ? record2.customProviderUrl : null
481
+ },
482
+ options?.now ?? Date.now()
483
+ );
484
+ const verifiedSharedKey = typeof record2?.verifiedAgentKey === "string" && record2.verifiedAgentKey ? record2.verifiedAgentKey : void 0;
485
+ let agentKey;
486
+ if (currentUserId) {
487
+ if (isOwned) {
488
+ agentKey = ownedKey ?? (id ? ownedAgentKey(currentUserId, id) : void 0);
489
+ } else if (publicKey) {
490
+ agentKey = publicKey;
491
+ } else {
492
+ agentKey = verifiedSharedKey;
493
+ }
494
+ }
495
+ const rawCredRef = (typeof record2?.apiKeyRef === "string" && record2.apiKeyRef ? record2.apiKeyRef : void 0) ?? (typeof record2?.credentialRef === "string" && record2.credentialRef ? record2.credentialRef : void 0);
496
+ const credInfo = deriveCredentialGroup(record2?.credentialGroup ?? rawCredRef);
497
+ const credentialGroup = record2?.credentialGroup ?? credInfo?.credentialGroup;
498
+ const credentialKind = record2?.credentialKind ?? credInfo?.credentialKind;
499
+ const availability = resolveAgentAvailability(
500
+ { nextAvailableAt, quota, quotaExhaustion },
501
+ options?.now ?? Date.now()
502
+ );
503
+ return {
504
+ id,
505
+ ...agentKey !== void 0 ? { agentKey } : {},
506
+ ...publicKey !== void 0 ? { publicKey } : {},
507
+ name,
508
+ handle,
509
+ introduction,
510
+ model,
511
+ modelTier: resolveModelTier(model),
512
+ provider,
513
+ apiSource,
514
+ cliProvider,
515
+ billingSource,
516
+ tools,
517
+ inputPrice,
518
+ outputPrice,
519
+ modelAbility,
520
+ isFavorite: favStatus.isFavorite,
521
+ favoritedAt: favStatus.favoritedAt,
522
+ isPublic,
523
+ // 复用 platformPaidCall.ts 的唯一判据(该文件头明确它是「谁出钱」的真源):
524
+ // 自己写 billingSource === "platform_credits" 会与 199 门槛口径分叉——
525
+ // 例如 apiSource==="cli" 的本地 CLI Agent 在 resolveBillingSource 里会落到
526
+ // platform_credits,但 isPlatformPaidAgentCall 显式短路为「非平台垫付」。
527
+ requiresPaidApproval: isPlatformPaidAgentCall({
528
+ agentConfig: record2 ?? void 0,
529
+ callerUserId: currentUserId ?? void 0
530
+ }),
531
+ ...economics ? { economics } : {},
532
+ isOwned,
533
+ isOAuth,
534
+ ...nextAvailableAt !== void 0 ? { nextAvailableAt } : {},
535
+ availabilityStatus: availability.status,
536
+ availabilityReason: availability.reason,
537
+ ...quota !== void 0 ? { quota } : {},
538
+ ...quotaExhaustion ? { quotaExhaustion } : {},
539
+ ...credentialGroup !== void 0 ? { credentialGroup } : {},
540
+ ...credentialKind !== void 0 ? { credentialKind } : {},
541
+ // 「未知 ≠ 独立」:无 credentialGroup 时显式 credentialed:false,调用方
542
+ // 不得把缺失解读成独立凭证(并发扇出守卫依赖这个区分)。
543
+ credentialed: credentialGroup !== void 0,
544
+ updatedAt
545
+ };
546
+ }
547
+ function sortSafeAgentSummaries(agents) {
548
+ return [...agents].sort(compareAgentSelection);
549
+ }
550
+ var COMPACT_AGENT_SUMMARY_FIELDS = [
551
+ // —— 派发决策必需(短字段,必须排最前)——
552
+ // agentKey 是唯一不可推导、必须逐字复制的字段;截断时它首先被保住。
553
+ "agentKey",
554
+ "name",
555
+ "model",
556
+ "modelTier",
557
+ "billingSource",
558
+ // 扣费授权判据:listAgents 默认走 compact 投影,缺了它模型在默认派发
559
+ // 流程里读不到「派它之前要先问用户」(2026-11-15 事故成因)。
560
+ // 与 ULTRA_COMPACT 白名单必须同时保留——两处任何一处缺失都等于该字段不存在。
561
+ "requiresPaidApproval",
562
+ "availabilityStatus",
563
+ "credentialGroup",
564
+ "isFavorite",
565
+ "isOAuth",
566
+ "isOwned",
567
+ "isPublic",
568
+ // —— 次要身份/来源字段(仍很短)——
569
+ "provider",
570
+ "apiSource",
571
+ "credentialKind",
572
+ "credentialed",
573
+ // 仅限流中的 agent 才会带(可用 agent 上不存在)。额度/冷却只作参考信息,
574
+ // 不参与派发门控:这类 agent 同样在 agents 主列表里(带标注),不做过滤,
575
+ // 所以这两个字段只在确实限流时才占字节。
576
+ "nextAvailableAt",
577
+ "availabilityReason",
578
+ // —— 体积大的说明性字段(排在每条记录最后,截断时先牺牲它们)——
579
+ // Phase 2A economics 快照(period/multipliers/changesAt 等小对象)。
580
+ // 只对 DeepSeek API / BigModel GLM Coding Plan 存在;不含完整 policy/windows。
581
+ "economics",
582
+ "tools",
583
+ // 额度快照(windows 数组,体积最大):只有上游真上报过窗口的 agent 才带。
584
+ "quota"
585
+ ];
586
+ function omitNullishAgentSummaryFields(summary) {
587
+ const result = {};
588
+ for (const [key, value] of Object.entries(summary)) {
589
+ if (value !== null && value !== void 0) {
590
+ result[key] = value;
591
+ }
592
+ }
593
+ return result;
594
+ }
595
+ function toCompactAgentSummary(summary) {
596
+ const compact = {};
597
+ for (const field of COMPACT_AGENT_SUMMARY_FIELDS) {
598
+ const value = summary[field];
599
+ if (value !== null && value !== void 0) {
600
+ compact[field] = value;
601
+ }
602
+ }
603
+ return compact;
604
+ }
605
+ var ULTRA_COMPACT_AGENT_SUMMARY_FIELDS = [
606
+ // —— 派发决策与关键准入语义(必须保留,不能宣称安全但丢证据)——
607
+ "agentKey",
608
+ "name",
609
+ "model",
610
+ "modelTier",
611
+ "billingSource",
612
+ // 扣费授权判据必须随投影一起走:精简投影里没有它,模型就看不到
613
+ // 「派它之前要先问用户」,等于该字段不存在(2026-11-15 事故的直接成因)。
614
+ "requiresPaidApproval",
615
+ "availabilityStatus",
616
+ "credentialGroup",
617
+ "isFavorite",
618
+ "isOAuth",
619
+ "isOwned",
620
+ "isPublic",
621
+ "provider",
622
+ "apiSource",
623
+ "credentialKind",
624
+ "credentialed",
625
+ "nextAvailableAt",
626
+ "availabilityReason",
627
+ "economics",
628
+ "tools",
629
+ "quota"
630
+ ];
631
+ function toUltraCompactAgentSummary(summary) {
632
+ const compact = {};
633
+ for (const field of ULTRA_COMPACT_AGENT_SUMMARY_FIELDS) {
634
+ const value = summary[field];
635
+ if (value !== null && value !== void 0) {
636
+ compact[field] = value;
637
+ }
638
+ }
639
+ return compact;
640
+ }
641
+
642
+ // packages/ai/agent/platformPaidCall.ts
643
+ var asTrimmed = (value) => typeof value === "string" ? value.trim() : "";
644
+ var hasOAuthCredentialShape = (agentConfig) => isOAuthApiKeyRef(agentConfig?.apiKeyRef) || isAntigravityOAuthAgent({
645
+ key: "platform-paid-call-probe",
646
+ apiKeyRef: agentConfig?.apiKeyRef ?? void 0,
647
+ provider: agentConfig?.provider ?? void 0,
648
+ customProviderUrl: agentConfig?.customProviderUrl ?? void 0
649
+ });
650
+ function isPlatformPaidAgentCall(probe) {
651
+ const agentConfig = probe?.agentConfig ?? {};
652
+ const authKind = asTrimmed(probe?.authKind);
653
+ if (authKind) return authKind === "platform-key";
654
+ if (asTrimmed(agentConfig.apiSource) === "cli") return false;
655
+ return resolveBillingSource({
656
+ local: agentConfig.local,
657
+ isLocal: agentConfig.isLocal,
658
+ cliProvider: agentConfig.cliProvider,
659
+ apiSource: agentConfig.apiSource,
660
+ provider: agentConfig.provider,
661
+ billingSource: agentConfig.billingSource,
662
+ // 形态证明而非记录自声明(见文件头):自声明 isOAuth 不足以证明 OAuth 通道归属。
663
+ isOAuth: hasOAuthCredentialShape(agentConfig),
664
+ apiKeyRef: agentConfig.apiKeyRef,
665
+ customProviderUrl: agentConfig.customProviderUrl,
666
+ isOwned: isOwnedAgentRecord(
667
+ agentConfig,
668
+ asTrimmed(probe?.callerUserId) || void 0
669
+ ),
670
+ userId: agentConfig.userId,
671
+ ownerId: agentConfig.ownerId
672
+ }) === "platform_credits";
673
+ }
674
+
675
+ // packages/ai/agent/agentDiscovery.ts
676
+ function isPreferredAgent(agent) {
677
+ return agent.isFavorite === true || agent.isOwned === true || agent.isOAuth === true || agent.billingSource === "user_subscription" || agent.billingSource === "user_api" || agent.billingSource === "local";
678
+ }
679
+ function isPublicDiscoveryAgent(agent) {
680
+ return agent.isPublic === true && !isPreferredAgent(agent);
681
+ }
682
+ function resolveDiscoveryScope(args) {
683
+ const rawScope = typeof args?.scope === "string" ? args.scope.trim().toLowerCase() : void 0;
684
+ const hasScope = rawScope !== void 0 && rawScope !== "";
685
+ const hasPublicOnly = typeof args?.publicOnly === "boolean";
686
+ const publicOnly = args?.publicOnly === true;
687
+ if (hasScope) {
688
+ if (rawScope !== "preferred" && rawScope !== "public" && rawScope !== "all") {
689
+ throw new Error(`Invalid scope '${args?.scope}': must be 'preferred', 'public', or 'all'.`);
690
+ }
691
+ const scope = rawScope;
692
+ if (hasPublicOnly) {
693
+ if (publicOnly && scope !== "public") {
694
+ throw new Error(
695
+ `Conflicting arguments: scope='${args?.scope}' conflicts with publicOnly=true.`
696
+ );
697
+ }
698
+ if (!publicOnly && scope === "public") {
699
+ throw new Error(
700
+ `Conflicting arguments: scope='${args?.scope}' conflicts with publicOnly=false.`
701
+ );
702
+ }
703
+ }
704
+ return scope;
705
+ }
706
+ if (hasPublicOnly && publicOnly) {
707
+ return "public";
708
+ }
709
+ return "all";
710
+ }
711
+ function agentIdentityKeys(agent) {
712
+ return [agent.agentKey, agent.publicKey, agent.id].filter(
713
+ (key) => typeof key === "string" && key.length > 0
714
+ );
715
+ }
716
+ function deduplicateAgentSummaries(agents) {
717
+ const byIdentity = /* @__PURE__ */ new Map();
718
+ for (const agent of agents) {
719
+ const keys = agentIdentityKeys(agent);
720
+ const existing = keys.map((key) => byIdentity.get(key)).find(Boolean);
721
+ if (!existing) {
722
+ for (const key of keys) byIdentity.set(key, agent);
723
+ continue;
724
+ }
725
+ const winner = isPreferredAgent(agent) && !isPreferredAgent(existing) ? agent : existing;
726
+ for (const key of /* @__PURE__ */ new Set([...agentIdentityKeys(existing), ...keys])) byIdentity.set(key, winner);
727
+ }
728
+ return [...new Set(byIdentity.values())];
729
+ }
730
+ function filterAgentsByScope(agents, scope) {
731
+ const unique = deduplicateAgentSummaries(agents);
732
+ if (scope === "preferred") return unique.filter((agent) => isPreferredAgent(agent));
733
+ if (scope === "public") return unique.filter((agent) => isPublicDiscoveryAgent(agent));
734
+ return unique.filter((agent) => isPreferredAgent(agent) || agent.isPublic === true);
735
+ }
736
+ function recommendPlanning(agents, caller, poolComplete) {
737
+ const callerKey = typeof caller?.agentKey === "string" && caller.agentKey.trim() ? caller.agentKey : void 0;
738
+ const current = callerKey ? agents.find((a) => a.agentKey === callerKey) : void 0;
739
+ const currentTier = callerKey ? resolveModelTier(caller?.effectiveModel ?? current?.model) : "unknown";
740
+ const base = {
741
+ condition: "when_planning_needed_and_candidate_suitable",
742
+ action: "self",
743
+ currentTier,
744
+ poolComplete,
745
+ requiresPaidApproval: false
746
+ };
747
+ if (caller?.runKind === "subtask") return { ...base, reason: "bounded_subtask" };
748
+ if (!callerKey) return { ...base, reason: "caller_unknown" };
749
+ if (currentTier === "unknown") return { ...base, reason: "caller_tier_unknown" };
750
+ if (!poolComplete) return { ...base, reason: "pool_incomplete" };
751
+ const ranks = { easy: 0, normal: 1, complex: 2, extreme: 3 };
752
+ const higher = agents.filter((a) => a.agentKey && a.agentKey !== callerKey && a.modelTier !== "unknown" && ranks[a.modelTier] > ranks[currentTier]);
753
+ const free = higher.filter((a) => a.requiresPaidApproval === false);
754
+ free.sort((a, b) => ranks[b.modelTier] - ranks[a.modelTier]);
755
+ const best = free[0];
756
+ if (best) return {
757
+ ...base,
758
+ action: "delegate",
759
+ reason: "higher_suitable_agent",
760
+ agentKey: best.agentKey,
761
+ recommendedTier: best.modelTier
762
+ };
763
+ if (higher.length) return { ...base, reason: "paid_approval_required", requiresPaidApproval: true };
764
+ return { ...base, reason: "no_higher_suitable_agent" };
765
+ }
766
+ function resolvePaginationArgs(args) {
767
+ let limit;
768
+ let offset;
769
+ if (args?.limit !== void 0 && args?.limit !== null) {
770
+ const raw = args.limit;
771
+ if (typeof raw === "boolean") {
772
+ throw new Error(`Invalid limit '${raw}': must be a positive integer.`);
773
+ }
774
+ if (typeof raw === "number") {
775
+ if (!Number.isInteger(raw) || raw <= 0) {
776
+ throw new Error(`Invalid limit '${raw}': must be a positive integer.`);
777
+ }
778
+ limit = Math.min(raw, 500);
779
+ } else if (typeof raw === "string") {
780
+ if (raw.trim() !== "") {
781
+ if (!/^\d+$/.test(raw.trim())) {
782
+ throw new Error(`Invalid limit '${raw}': must be a positive integer.`);
783
+ }
784
+ const parsed = Number(raw.trim());
785
+ if (!Number.isInteger(parsed) || parsed <= 0) {
786
+ throw new Error(`Invalid limit '${raw}': must be a positive integer.`);
787
+ }
788
+ limit = Math.min(parsed, 500);
789
+ }
790
+ } else {
791
+ throw new Error(`Invalid limit '${String(raw)}': must be a positive integer.`);
792
+ }
793
+ }
794
+ if (args?.offset !== void 0 && args?.offset !== null) {
795
+ const raw = args.offset;
796
+ if (typeof raw === "boolean") {
797
+ throw new Error(`Invalid offset '${raw}': must be a non-negative integer.`);
798
+ }
799
+ if (typeof raw === "number") {
800
+ if (!Number.isInteger(raw) || raw < 0) {
801
+ throw new Error(`Invalid offset '${raw}': must be a non-negative integer.`);
802
+ }
803
+ offset = raw;
804
+ } else if (typeof raw === "string") {
805
+ if (raw.trim() !== "") {
806
+ if (!/^\d+$/.test(raw.trim())) {
807
+ throw new Error(`Invalid offset '${raw}': must be a non-negative integer.`);
808
+ }
809
+ const parsed = Number(raw.trim());
810
+ if (!Number.isInteger(parsed) || parsed < 0) {
811
+ throw new Error(`Invalid offset '${raw}': must be a non-negative integer.`);
812
+ }
813
+ offset = parsed;
814
+ }
815
+ } else {
816
+ throw new Error(`Invalid offset '${String(raw)}': must be a non-negative integer.`);
817
+ }
818
+ }
819
+ return { limit, offset };
820
+ }
821
+ function matchesAgentQuery(agent, query) {
822
+ if (!query || typeof query !== "string") return true;
823
+ const q = query.trim().toLowerCase();
824
+ if (!q) return true;
825
+ const candidates = [
826
+ agent.name,
827
+ agent.model,
828
+ agent.provider,
829
+ agent.handle,
830
+ agent.agentKey,
831
+ agent.publicKey,
832
+ agent.id
833
+ ];
834
+ return candidates.some((text) => typeof text === "string" && text.toLowerCase().includes(q));
835
+ }
836
+ function buildAgentDiscoveryResult(options) {
837
+ const scope = resolveDiscoveryScope({
838
+ scope: options.scope,
839
+ publicOnly: options.publicOnly
840
+ });
841
+ const now = options.now ?? Date.now();
842
+ let scopedAgents = filterAgentsByScope(options.agents, scope);
843
+ if (options.query && typeof options.query === "string" && options.query.trim()) {
844
+ scopedAgents = scopedAgents.filter((a) => matchesAgentQuery(a, options.query));
845
+ }
846
+ scopedAgents = scopedAgents.map((agent) => {
847
+ const decision = resolveAgentAvailability(agent, now);
848
+ if (decision.status === "quota_exhausted") {
849
+ const resetAt = decision.resetAt ?? now + DEFAULT_PROVIDER_RETRY_MS;
850
+ const nextAvailableAt = typeof agent.nextAvailableAt === "number" && agent.nextAvailableAt > resetAt ? agent.nextAvailableAt : resetAt;
851
+ return {
852
+ ...agent,
853
+ nextAvailableAt,
854
+ availableAt: nextAvailableAt,
855
+ availabilityStatus: decision.status,
856
+ availabilityReason: decision.reason
857
+ };
858
+ }
859
+ return {
860
+ ...agent,
861
+ availabilityStatus: decision.status,
862
+ availabilityReason: decision.reason
863
+ };
864
+ });
865
+ const unavailableCount = scopedAgents.filter((a) => isAgentUnavailableNow(a, now)).length;
866
+ const credentialGroups = summarizeCredentialGroups(scopedAgents, now);
867
+ const pagination = resolvePaginationArgs({
868
+ limit: options.limit,
869
+ offset: options.offset
870
+ });
871
+ const offset = pagination.offset;
872
+ const limit = pagination.limit;
873
+ const sortedAgents = sortSafeAgentSummaries(scopedAgents);
874
+ const hasQuery = Boolean(options.query && typeof options.query === "string" && options.query.trim());
875
+ const hasFilteredCandidates = sortedAgents.length < options.agents.length;
876
+ let total;
877
+ if (hasQuery) {
878
+ total = sortedAgents.length;
879
+ } else if (hasFilteredCandidates) {
880
+ total = sortedAgents.length;
881
+ } else if (scope === "public") {
882
+ total = typeof options.upstreamTotal === "number" && options.upstreamTotal > sortedAgents.length ? options.upstreamTotal : sortedAgents.length;
883
+ } else if (scope === "all") {
884
+ const privateOnlyCount = scopedAgents.filter((a) => isPreferredAgent(a) && a.isPublic !== true).length;
885
+ const publicPulledCount = scopedAgents.filter((a) => a.isPublic === true).length;
886
+ const effectivePublicTotal = typeof options.upstreamTotal === "number" && options.upstreamTotal > publicPulledCount ? options.upstreamTotal : publicPulledCount;
887
+ total = options.upstreamTruncated === true ? privateOnlyCount + effectivePublicTotal : sortedAgents.length;
888
+ } else {
889
+ total = typeof options.upstreamTotal === "number" && options.upstreamTotal > sortedAgents.length ? options.upstreamTotal : sortedAgents.length;
890
+ }
891
+ const isTruncated = options.upstreamTruncated === true || !hasQuery && !hasFilteredCandidates && typeof options.upstreamTotal === "number" && options.upstreamTotal > sortedAgents.length;
892
+ const pagedAgents = typeof limit === "number" || typeof offset === "number" ? sortedAgents.slice(
893
+ offset ?? 0,
894
+ (offset ?? 0) + (limit ?? sortedAgents.length)
895
+ ) : sortedAgents;
896
+ const projectedAgents = options.verbose === true ? pagedAgents.map(omitNullishAgentSummaryFields) : options.compact === true ? pagedAgents.map(toUltraCompactAgentSummary) : pagedAgents.map(toCompactAgentSummary);
897
+ return {
898
+ total,
899
+ ...typeof offset === "number" ? { offset } : {},
900
+ ...typeof limit === "number" ? { limit } : {},
901
+ ...isTruncated ? { truncated: true } : {},
902
+ unavailableCount,
903
+ availableCount: sortedAgents.length,
904
+ agents: projectedAgents,
905
+ planningRecommendation: recommendPlanning(
906
+ sortedAgents,
907
+ options.caller,
908
+ !isTruncated && scope === "all" && !hasQuery && !options.poolRestricted
909
+ ),
910
+ credentialGroups
911
+ };
912
+ }
913
+ function toDiscoverySafeAgentSummary(record2, options) {
914
+ const mergedOptions = record2?.publicRecordExists === true ? { ...options, publicRecordExists: true } : options;
915
+ return toSafeAgentSummary(record2, mergedOptions);
916
+ }
917
+
918
+ // packages/ai/agent/speedSampleCache.ts
919
+ var SPEED_SAMPLE_DISK_CACHE_TTL_MS = 10 * 6e4;
920
+ var SPEED_SAMPLE_SCAN_BUDGET_MS = 2500;
921
+ var SPEED_SAMPLE_CACHE_VERSION = 4;
922
+ var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
923
+ var sanitizeSample = (value) => {
924
+ if (!value || typeof value !== "object") return null;
925
+ const sample = value;
926
+ const clean = {};
927
+ if (isFiniteNumber(sample.firstOutputMs)) clean.firstOutputMs = sample.firstOutputMs;
928
+ if (isFiniteNumber(sample.callDurationMs)) clean.callDurationMs = sample.callDurationMs;
929
+ if (isFiniteNumber(sample.output_tokens)) clean.output_tokens = sample.output_tokens;
930
+ if (isFiniteNumber(sample.t)) clean.t = sample.t;
931
+ return clean.firstOutputMs === void 0 && clean.callDurationMs === void 0 ? null : clean;
932
+ };
933
+ var SPEED_SAMPLE_STALE_SNAPSHOT_MAX_MS = 7 * 24 * 60 * 6e4;
934
+ async function parseCacheFile(cachePath, userId) {
935
+ try {
936
+ const fs = await import("node:fs/promises");
937
+ const raw = await fs.readFile(cachePath, "utf8");
938
+ const parsed = JSON.parse(raw);
939
+ if (!parsed || typeof parsed !== "object") return null;
940
+ const version = parsed.version;
941
+ if (version !== SPEED_SAMPLE_CACHE_VERSION) {
942
+ return null;
943
+ }
944
+ if (parsed.userId !== userId) return null;
945
+ if (!isFiniteNumber(parsed.at)) return null;
946
+ const source = parsed.samples;
947
+ if (!source || typeof source !== "object") return null;
948
+ const samples = /* @__PURE__ */ new Map();
949
+ for (const [model, list] of Object.entries(source)) {
950
+ if (!model || !Array.isArray(list)) continue;
951
+ const cleaned = [];
952
+ for (const entry of list) {
953
+ const sample = sanitizeSample(entry);
954
+ if (sample) cleaned.push(sample);
955
+ }
956
+ samples.set(model, cleaned);
957
+ }
958
+ const complete = parsed.complete === true;
959
+ const cursor = typeof parsed.cursor === "string" && parsed.cursor.length > 0 ? parsed.cursor : void 0;
960
+ return { samples, at: parsed.at, complete, cursor: complete ? void 0 : cursor };
961
+ } catch {
962
+ return null;
963
+ }
964
+ }
965
+ async function readSpeedSamplesSnapshot(cachePath, options) {
966
+ const maxAgeMs = isFiniteNumber(options.maxAgeMs) ? options.maxAgeMs : SPEED_SAMPLE_STALE_SNAPSHOT_MAX_MS;
967
+ const parsed = await parseCacheFile(cachePath, options.userId);
968
+ if (!parsed || !parsed.complete) return null;
969
+ const age = options.now - parsed.at;
970
+ if (age < 0 || age >= maxAgeMs) return null;
971
+ return { samples: parsed.samples, ageMs: age };
972
+ }
973
+ async function readSpeedSamplesProgress(cachePath, userId) {
974
+ const parsed = await parseCacheFile(cachePath, userId);
975
+ if (!parsed) return null;
976
+ return {
977
+ samples: parsed.samples,
978
+ at: parsed.at,
979
+ complete: parsed.complete,
980
+ ...parsed.cursor === void 0 ? {} : { cursor: parsed.cursor }
981
+ };
982
+ }
983
+ function resolveSpeedSamplesProgressPath(cachePath) {
984
+ return `${cachePath}.progress`;
985
+ }
986
+ async function writeSpeedSamplesCache(cachePath, payload) {
987
+ try {
988
+ const fs = await import("node:fs/promises");
989
+ const path = await import("node:path");
990
+ await fs.mkdir(path.dirname(cachePath), { recursive: true });
991
+ const tmpPath = `${cachePath}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
992
+ await fs.writeFile(tmpPath, JSON.stringify(payload), "utf8");
993
+ await fs.rename(tmpPath, cachePath);
994
+ } catch {
995
+ }
996
+ }
997
+
998
+ // packages/ai/agent/candidateSpeedContext.ts
999
+ var OBSERVED_SPEED_WINDOW = 50;
1000
+ var MIN_OBSERVED_FIRST_OUTPUT_SAMPLES = 5;
1001
+ var SPEED_SAMPLES_CACHE_TTL_MS = 5 * 6e4;
1002
+ var SPEED_SAMPLES_CACHE_MAX_ENTRIES = 500;
1003
+ function normalizeSpeedModelName(raw) {
1004
+ const name = raw.trim().toLowerCase();
1005
+ const slash = name.lastIndexOf("/");
1006
+ return slash === -1 ? name : name.slice(slash + 1);
1007
+ }
1008
+ var isFiniteNumber2 = (value) => typeof value === "number" && Number.isFinite(value);
1009
+ var REASONING_EFFORT_SUFFIXES = ["minimal", "low", "medium", "high", "xhigh"];
1010
+ var REASONING_EFFORT_SUFFIX_RE = new RegExp(`-(?:${REASONING_EFFORT_SUFFIXES.join("|")})$`);
1011
+ function stripReasoningEffortSuffix(model) {
1012
+ const base = model.replace(REASONING_EFFORT_SUFFIX_RE, "");
1013
+ return base && base !== model ? base : null;
1014
+ }
1015
+ function resolveOneBare(model, samplesByModel) {
1016
+ const observed = resolveObservedSpeed(samplesByModel.get(model) ?? [], {
1017
+ limit: OBSERVED_SPEED_WINDOW
1018
+ });
1019
+ if (observed.firstOutputSampleCount >= MIN_OBSERVED_FIRST_OUTPUT_SAMPLES && observed.medianFirstOutputMs !== void 0) {
1020
+ return {
1021
+ source: "observed",
1022
+ firstOutputMs: observed.medianFirstOutputMs,
1023
+ ...observed.medianOutputTokensPerSecond !== void 0 ? { outputTps: observed.medianOutputTokensPerSecond } : {},
1024
+ firstOutputSamples: observed.firstOutputSampleCount,
1025
+ tpsSamples: observed.throughputSampleCount
1026
+ };
1027
+ }
1028
+ return null;
1029
+ }
1030
+ function resolveOne(model, samplesByModel) {
1031
+ const direct = resolveOneBare(model, samplesByModel);
1032
+ if (direct) return { model, ...direct };
1033
+ const base = stripReasoningEffortSuffix(model);
1034
+ if (!base) return null;
1035
+ const stripped = resolveOneBare(base, samplesByModel);
1036
+ return stripped ? { model, ...stripped } : null;
1037
+ }
1038
+ function resolveCandidateSpeedFacts(models, samplesByModel) {
1039
+ const unique = [
1040
+ ...new Set(
1041
+ models.filter((model) => typeof model === "string").map(normalizeSpeedModelName).filter(Boolean)
1042
+ )
1043
+ ];
1044
+ return unique.map((model) => resolveOne(model, samplesByModel)).filter((fact) => fact !== null);
1045
+ }
1046
+ var formatSeconds = (ms) => `${(ms / 1e3).toFixed(1)}s`;
1047
+ var formatTps = (tps) => String(Math.round(tps));
1048
+ var SPEED_CONTEXT_HEADER = "speed (observed=\u672C\u7528\u6237\u5B9E\u6D4B\u8C03\u7528\u4E2D\u4F4D\u6570, firstOutput \u542B\u63A8\u7406\u8F93\u51FA; tps=generation\uFF08\u4E0D\u542B\u7AEF\u5230\u7AEF\u53E3\u5F84\uFF09, tps=n/a \u8868\u793A\u65E0\u53EF\u4FE1\u541E\u5410\u6837\u672C\u3002\u672A\u5217\u51FA\u7684 model \u8868\u793A\u6CA1\u6709\u5B9E\u6D4B\u6837\u672C\uFF0C\u4E0D\u4EE3\u8868\u6162):";
1049
+ function formatSnapshotAge(ageMs) {
1050
+ const minutes = Math.floor(ageMs / 6e4);
1051
+ if (minutes < 1) return "<1min";
1052
+ if (minutes < 60) return `${minutes}min`;
1053
+ const hours = Math.floor(minutes / 60);
1054
+ if (hours < 24) return `${hours}h`;
1055
+ return `${Math.floor(hours / 24)}d`;
1056
+ }
1057
+ function formatCandidateSpeedFacts(facts, options = {}) {
1058
+ if (facts.length === 0) return null;
1059
+ const lines = facts.map((fact) => {
1060
+ const tps = fact.outputTps !== void 0 ? formatTps(fact.outputTps) : "n/a";
1061
+ return ` ${fact.model}: firstOutput=${formatSeconds(fact.firstOutputMs ?? 0)} tps=${tps} [observed n=${fact.firstOutputSamples ?? 0} tpsN=${fact.tpsSamples ?? 0}]`;
1062
+ });
1063
+ const age = options.snapshotAgeMs;
1064
+ const note = typeof age === "number" && age > 0 ? ` (snapshot=${formatSnapshotAge(age)}\u524D\u91C7\u96C6\u7684\u5B8C\u6574\u7A97\u53E3, \u975E\u672C\u6B21\u5B9E\u65F6\u626B\u63CF)` : "";
1065
+ return `${SPEED_CONTEXT_HEADER}${note}
1066
+ ${lines.join("\n")}`;
1067
+ }
1068
+ function buildCandidateSpeedContext(models, samplesByModel, options = {}) {
1069
+ return formatCandidateSpeedFacts(resolveCandidateSpeedFacts(models, samplesByModel), options);
1070
+ }
1071
+ var SPEED_SAMPLE_PAGE_SIZE = 2e3;
1072
+ var DISPATCH_ENTRY_PATH = "agent-run";
1073
+ var eventTime = (value) => {
1074
+ if (isFiniteNumber2(value.timestamp)) return value.timestamp;
1075
+ if (isFiniteNumber2(value.createdAt)) return value.createdAt;
1076
+ return 0;
1077
+ };
1078
+ function collectSample(collected, value) {
1079
+ if (typeof value.model !== "string") return;
1080
+ if (!isFiniteNumber2(value.firstOutputMs) && !isFiniteNumber2(value.callDurationMs)) return;
1081
+ const model = normalizeSpeedModelName(value.model);
1082
+ if (!model) return;
1083
+ const list = collected.get(model) ?? [];
1084
+ list.push({
1085
+ t: eventTime(value),
1086
+ firstOutputMs: value.firstOutputMs,
1087
+ callDurationMs: value.callDurationMs,
1088
+ output_tokens: value.output_tokens
1089
+ });
1090
+ collected.set(model, list);
1091
+ }
1092
+ function finalizeSamples(collected, keepTime = false) {
1093
+ const result = /* @__PURE__ */ new Map();
1094
+ for (const [model, list] of collected) {
1095
+ list.sort((a, b) => b.t - a.t);
1096
+ const window = list.slice(0, OBSERVED_SPEED_WINDOW);
1097
+ result.set(
1098
+ model,
1099
+ keepTime ? window : window.map(({ t: _t, ...sample }) => sample)
1100
+ );
1101
+ }
1102
+ return result;
1103
+ }
1104
+ async function collectRecentSpeedSamples(db, userId, options = {}) {
1105
+ const pageSize = isFiniteNumber2(options.pageSize) && options.pageSize > 0 ? Math.floor(options.pageSize) : SPEED_SAMPLE_PAGE_SIZE;
1106
+ const budgetMs = isFiniteNumber2(options.budgetMs) ? options.budgetMs : Number.POSITIVE_INFINITY;
1107
+ const { start, end } = createTokenKey.rangeOfUser(userId);
1108
+ const failedPrefix = createKey("token", userId, "failed-call", "");
1109
+ const dispatchRunCache = /* @__PURE__ */ new Map();
1110
+ const isDispatchSampleRecord = async (record2, resolver, cache) => {
1111
+ if (record2.entry_path !== DISPATCH_ENTRY_PATH && record2.entry_path !== "cli-local") return false;
1112
+ const runId = typeof record2.dialogId === "string" ? record2.dialogId.trim() : "";
1113
+ if (!runId) return false;
1114
+ const cacheKey = `${record2.entry_path}:${runId}`;
1115
+ const cached = cache.get(cacheKey);
1116
+ if (cached !== void 0) return cached;
1117
+ let dispatch = false;
1118
+ if (resolver) {
1119
+ try {
1120
+ dispatch = await resolver(runId, record2.entry_path) === true;
1121
+ } catch {
1122
+ dispatch = false;
1123
+ }
1124
+ }
1125
+ cache.set(cacheKey, dispatch);
1126
+ return dispatch;
1127
+ };
1128
+ const collected = /* @__PURE__ */ new Map();
1129
+ const startedAt = Date.now();
1130
+ let lastKey = options.startAfter;
1131
+ let budgetExhausted = false;
1132
+ let scanned = 0;
1133
+ while (true) {
1134
+ if (Date.now() - startedAt >= budgetMs) {
1135
+ budgetExhausted = true;
1136
+ break;
1137
+ }
1138
+ const pageOptions = {
1139
+ ...lastKey === void 0 ? { gte: start } : { gt: lastKey },
1140
+ lte: end,
1141
+ limit: pageSize
1142
+ };
1143
+ let accepted = 0;
1144
+ let newestKey = lastKey;
1145
+ for await (const [key, raw] of db.iterator(pageOptions)) {
1146
+ if (typeof key !== "string") continue;
1147
+ if (lastKey !== void 0 && key <= lastKey) continue;
1148
+ accepted += 1;
1149
+ scanned += 1;
1150
+ newestKey = key;
1151
+ if (key.startsWith(failedPrefix)) continue;
1152
+ if (!raw || typeof raw !== "object") continue;
1153
+ const record2 = raw;
1154
+ const resolver = options.isDispatchRun ?? db.isDispatchRun;
1155
+ if (!await isDispatchSampleRecord(
1156
+ record2,
1157
+ resolver ? (runId, entryPath) => resolver.call(db, runId, entryPath) : void 0,
1158
+ dispatchRunCache
1159
+ ))
1160
+ continue;
1161
+ collectSample(collected, record2);
1162
+ }
1163
+ if (accepted === 0 || accepted < pageSize) break;
1164
+ lastKey = newestKey;
1165
+ }
1166
+ return {
1167
+ samples: finalizeSamples(collected, options.keepTime === true),
1168
+ budgetExhausted,
1169
+ scanned,
1170
+ ...budgetExhausted && lastKey !== void 0 ? { nextCursor: lastKey } : {}
1171
+ };
1172
+ }
1173
+ function mergeNewestSamples(into, from) {
1174
+ for (const [model, list] of from) {
1175
+ const merged = [...into.get(model) ?? [], ...list];
1176
+ merged.sort(
1177
+ (a, b) => (b.t ?? 0) - (a.t ?? 0)
1178
+ );
1179
+ into.set(model, merged.slice(0, OBSERVED_SPEED_WINDOW));
1180
+ }
1181
+ }
1182
+ async function loadSpeedSamplesWithDiskCache(db, userId, now, cache) {
1183
+ try {
1184
+ const ttlMs = isFiniteNumber2(cache.ttlMs) ? cache.ttlMs : SPEED_SAMPLE_DISK_CACHE_TTL_MS;
1185
+ const snapshot = await readSpeedSamplesSnapshot(cache.cachePath, { userId, now });
1186
+ if (snapshot && snapshot.ageMs < ttlMs) return { samples: snapshot.samples };
1187
+ const progressPath = resolveSpeedSamplesProgressPath(cache.cachePath);
1188
+ const progress = await readSpeedSamplesProgress(progressPath, userId);
1189
+ const resumable = progress && !progress.complete && progress.cursor ? progress : void 0;
1190
+ const collected = new Map(resumable?.samples ?? []);
1191
+ let step;
1192
+ try {
1193
+ step = await collectRecentSpeedSamples(db, userId, {
1194
+ pageSize: cache.pageSize,
1195
+ budgetMs: isFiniteNumber2(cache.budgetMs) ? cache.budgetMs : SPEED_SAMPLE_SCAN_BUDGET_MS,
1196
+ keepTime: true,
1197
+ ...resumable?.cursor ? { startAfter: resumable.cursor } : {}
1198
+ });
1199
+ } catch {
1200
+ return snapshot ? { samples: snapshot.samples, snapshotAgeMs: snapshot.ageMs } : { samples: /* @__PURE__ */ new Map() };
1201
+ }
1202
+ if (!resumable && step.scanned === 0 && !step.budgetExhausted) {
1203
+ return snapshot ? { samples: snapshot.samples, snapshotAgeMs: snapshot.ageMs } : { samples: /* @__PURE__ */ new Map() };
1204
+ }
1205
+ mergeNewestSamples(collected, step.samples);
1206
+ if (!step.budgetExhausted) {
1207
+ await writeSpeedSamplesCache(cache.cachePath, {
1208
+ version: SPEED_SAMPLE_CACHE_VERSION,
1209
+ userId,
1210
+ at: now,
1211
+ complete: true,
1212
+ samples: Object.fromEntries(collected)
1213
+ });
1214
+ await writeSpeedSamplesCache(progressPath, {
1215
+ version: SPEED_SAMPLE_CACHE_VERSION,
1216
+ userId,
1217
+ at: now,
1218
+ complete: true,
1219
+ samples: {}
1220
+ });
1221
+ return { samples: collected };
1222
+ }
1223
+ await writeSpeedSamplesCache(progressPath, {
1224
+ version: SPEED_SAMPLE_CACHE_VERSION,
1225
+ userId,
1226
+ // Progress keeps the cycle's collection start so a later stale label stays honest.
1227
+ at: resumable?.at ?? now,
1228
+ complete: false,
1229
+ samples: Object.fromEntries(collected),
1230
+ ...step.nextCursor ? { cursor: step.nextCursor } : {}
1231
+ });
1232
+ return snapshot ? { samples: snapshot.samples, snapshotAgeMs: snapshot.ageMs } : { samples: /* @__PURE__ */ new Map() };
1233
+ } catch {
1234
+ return { samples: /* @__PURE__ */ new Map() };
1235
+ }
1236
+ }
1237
+ var samplesCache = /* @__PURE__ */ new Map();
1238
+ function writeSamplesCache(userId, now, samples) {
1239
+ for (const [key, entry] of samplesCache) {
1240
+ if (now - entry.at >= SPEED_SAMPLES_CACHE_TTL_MS) samplesCache.delete(key);
1241
+ }
1242
+ samplesCache.delete(userId);
1243
+ samplesCache.set(userId, { at: now, samples });
1244
+ while (samplesCache.size > SPEED_SAMPLES_CACHE_MAX_ENTRIES) {
1245
+ const oldest = samplesCache.keys().next().value;
1246
+ if (oldest === void 0) break;
1247
+ samplesCache.delete(oldest);
1248
+ }
1249
+ }
1250
+ var SPEED_SAMPLE_REFRESH_BUDGET_MS = 6e4;
1251
+ var snapshotRefreshes = /* @__PURE__ */ new Map();
1252
+ function startSpeedSnapshotRefresh(db, userId, now = Date.now()) {
1253
+ const inFlight = snapshotRefreshes.get(userId);
1254
+ if (inFlight) return inFlight;
1255
+ const job = (async () => {
1256
+ try {
1257
+ const { samples, budgetExhausted } = await collectRecentSpeedSamples(db, userId, {
1258
+ budgetMs: SPEED_SAMPLE_REFRESH_BUDGET_MS
1259
+ });
1260
+ if (!budgetExhausted) writeSamplesCache(userId, now, samples);
1261
+ } catch {
1262
+ }
1263
+ })().finally(() => {
1264
+ snapshotRefreshes.delete(userId);
1265
+ });
1266
+ snapshotRefreshes.set(userId, job);
1267
+ return job;
1268
+ }
1269
+ async function loadCachedSpeedSamples(db, userId, now) {
1270
+ const hit = samplesCache.get(userId);
1271
+ if (hit) {
1272
+ const age = now - hit.at;
1273
+ if (age >= 0 && age < SPEED_SAMPLE_STALE_SNAPSHOT_MAX_MS) {
1274
+ if (age >= SPEED_SAMPLES_CACHE_TTL_MS) void startSpeedSnapshotRefresh(db, userId);
1275
+ return age >= SPEED_SAMPLES_CACHE_TTL_MS ? { samples: hit.samples, snapshotAgeMs: age } : { samples: hit.samples };
1276
+ }
1277
+ }
1278
+ void startSpeedSnapshotRefresh(db, userId);
1279
+ return { samples: /* @__PURE__ */ new Map() };
1280
+ }
1281
+ async function injectSpeedContextIntoListAgentsResult(result, options = {}) {
1282
+ try {
1283
+ let parsed;
1284
+ try {
1285
+ parsed = JSON.parse(result);
1286
+ } catch {
1287
+ return result;
1288
+ }
1289
+ if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.agents)) return result;
1290
+ const models = parsed.agents.map((agent) => agent?.model).filter((model) => typeof model === "string");
1291
+ if (models.length === 0 && !options.compactPage) return result;
1292
+ const now = options.now ?? Date.now();
1293
+ let samples = /* @__PURE__ */ new Map();
1294
+ let snapshotAgeMs;
1295
+ const userId = typeof options.userId === "string" ? options.userId.trim() : "";
1296
+ if (options.db && userId) {
1297
+ try {
1298
+ const loaded = options.diskCache ? await loadSpeedSamplesWithDiskCache(options.db, userId, now, options.diskCache) : await loadCachedSpeedSamples(options.db, userId, now);
1299
+ samples = loaded.samples;
1300
+ snapshotAgeMs = loaded.snapshotAgeMs;
1301
+ } catch {
1302
+ samples = /* @__PURE__ */ new Map();
1303
+ }
1304
+ }
1305
+ if (options.compactPage) {
1306
+ return await serializeCompactAgentPage(parsed, samples, snapshotAgeMs, options);
1307
+ }
1308
+ const speedContext = buildCandidateSpeedContext(models, samples, { snapshotAgeMs });
1309
+ return speedContext ? JSON.stringify({ ...parsed, speedContext }) : result;
1310
+ } catch {
1311
+ return options.compactPage ? JSON.stringify({ success: false, error: "LIST_AGENTS_PAGE_SERIALIZATION_FAILED" }) : result;
1312
+ }
1313
+ }
1314
+ async function serializeCompactAgentPage(parsed, samples, snapshotAgeMs, options) {
1315
+ const maxChars = LIST_AGENTS_PAGE_BUDGET;
1316
+ const maxBytes = LIST_AGENTS_PAGE_BUDGET;
1317
+ const fits = (page) => page.length <= maxChars && new TextEncoder().encode(page).length <= maxBytes;
1318
+ const offset = typeof parsed.offset === "number" ? parsed.offset : 0;
1319
+ const candidates = parsed.agents;
1320
+ const availableCount = typeof parsed.availableCount === "number" ? parsed.availableCount : parsed.total;
1321
+ const groups = Array.isArray(parsed.credentialGroups) ? parsed.credentialGroups : [];
1322
+ if (options.fragmentOffset !== void 0) {
1323
+ const fragmentOffset = Number(options.fragmentOffset);
1324
+ const agentKey2 = candidates[0]?.agentKey;
1325
+ if (typeof options.fragmentOffset !== "number" && (typeof options.fragmentOffset !== "string" || !/^\d+$/.test(options.fragmentOffset)) || !Number.isSafeInteger(fragmentOffset) || fragmentOffset < 0 || typeof agentKey2 !== "string" || agentKey2 !== options.fragmentAgentKey) {
1326
+ return JSON.stringify({ success: false, error: "LIST_AGENTS_FRAGMENT_INVALID", offset });
1327
+ }
1328
+ const agent = candidates[0];
1329
+ const speedContext = buildCandidateSpeedContext(typeof agent.model === "string" ? [agent.model] : [], samples, { snapshotAgeMs });
1330
+ const payload = { agent, credentialGroups: groups.filter((group) => group.credentialGroup === agent.credentialGroup) };
1331
+ let keyCollision = false;
1332
+ const cleanText = (value) => scrubSecrets(sanitizeToolOutputText(value)).cleaned;
1333
+ const sanitize = (value) => {
1334
+ if (typeof value === "string") return cleanText(value);
1335
+ if (Array.isArray(value)) return value.map(sanitize);
1336
+ if (value && typeof value === "object") {
1337
+ const entries = [];
1338
+ const keys = /* @__PURE__ */ new Set();
1339
+ for (const [key, item] of Object.entries(value)) {
1340
+ const cleanedKey = cleanText(key);
1341
+ if (keys.has(cleanedKey)) keyCollision = true;
1342
+ keys.add(cleanedKey);
1343
+ entries.push([cleanedKey, sanitize(item)]);
1344
+ }
1345
+ return Object.fromEntries(entries);
1346
+ }
1347
+ return value;
1348
+ };
1349
+ const safePayload = sanitize(payload);
1350
+ if (keyCollision) return JSON.stringify({ success: false, error: "LIST_AGENTS_SANITIZED_KEY_COLLISION", offset });
1351
+ const serialized = JSON.stringify(safePayload);
1352
+ const bytes = new TextEncoder().encode(serialized);
1353
+ const hash = await globalThis.crypto.subtle.digest("SHA-256", bytes);
1354
+ const digest = Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, "0")).join("");
1355
+ if (fragmentOffset > 0 && !options.fragmentDigest || options.fragmentDigest && options.fragmentDigest !== digest) {
1356
+ return JSON.stringify({ success: false, error: "LIST_AGENTS_FRAGMENT_CHANGED", offset });
1357
+ }
1358
+ if (fragmentOffset >= serialized.length) return JSON.stringify({ success: false, error: "LIST_AGENTS_FRAGMENT_INVALID", offset });
1359
+ if (fragmentOffset > 0 && /[\uDC00-\uDFFF]/.test(serialized[fragmentOffset]) && /[\uD800-\uDBFF]/.test(serialized[fragmentOffset - 1])) return JSON.stringify({ success: false, error: "LIST_AGENTS_FRAGMENT_INVALID", offset });
1360
+ let end = Math.min(serialized.length, fragmentOffset + 3e3);
1361
+ if (end < serialized.length && /[\uD800-\uDBFF]/.test(serialized[end - 1]) && /[\uDC00-\uDFFF]/.test(serialized[end])) end--;
1362
+ const fragment = serialized.slice(fragmentOffset, end);
1363
+ const result = JSON.stringify({ success: true, agentKey: agentKey2, offset, digest, fragment, fragmentOffset, nextFragmentOffset: end, hasMoreFragments: end < serialized.length, nextOffset: offset + 1, ...speedContext ? { speedContext: cleanText(speedContext) } : {} });
1364
+ return fits(result) ? result : JSON.stringify({ success: false, error: "LIST_AGENTS_FRAGMENT_METADATA_TOO_LARGE", offset });
1365
+ }
1366
+ const makePage = (count) => {
1367
+ const agents = candidates.slice(0, count);
1368
+ const groupKeys = new Set(agents.map((agent) => agent.credentialGroup).filter(Boolean));
1369
+ const speedContext = buildCandidateSpeedContext(agents.map((agent) => agent.model).filter((model) => typeof model === "string"), samples, { snapshotAgeMs });
1370
+ const nextOffset = offset + count;
1371
+ const hasMore = nextOffset < availableCount;
1372
+ return JSON.stringify({
1373
+ ...parsed,
1374
+ offset,
1375
+ agents,
1376
+ credentialGroups: groups.filter((group) => groupKeys.has(group.credentialGroup)),
1377
+ hasMore,
1378
+ ...hasMore ? { nextOffset } : {},
1379
+ ...speedContext ? { speedContext } : {}
1380
+ });
1381
+ };
1382
+ if (!candidates.length) {
1383
+ const empty = makePage(0);
1384
+ if (fits(empty)) return empty;
1385
+ } else {
1386
+ let best;
1387
+ for (let count = 1; count <= candidates.length; count++) {
1388
+ const page = makePage(count);
1389
+ if (!fits(page)) break;
1390
+ best = page;
1391
+ }
1392
+ if (best) return best;
1393
+ }
1394
+ const agentKey = typeof candidates[0]?.agentKey === "string" ? candidates[0].agentKey : void 0;
1395
+ const error = {
1396
+ success: false,
1397
+ error: candidates.length ? "LIST_AGENTS_CANDIDATE_TOO_LARGE" : "LIST_AGENTS_PAGE_METADATA_TOO_LARGE",
1398
+ offset,
1399
+ ...agentKey ? { agentKey, recovery: {
1400
+ tool: "listAgents",
1401
+ arguments: { compact: true, offset, fragmentOffset: 0, fragmentAgentKey: agentKey },
1402
+ note: "Repeat with the same filters and returned digest and nextFragmentOffset; concatenate fragments and parse JSON before continuing at nextOffset."
1403
+ } } : {},
1404
+ ...candidates.length ? { nextOffset: offset + 1, truncated: parsed.truncated === true, poolComplete: parsed.planningRecommendation?.poolComplete === true, hasMore: offset + 1 < availableCount } : {}
1405
+ };
1406
+ const encoded = JSON.stringify(error);
1407
+ return fits(encoded) ? encoded : JSON.stringify({ success: false, error: "LIST_AGENTS_RECOVERY_ID_TOO_LARGE", offset });
1408
+ }
1409
+
1410
+ // packages/ai/agent/dispatchSpeedProvenance.ts
1411
+ var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
1412
+ function isServerDispatchSpeedSource(value, dialogId, userId) {
1413
+ const dialog = record(value);
1414
+ const proof = record(dialog.dispatchSpeedProvenance);
1415
+ return proof.version === 1 && proof.source === "server-startAgentRun" && proof.userId === userId && record(dialog.runtimeBinding).tenantUserId === userId && dialog.id === dialogId;
1416
+ }
1417
+ function isLocalDispatchSpeedSource(value, dialogId, userId) {
1418
+ const run = record(value);
1419
+ const proof = record(run.dispatchSpeedProvenance);
1420
+ return proof.version === 1 && proof.source === "cli-startAgentRun" && proof.userId === userId && typeof run.runId === "string" && run.runId.length > 0 && run.dialogId === dialogId && run.ephemeral !== true;
1421
+ }
1422
+
1423
+ export {
1424
+ isGptProModel,
1425
+ shouldBlockForGptPro,
1426
+ isPlatformPaidAgentCall,
1427
+ deriveCredentialGroup,
1428
+ deriveCustomProviderCredentialGroup,
1429
+ summarizeCredentialGroups,
1430
+ resolveDiscoveryScope,
1431
+ resolvePaginationArgs,
1432
+ matchesAgentQuery,
1433
+ buildAgentDiscoveryResult,
1434
+ toDiscoverySafeAgentSummary,
1435
+ injectSpeedContextIntoListAgentsResult,
1436
+ isServerDispatchSpeedSource,
1437
+ isLocalDispatchSpeedSource
1438
+ };