nolo-cli 0.264.0-alpha.2 → 0.266.0-alpha.1

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 (538) hide show
  1. package/{chunk-LXP53WGF.js → chunk-05wkntba.js} +44 -40
  2. package/{chunk-XFYFMTOM.js → chunk-08ts2q1n.js} +9 -11
  3. package/{chromeCommands-MVEEIY4R.js → chunk-0a3m1n6h.js} +182 -238
  4. package/chunk-0gfvc7g8.js +13 -0
  5. package/{chunk-CF7PE763.js → chunk-0h0sncy4.js} +3 -4
  6. package/{chunk-3UH7SS4W.js → chunk-0nsxwrge.js} +232 -241
  7. package/chunk-0ra8cne4.js +11 -0
  8. package/{chunk-MRACVEPZ.js → chunk-0sgwk7am.js} +1 -3
  9. package/{chunk-PEXGRTTQ.js → chunk-0tsfn0dk.js} +44 -45
  10. package/{chunk-WOAZVUSN.js → chunk-0y8cbwzy.js} +26 -30
  11. package/chunk-12gz55kk.js +6 -0
  12. package/{chunk-GLKOYSRU.js → chunk-186gshgw.js} +3 -6
  13. package/chunk-19w4ss38.js +44 -0
  14. package/{chunk-RF576RYE.js → chunk-1cakzp6r.js} +23 -23
  15. package/chunk-1fbfwbzp.js +27 -0
  16. package/{chunk-4IVMDQBA.js → chunk-1fv9k8zt.js} +103 -68
  17. package/{chunk-Q5FJJ6XI.js → chunk-1js4cdzp.js} +11 -19
  18. package/{chunk-YECCIUYU.js → chunk-1nhx0er5.js} +63 -63
  19. package/chunk-1p152b7g.js +12 -0
  20. package/{chunk-HXEO5DNV.js → chunk-1ynbq3yr.js} +322 -353
  21. package/{chunk-6UBGXX2W.js → chunk-1zrg4h5n.js} +3 -4
  22. package/{chunk-Y5GCAMGP.js → chunk-2g6zsfq8.js} +1 -3
  23. package/chunk-2hekb0eh.js +17 -0
  24. package/chunk-2pj6qzq5.js +12 -0
  25. package/chunk-2tvd4jyp.js +226 -0
  26. package/chunk-2ygg7azv.js +846 -0
  27. package/chunk-33405wtv.js +50 -0
  28. package/chunk-34axejtd.js +30 -0
  29. package/{tableCommands-FCPDULSU.js → chunk-3700dvt3.js} +224 -276
  30. package/{pdf-KE3QI2V7.js → chunk-3j08t1nm.js} +12505 -10133
  31. package/chunk-3j9gq18v.js +111 -0
  32. package/{chunk-LYPJYBE5.js → chunk-3qfpcdkm.js} +486 -505
  33. package/{settingThunks-PNC7ZISV.js → chunk-3r2x7h64.js} +189 -272
  34. package/{agentGrantCommands-2VLLXGIU.js → chunk-3tbj5fxt.js} +61 -56
  35. package/chunk-40whhjj5.js +168 -0
  36. package/chunk-4301919y.js +7 -0
  37. package/chunk-43adz39e.js +77 -0
  38. package/{chunk-5ZUL4CUO.js → chunk-49v3zc4g.js} +1 -3
  39. package/chunk-4dd7mxkb.js +72 -0
  40. package/{chunk-BKP325XS.js → chunk-4hapfzpq.js} +66 -62
  41. package/chunk-4mm7dz0m.js +95 -0
  42. package/chunk-4pqxempz.js +440 -0
  43. package/chunk-4x9zf5pv.js +10 -0
  44. package/{chunk-CA7LGAHV.js → chunk-511q8qzv.js} +66 -57
  45. package/{chunk-U7OULUMF.js → chunk-53v9g0np.js} +49 -64
  46. package/chunk-572mg6q5.js +19 -0
  47. package/{chunk-QAW6BEWQ.js → chunk-57eyhmwr.js} +17173 -16165
  48. package/chunk-5hsr0zjm.js +156 -0
  49. package/chunk-5k883yyd.js +20 -0
  50. package/chunk-5m0wsee4.js +639 -0
  51. package/{memberThunks-NEZRAW5K.js → chunk-5r1sq2gt.js} +299 -373
  52. package/chunk-648rq4np.js +255 -0
  53. package/{chunk-IYRZKHA6.js → chunk-666yjw5c.js} +63 -86
  54. package/{chunk-4O22PGNQ.js → chunk-6cdcbmtp.js} +19 -19
  55. package/chunk-6dbyqcf7.js +59 -0
  56. package/{agentProviderCommands-2W3VXDLV.js → chunk-6e8mgp1x.js} +82 -105
  57. package/chunk-6n0pw7sx.js +44 -0
  58. package/chunk-6q1b7381.js +361 -0
  59. package/chunk-6sj756ry.js +23 -0
  60. package/{chunk-4UNN45DS.js → chunk-6t7a7zck.js} +14785 -14454
  61. package/chunk-6yarwtxh.js +776 -0
  62. package/chunk-708h542p.js +18 -0
  63. package/chunk-76f076t8.js +266 -0
  64. package/chunk-782rrrwv.js +523 -0
  65. package/{workloadLifecycle-P2SJVV3S.js → chunk-7gk330wp.js} +77 -84
  66. package/{chunk-EZKIRVLJ.js → chunk-7ks60vxy.js} +146 -128
  67. package/{chunk-FI4DPLR7.js → chunk-7mrqbxe8.js} +342 -228
  68. package/chunk-7sztayrd.js +169 -0
  69. package/chunk-7vgt2mxz.js +15 -0
  70. package/{localFirstLog-OIETGK66.js → chunk-7z8y4k6y.js} +0 -2
  71. package/{chunk-KDDXC2IH.js → chunk-82htft2m.js} +49 -11
  72. package/{updateDialogTitleAction-XOSLNRT3.js → chunk-88vrtxxg.js} +65 -137
  73. package/{chunk-LS5KAVFQ.js → chunk-8dtjbp79.js} +293 -229
  74. package/chunk-8fajbkaz.js +50 -0
  75. package/chunk-8m1ebxpw.js +65 -0
  76. package/{accountResolver-JYG5L7YP.js → chunk-8mgfeg0w.js} +37 -30
  77. package/{chunk-LPXBBC32.js → chunk-8myksy35.js} +156 -160
  78. package/{chunk-BMQ2MJUK.js → chunk-8nrj7dc7.js} +75 -66
  79. package/{commandRegistry-ENNFT77C.js → chunk-8t8x64ec.js} +228 -286
  80. package/chunk-8yj4pq79.js +458 -0
  81. package/{chunk-5MKPNTJP.js → chunk-8z6pepcx.js} +43 -48
  82. package/{chunk-UYQILGDR.js → chunk-90egc9vb.js} +122 -102
  83. package/{chunk-EODBQPRM.js → chunk-91q5dc5r.js} +10 -14
  84. package/{chunk-U6VC4MU4.js → chunk-96jtrqk1.js} +2 -4
  85. package/{chunk-H57T64RA.js → chunk-996j61av.js} +28 -31
  86. package/{chunk-Q6FKWH66.js → chunk-9cxgb9jy.js} +137 -243
  87. package/{chunk-2ZBPWX7N.js → chunk-9q1gbmet.js} +62 -104
  88. package/chunk-9qtjh73q.js +344 -0
  89. package/{chunk-SR57FDTX.js → chunk-9raka469.js} +72 -155
  90. package/{chunk-V6K5U4YE.js → chunk-9vh4v046.js} +32 -41
  91. package/{chunk-AGIM7IMJ.js → chunk-9yr1fy7j.js} +14 -49
  92. package/{chunk-FGFJUFPS.js → chunk-a16x0wt6.js} +11 -18
  93. package/chunk-a5b2rvzs.js +131 -0
  94. package/{chunk-7DPNBQSV.js → chunk-a7bz6nc3.js} +3 -4
  95. package/chunk-ac85azv9.js +29 -0
  96. package/{chunk-VXL2FZTP.js → chunk-ahhbkad4.js} +16 -20
  97. package/{chunk-37DGW762.js → chunk-anhksj2j.js} +16 -29
  98. package/{cliAuthorityBrokerServer-27C5YBYP.js → chunk-atvmx76t.js} +180 -186
  99. package/{chunk-E6A5NHDH.js → chunk-av2mzeqz.js} +16 -17
  100. package/chunk-avbwrb0z.js +614 -0
  101. package/chunk-avr6rqe5.js +544 -0
  102. package/{workContextQueryProjection-CACY5VFE.js → chunk-axx60d5a.js} +7 -7
  103. package/{chunk-EWQ3HGNZ.js → chunk-b00vzjkb.js} +30 -23
  104. package/chunk-b0m6ezxr.js +132 -0
  105. package/chunk-bbd5mgdt.js +47 -0
  106. package/chunk-bcecft0r.js +28 -0
  107. package/chunk-beyr4pyp.js +33 -0
  108. package/{chunk-BR3GT6MR.js → chunk-bge0cagn.js} +7 -18
  109. package/{offlineMarxistsAgentCommand-MFURGWHL.js → chunk-bh53zg3t.js} +33 -43
  110. package/chunk-bmx1cw89.js +37 -0
  111. package/chunk-br2195h4.js +22 -0
  112. package/chunk-bsqkwveq.js +56 -0
  113. package/{chunk-QAU6KM2U.js → chunk-c09s2z1m.js} +139 -98
  114. package/chunk-c235kypv.js +24636 -0
  115. package/{chunk-2JMYAH5O.js → chunk-c30j6pyh.js} +213 -256
  116. package/chunk-c3v6r6sq.js +29 -0
  117. package/{chunk-PDSXYHNI.js → chunk-c5z7qspt.js} +1177 -1196
  118. package/{chunk-GWB6AGME.js → chunk-c6jvz0mp.js} +34 -50
  119. package/{chunk-PRJ473FK.js → chunk-cd6h9qqs.js} +14 -12
  120. package/chunk-cdt0amyy.js +37 -0
  121. package/{chunk-2AJLG6PY.js → chunk-cfh6tfc3.js} +73 -86
  122. package/{chunk-WIVVNJUS.js → chunk-ch4ck1yz.js} +38 -68
  123. package/chunk-chtvrtp5.js +55 -0
  124. package/{chunk-EYLGAEB4.js → chunk-ckvz7abv.js} +170 -165
  125. package/{chunk-YZMNK53S.js → chunk-csf18m5w.js} +32 -25
  126. package/{chunk-C36L6ZID.js → chunk-cwnvf8dt.js} +2 -10
  127. package/chunk-cy7thb6n.js +19877 -0
  128. package/{dialogPortabilityCommands-YQJNB2KL.js → chunk-d61q9nah.js} +439 -487
  129. package/chunk-d6xdy0gp.js +142 -0
  130. package/{chunk-EBH4RFJ6.js → chunk-dh69vqbd.js} +6390 -6496
  131. package/{chunk-KJ4J2XQB.js → chunk-dj4ggbc6.js} +17 -19
  132. package/{chunk-LISC7BD4.js → chunk-djrrhbk3.js} +29 -37
  133. package/chunk-drqzzzvr.js +822 -0
  134. package/chunk-e1n7edjk.js +33 -0
  135. package/chunk-e3atr4hk.js +59 -0
  136. package/chunk-e9bn2aav.js +13 -0
  137. package/chunk-ed396rfq.js +87 -0
  138. package/chunk-eha8ggh6.js +10 -0
  139. package/{chunk-MALPQFGT.js → chunk-ek122zzt.js} +893 -948
  140. package/chunk-epnmvek4.js +22 -0
  141. package/{chunk-S25VJYXV.js → chunk-eqzvk3xm.js} +69 -80
  142. package/chunk-ex34n71b.js +2874 -0
  143. package/{chunk-56OAS5RZ.js → chunk-f3ad6q4h.js} +7 -11
  144. package/{chunk-3PVYUPXK.js → chunk-f8jepva1.js} +6 -7
  145. package/{chunk-GH34JXNV.js → chunk-f9yvy9t9.js} +114 -92
  146. package/chunk-fbdz4f0j.js +90 -0
  147. package/{chunk-J44TXB4J.js → chunk-fcsc2day.js} +216 -164
  148. package/chunk-fevdhnbh.js +19 -0
  149. package/chunk-fkrgqq8w.js +3300 -0
  150. package/{chunk-TSBJVMNW.js → chunk-fs3bvh2p.js} +42 -57
  151. package/chunk-fvwzyhah.js +134 -0
  152. package/chunk-g0mpxdp9.js +101 -0
  153. package/{chunk-LTQ6ECCF.js → chunk-g35f20d1.js} +450 -414
  154. package/{chunk-3L2WKC3W.js → chunk-g5fhtjqg.js} +13 -16
  155. package/{chunk-DBEOW57U.js → chunk-gcq01td7.js} +270 -227
  156. package/{chunk-ADMRXWXJ.js → chunk-ge97b11r.js} +121 -42
  157. package/chunk-ghjtgbkw.js +180 -0
  158. package/chunk-gkra36c1.js +16 -0
  159. package/chunk-gmz86t60.js +1000 -0
  160. package/{localDialogRead-GWGWSL5K.js → chunk-gszpesze.js} +5 -12
  161. package/chunk-gvsfec9m.js +16536 -0
  162. package/{chunk-QSJ3HFEF.js → chunk-h1hzmqph.js} +1 -3
  163. package/chunk-h30dg154.js +17 -0
  164. package/chunk-h3hkb7cw.js +241 -0
  165. package/chunk-h40py996.js +28 -0
  166. package/{chunk-47T3QP4V.js → chunk-h60gnewh.js} +112 -116
  167. package/{agentPullCommand-XEGOUYQT.js → chunk-hkwsv9xf.js} +33 -45
  168. package/chunk-hnyg0gwj.js +28 -0
  169. package/{chunk-KSV6T4AH.js → chunk-hqqqph5w.js} +12 -4
  170. package/{chunk-YQJEXXDK.js → chunk-hrngs1wy.js} +157 -246
  171. package/{chunk-LRLLWD4P.js → chunk-htf69s94.js} +14 -12
  172. package/chunk-j0yxesh3.js +83 -0
  173. package/{chunk-VF4K2QE6.js → chunk-j22t9g05.js} +3 -6
  174. package/{chunk-3R4AYHJR.js → chunk-j4a8m2zn.js} +5 -34
  175. package/chunk-j9p4jnwg.js +27 -0
  176. package/{chunk-R72QWIFO.js → chunk-jdycmfsm.js} +9 -9
  177. package/chunk-jdyvrne0.js +52 -0
  178. package/{spacePruneCommand-YKIEUIDQ.js → chunk-je0b66qf.js} +44 -62
  179. package/{chunk-HNMXYYJR.js → chunk-jec44fkj.js} +3 -4
  180. package/{chunk-526GLZJE.js → chunk-jf1ex00r.js} +107 -73
  181. package/chunk-jgqdec9b.js +31 -0
  182. package/{chunk-56GBUMO5.js → chunk-jkw9n4h5.js} +16 -25
  183. package/{chunk-7422ZLGL.js → chunk-jmnzdwjt.js} +867 -965
  184. package/chunk-jqq57s0a.js +58 -0
  185. package/{chunk-OKUSDVRS.js → chunk-jtkn5aj6.js} +27 -38
  186. package/chunk-jwvzn9r0.js +316 -0
  187. package/chunk-k1re0fc7.js +107 -0
  188. package/chunk-k2ep3rb2.js +103 -0
  189. package/{chunk-JEXVIMYZ.js → chunk-k6ycb24w.js} +5 -8
  190. package/{chunk-RI7SXDJW.js → chunk-kawvydbk.js} +383 -195
  191. package/chunk-kf2ghpzh.js +10 -0
  192. package/{chunk-S6FAHQDH.js → chunk-kgah9e46.js} +28 -59
  193. package/{chunk-T3MWVUBE.js → chunk-kjjepkvc.js} +71 -82
  194. package/chunk-kn4dgg4j.js +4113 -0
  195. package/{chunk-2LFYMWM3.js → chunk-kn5p91n8.js} +43 -53
  196. package/{chunk-MVOZ22RZ.js → chunk-kntqrbwc.js} +8 -12
  197. package/{chunk-I6YIA2TY.js → chunk-kq3vr7mx.js} +25 -20
  198. package/chunk-kz1x1d8n.js +15 -0
  199. package/{mcpLocalAuthorizeCommand-IKOFKY5U.js → chunk-m22e7tt2.js} +53 -71
  200. package/{chunk-ZNFJWEN4.js → chunk-m32rwr4d.js} +11 -8
  201. package/chunk-m39e9m18.js +93 -0
  202. package/{chunk-4D4QD7FT.js → chunk-m5518371.js} +64 -56
  203. package/{chunk-LHTXSC2E.js → chunk-mb5hnfyp.js} +9 -11
  204. package/chunk-mexet11v.js +11 -0
  205. package/chunk-mg2hgfgh.js +185 -0
  206. package/chunk-mmdhm4kx.js +10317 -0
  207. package/chunk-mz002yz8.js +2821 -0
  208. package/chunk-mzadqnyq.js +56 -0
  209. package/{chunk-VIDPVFP3.js → chunk-n3r1ebdm.js} +5 -6
  210. package/chunk-n438qea7.js +33 -0
  211. package/chunk-n5ffnhnb.js +93 -0
  212. package/chunk-nbvd87fy.js +9 -0
  213. package/{chunk-E36V7MPY.js → chunk-ndej7jc9.js} +53 -43
  214. package/{chunk-B767MA64.js → chunk-nen6rwe4.js} +62 -22
  215. package/chunk-nf06tr3v.js +16 -0
  216. package/chunk-ng8z355q.js +16 -0
  217. package/{chunk-4MEKE5D3.js → chunk-nhtxfv8k.js} +78 -63
  218. package/{runAgentClientLoop-2SFASHDS.js → chunk-nj62jscj.js} +132 -214
  219. package/{chunk-GBWGPTA7.js → chunk-nkryrkyp.js} +16 -19
  220. package/chunk-nmesxem8.js +197 -0
  221. package/{chunk-YR4J7RFS.js → chunk-nmq0qwbn.js} +117 -164
  222. package/chunk-nph8brvw.js +7 -0
  223. package/chunk-nr8fees9.js +10 -0
  224. package/{chunk-DFI7MVCQ.js → chunk-nvewvf7h.js} +1441 -1427
  225. package/{chunk-G7Y4GXTY.js → chunk-nyamhphs.js} +70 -79
  226. package/chunk-nz1c8tcg.js +111 -0
  227. package/{chunk-GPLUFN2E.js → chunk-nzc5yffh.js} +176 -217
  228. package/{chunk-G3SUCT4W.js → chunk-p1vg4bx8.js} +2 -4
  229. package/chunk-p3k3abe8.js +202 -0
  230. package/chunk-p4zy30q5.js +8 -0
  231. package/{chunk-ZJACPM5O.js → chunk-p6se1rx0.js} +102 -102
  232. package/chunk-p9dpshev.js +6968 -0
  233. package/chunk-pa42wxr0.js +116 -0
  234. package/{chunk-TA5QI4MM.js → chunk-paxthgqp.js} +56 -107
  235. package/{readlineWorkspace-ZH5FGDMI.js → chunk-pb35s8d9.js} +5395 -5786
  236. package/{chunk-XT6C2QZW.js → chunk-pbebzbcq.js} +8 -8
  237. package/chunk-pbx7e1mb.js +11 -0
  238. package/chunk-pe5czfn9.js +8 -0
  239. package/chunk-pextk1j4.js +62 -0
  240. package/chunk-pf5rywc6.js +575 -0
  241. package/chunk-pjfhd3fz.js +136 -0
  242. package/{chunk-ZCMAKAZM.js → chunk-pkhqb0fs.js} +118 -59
  243. package/chunk-pm5xb9jh.js +26 -0
  244. package/{chunk-Y3KGWZKF.js → chunk-ppdmmdkx.js} +110 -97
  245. package/chunk-pqp6y2hs.js +9 -0
  246. package/{chunk-QHEN7NZ7.js → chunk-ptz8fm2n.js} +12 -17
  247. package/{chunk-EUHMI5KG.js → chunk-pwqnvbt7.js} +65 -46
  248. package/chunk-pzr31nz7.js +12 -0
  249. package/{chunk-WWC7I6TA.js → chunk-q3cx89sw.js} +2 -4
  250. package/chunk-q5pe7be3.js +78 -0
  251. package/{chunk-ZHWTBHT3.js → chunk-q6zqbxp2.js} +418 -409
  252. package/chunk-q7r0e1p3.js +15 -0
  253. package/chunk-q8t2fecd.js +6 -0
  254. package/{chunk-2QAZCYOM.js → chunk-q94zx4d0.js} +721 -753
  255. package/{runtimeDoctorCommands-52MBG5JN.js → chunk-qarz1az1.js} +65 -85
  256. package/{chunk-4INJGWE3.js → chunk-qdcvr25b.js} +72 -53
  257. package/{streamAgentChatTurn-KOUWITHH.js → chunk-qxs27wfg.js} +1079 -1475
  258. package/{chunk-GIXWVN2W.js → chunk-r06ycjjr.js} +50 -47
  259. package/{chunk-63W5N6P3.js → chunk-r20jw5hb.js} +57 -38
  260. package/{chunk-I5BYFTYK.js → chunk-r7sfwdka.js} +1201 -1142
  261. package/{chunk-UMADT6B2.js → chunk-r9sp1yyb.js} +6 -8
  262. package/{handleSendMessageAction-FHGUFT2X.js → chunk-rbd2vgb3.js} +627 -757
  263. package/chunk-rc37js46.js +12 -0
  264. package/{chunk-5YI447UL.js → chunk-rmngk6r3.js} +67 -76
  265. package/chunk-rnhbnbrq.js +15 -0
  266. package/{chunk-WRHVVIGI.js → chunk-rsfnmrt5.js} +111 -131
  267. package/{chunk-YFSM2366.js → chunk-rvvn2rhj.js} +28 -22
  268. package/{chunk-4Y6CZ2N4.js → chunk-s0fpz7ht.js} +37 -33
  269. package/{chunk-VI4SWTUO.js → chunk-s1cqzb2r.js} +77 -65
  270. package/{chunk-6QDYSCPW.js → chunk-s8q81tda.js} +73 -65
  271. package/chunk-s9hy639e.js +6 -0
  272. package/{chunk-R5GO3YZP.js → chunk-s9vbwme8.js} +115 -106
  273. package/chunk-sger1m1b.js +20 -0
  274. package/chunk-spe6crvk.js +60 -0
  275. package/chunk-spwsrvh9.js +70 -0
  276. package/chunk-sr05zpk7.js +573 -0
  277. package/{chunk-M2EJHDJP.js → chunk-srncrd3f.js} +1 -12
  278. package/{chunk-QXHFIX7W.js → chunk-sry80bpx.js} +71 -53
  279. package/{chunk-PSCNXBYA.js → chunk-t6q69p83.js} +3 -4
  280. package/{chunk-UAD2WT54.js → chunk-t714r4q0.js} +9 -28
  281. package/chunk-t7vbraqe.js +42 -0
  282. package/{chunk-CVMMWN6P.js → chunk-td7653rr.js} +10 -20
  283. package/{chunk-3BQDF4QB.js → chunk-tmytcetz.js} +17 -21
  284. package/{chunk-AMWMV56B.js → chunk-tta4prwg.js} +16 -15
  285. package/chunk-tvh8azgq.js +4829 -0
  286. package/{chunk-ID4G2MAR.js → chunk-v08kbfm8.js} +10 -11
  287. package/{chunk-OKPOQGQJ.js → chunk-v1x702q8.js} +801 -852
  288. package/{chunk-KHCLMKZZ.js → chunk-v39fea91.js} +576 -247
  289. package/{chunk-OW765XBU.js → chunk-vejtd8p2.js} +3 -4
  290. package/chunk-vep7zkha.js +368 -0
  291. package/chunk-vfwn1k7n.js +142 -0
  292. package/chunk-vg68vxhx.js +20 -0
  293. package/chunk-vgcqgnsm.js +31 -0
  294. package/{chunk-NF64D32W.js → chunk-vnzyjdea.js} +1 -3
  295. package/{chunk-ZCLSM5AK.js → chunk-vqgtw1px.js} +800 -717
  296. package/chunk-vv1gr5xz.js +76 -0
  297. package/{spaceCommands-Z2CTQD6G.js → chunk-w1qeadpq.js} +176 -242
  298. package/chunk-w468ez1p.js +13 -0
  299. package/chunk-w49s0t79.js +14 -0
  300. package/{mcpLocalManageCommands-KUDZQRM4.js → chunk-w58zhfbn.js} +91 -93
  301. package/chunk-w5b74aq6.js +11 -0
  302. package/chunk-w7y41qyw.js +117 -0
  303. package/chunk-w820gg1w.js +4165 -0
  304. package/{chunk-DBJAJ4UD.js → chunk-wdsmaqmt.js} +399 -453
  305. package/{chunk-3EUW3WEO.js → chunk-wfvvnmmj.js} +1 -3
  306. package/{chunk-QY4NZCDA.js → chunk-wkr04bhk.js} +432 -651
  307. package/{chunk-KUG52IAP.js → chunk-ws402twv.js} +1 -3
  308. package/chunk-wzwh311q.js +164 -0
  309. package/{runtimeModeArgs-X7DL7PUN.js → chunk-x5vtgvwn.js} +6 -5
  310. package/{agentMachineCommands-COJD2KPZ.js → chunk-x8h2csmq.js} +152 -195
  311. package/{chunk-BAZCS5XG.js → chunk-x9zfjnrc.js} +59 -47
  312. package/{chunk-WTIJKWCI.js → chunk-xcarc2rf.js} +50 -56
  313. package/chunk-xf33gz0a.js +8 -0
  314. package/{chunk-PVFYPUIM.js → chunk-y7b3gwx1.js} +78 -71
  315. package/{memoryCommands-SVLAVFCV.js → chunk-y7sphmnh.js} +119 -95
  316. package/{agentListCommands-436FHOIT.js → chunk-ycvaafhc.js} +260 -374
  317. package/chunk-yd7zprb0.js +9 -0
  318. package/chunk-yfz3d27k.js +40 -0
  319. package/{chunk-MKR6KDD3.js → chunk-ykv9g3m4.js} +141 -125
  320. package/chunk-ystjgb9e.js +544 -0
  321. package/chunk-yysxn7ep.js +12 -0
  322. package/{chunk-AL3TYDIF.js → chunk-z17eyawk.js} +18 -16
  323. package/{machineCommands-RVB5OG2X.js → chunk-z17q416p.js} +442 -563
  324. package/chunk-z1n98pcf.js +12 -0
  325. package/{dialogTraceCommand-HWXGIGZX.js → chunk-z566jx5r.js} +292 -397
  326. package/chunk-zjxd6942.js +6 -0
  327. package/{versionChangeNotice-RFABJGJE.js → chunk-zk11x9y5.js} +7 -9
  328. package/{chunk-TEFD5E2D.js → chunk-zt73yc33.js} +48 -51
  329. package/chunk-zvs2fra1.js +5 -0
  330. package/{chunk-SVFFKLMR.js → chunk-zwee84rh.js} +117 -141
  331. package/chunk-zxgfqv72.js +8 -0
  332. package/index.js +53 -69
  333. package/package.json +4 -4
  334. package/_executeModel-YQNZNR2Y.js +0 -341
  335. package/action-UK3HXGXF.js +0 -30
  336. package/addContentAction-CAKFVBDM.js +0 -38
  337. package/addDialogAgentAction-KLJ2YWWM.js +0 -77
  338. package/agentDeleteCommand-S5FVPYKT.js +0 -523
  339. package/agentEmailCommands-ZEFMGVKM.js +0 -742
  340. package/agentRecordCommands-JZ35AC5A.js +0 -211
  341. package/agentRun-UIO43TUG.js +0 -251
  342. package/agentRunCommand-ATLKKD6O.js +0 -249
  343. package/agentRunControl-U2MV74WR.js +0 -211
  344. package/agentRuntimeLocal-P4MMGIR6.js +0 -189
  345. package/agentSlice-HHNKNNYM.js +0 -52
  346. package/appConfigCommands-W4JQHMOJ.js +0 -417
  347. package/appDeleteCommands-IXR47IAV.js +0 -183
  348. package/appDeployCommands-LB6DHDF4.js +0 -232
  349. package/appDeployStatusCommands-UQ6MJL6D.js +0 -204
  350. package/appGetCommands-M5JCTDDQ.js +0 -185
  351. package/appListCommands-TE3ZHE3I.js +0 -186
  352. package/appMigrateCommands-FOXH6R4B.js +0 -230
  353. package/appSourceCommands-3ACYB6I7.js +0 -279
  354. package/authCommand-I5OBJP5S.js +0 -66
  355. package/authCommands-I6KCGOCN.js +0 -54
  356. package/builtinSkillRegistry-MIXYSZUU.js +0 -35
  357. package/chromeOpsCommands-IZRCYDSW.js +0 -579
  358. package/chunk-24BICQPB.js +0 -25
  359. package/chunk-2E4BYAUE.js +0 -69
  360. package/chunk-2O72G3U2.js +0 -17157
  361. package/chunk-2OROOEOQ.js +0 -229
  362. package/chunk-2R6M34JP.js +0 -27225
  363. package/chunk-2SXN7LAY.js +0 -15
  364. package/chunk-35JIFLIG.js +0 -30
  365. package/chunk-3VXVE2LF.js +0 -12
  366. package/chunk-4DBTBNTX.js +0 -477
  367. package/chunk-4JH2UMJR.js +0 -40
  368. package/chunk-4RUQ2PFX.js +0 -432
  369. package/chunk-4SN6J65J.js +0 -38
  370. package/chunk-5MMAK75Q.js +0 -15
  371. package/chunk-6NYQHXMV.js +0 -1737
  372. package/chunk-6R4IY46J.js +0 -14
  373. package/chunk-7E6YXSFZ.js +0 -441
  374. package/chunk-7K4J76JQ.js +0 -917
  375. package/chunk-7LR2IFUH.js +0 -100
  376. package/chunk-AETZ7AD6.js +0 -274
  377. package/chunk-ATNTHIZI.js +0 -13
  378. package/chunk-BPB3T5EU.js +0 -791
  379. package/chunk-BV3FLP2L.js +0 -133
  380. package/chunk-BVYHE6QD.js +0 -110
  381. package/chunk-BWJLEN6X.js +0 -1388
  382. package/chunk-CHOZJMJS.js +0 -78
  383. package/chunk-D2LTQAGN.js +0 -464
  384. package/chunk-DALXH7BG.js +0 -3392
  385. package/chunk-DBCWXGOC.js +0 -15210
  386. package/chunk-DLXL4NSL.js +0 -1179
  387. package/chunk-DSBRIUX5.js +0 -23
  388. package/chunk-DWLEOOGR.js +0 -8
  389. package/chunk-E2KZNP6C.js +0 -13
  390. package/chunk-E5JV4DCB.js +0 -272
  391. package/chunk-EUGTFFO6.js +0 -42
  392. package/chunk-FBNVJ2TO.js +0 -294
  393. package/chunk-FGXG6OLW.js +0 -34
  394. package/chunk-G22P2J7O.js +0 -1775
  395. package/chunk-HEVRQGGH.js +0 -106
  396. package/chunk-HHXF57CL.js +0 -180
  397. package/chunk-HI5RS2O4.js +0 -2109
  398. package/chunk-HJTI7RZV.js +0 -94
  399. package/chunk-HRWRIPTB.js +0 -531
  400. package/chunk-HYCVEESH.js +0 -2824
  401. package/chunk-I42VC5KR.js +0 -15
  402. package/chunk-IB5AR52X.js +0 -15
  403. package/chunk-IIRJ4P4I.js +0 -24
  404. package/chunk-IT3ZZRJE.js +0 -12
  405. package/chunk-IV6VUVLJ.js +0 -88
  406. package/chunk-J42X32PV.js +0 -472
  407. package/chunk-JDMWYVUF.js +0 -449
  408. package/chunk-JKVOKKMQ.js +0 -53
  409. package/chunk-JRTNUU5Z.js +0 -54
  410. package/chunk-K7HLFORE.js +0 -226
  411. package/chunk-KGBASAB5.js +0 -74
  412. package/chunk-KGKTN2NX.js +0 -25
  413. package/chunk-KX6YBIHG.js +0 -8
  414. package/chunk-KYHNSSL2.js +0 -62
  415. package/chunk-KZO2MTVM.js +0 -140
  416. package/chunk-LKZPX6YH.js +0 -0
  417. package/chunk-LLP2NDED.js +0 -201
  418. package/chunk-LOFRSJX2.js +0 -47
  419. package/chunk-M75RM77T.js +0 -3970
  420. package/chunk-MDAYRIP7.js +0 -1889
  421. package/chunk-MI6HRMCK.js +0 -25
  422. package/chunk-MTNQNLSE.js +0 -1029
  423. package/chunk-NH4PUEWK.js +0 -762
  424. package/chunk-NHLLXINQ.js +0 -8
  425. package/chunk-NTUNHTJV.js +0 -40
  426. package/chunk-OJKUU3LP.js +0 -67
  427. package/chunk-OQH3TAB7.js +0 -299
  428. package/chunk-P62DHV4F.js +0 -443
  429. package/chunk-PHIERFHT.js +0 -574
  430. package/chunk-PKDFU6MY.js +0 -102
  431. package/chunk-PL5RKESU.js +0 -40
  432. package/chunk-PSJJBBWV.js +0 -42
  433. package/chunk-QKM55LP2.js +0 -739
  434. package/chunk-QQ56R7KS.js +0 -88
  435. package/chunk-QYPE3TS3.js +0 -43
  436. package/chunk-REAE2SZK.js +0 -62
  437. package/chunk-RGQ4UUWZ.js +0 -208
  438. package/chunk-RIRFHJTW.js +0 -353
  439. package/chunk-RYMLMTPZ.js +0 -547
  440. package/chunk-SSGTV4FC.js +0 -303
  441. package/chunk-SVKWZ3EG.js +0 -607
  442. package/chunk-T7KODHYS.js +0 -317
  443. package/chunk-TGVVE5BA.js +0 -3085
  444. package/chunk-TKLBBR7P.js +0 -779
  445. package/chunk-TZXPT53C.js +0 -8
  446. package/chunk-U67V476Y.js +0 -35
  447. package/chunk-UEILX4EV.js +0 -15
  448. package/chunk-VIWDGTDA.js +0 -8
  449. package/chunk-VXUQWCEZ.js +0 -138
  450. package/chunk-W5GKF5ZW.js +0 -32
  451. package/chunk-WDWZPASX.js +0 -29
  452. package/chunk-WX266G2C.js +0 -9594
  453. package/chunk-YCITCYSJ.js +0 -356
  454. package/chunk-Z3KTXWWB.js +0 -76
  455. package/chunk-ZC3CMUKU.js +0 -322
  456. package/chunk-ZSZBHRLP.js +0 -1710
  457. package/chunk-ZV7ZY46L.js +0 -1343
  458. package/cliAgentConfigHelpers-WB2S7PDO.js +0 -47
  459. package/cliAuthorityBrokerClient-3SKOA7OZ.js +0 -23
  460. package/cliAuthorityBrokerProcess-BMBVXPKU.js +0 -24
  461. package/cliAuthorityStoreDriver-6FE3BJNB.js +0 -20
  462. package/cliEnvHelpers-7V5ZWUJA.js +0 -34
  463. package/cliExecutor-N3445G2Z.js +0 -45
  464. package/cliLocalAgentRecordReader-QKKRK53P.js +0 -113
  465. package/cloudAutomationCommands-S52NKCLL.js +0 -310
  466. package/contentThunks-ERA42OXW.js +0 -100
  467. package/cooldownCommands-ZFDAL4MR.js +0 -79
  468. package/createAgentAutomationAction-DMD2VDPI.js +0 -173
  469. package/createDialogAction-3SPOJQAK.js +0 -87
  470. package/createPageAction-AVXUMZVT.js +0 -91
  471. package/cursorProvider-2RACMEMF.js +0 -6123
  472. package/db-LTHLW7QA.js +0 -178
  473. package/dbSlice-WNUHTF4C.js +0 -76
  474. package/deleteDbKey-KV6MYBAI.js +0 -87
  475. package/desktopFolderProjects-4POAMVJN.js +0 -45
  476. package/dialogCommands-4MOLJW4G.js +0 -165
  477. package/dialogMessageRecord-2HJTEXQX.js +0 -7
  478. package/dialogNotifyCommand-YL2GFKLO.js +0 -45
  479. package/dialogSlice-Q7H2YVNO.js +0 -200
  480. package/dialogUsageCommand-IO2BQKL2.js +0 -31
  481. package/docCreateCommands-OYLRBK2M.js +0 -255
  482. package/docDeleteCommands-3NF6QPJU.js +0 -226
  483. package/docReadCommands-CBAERJAP.js +0 -184
  484. package/docStore-GWPFDV6Y.js +0 -89
  485. package/docUpdateCommands-BAMCGX6F.js +0 -326
  486. package/ebookDownloaderAgentCommand-NOIZ6U7Y.js +0 -675
  487. package/fetchMessages-P7FSCSXV.js +0 -19
  488. package/getPricing-KNXVEIUI.js +0 -40
  489. package/hostCredentialCreate-2VEYBXJV.js +0 -402
  490. package/i18n-SAK6DDY4.js +0 -51
  491. package/keys-FXEGMKSG.js +0 -183
  492. package/legacyMigration-TF4SYJCZ.js +0 -19
  493. package/levelAuthorityStore-L5SVDM5O.js +0 -10
  494. package/localAutomationCommands-XSK7SM7I.js +0 -199
  495. package/localAutomationRuntime-5WBO7HGQ.js +0 -61
  496. package/localRecall-BDYKXB46.js +0 -17
  497. package/localRuntimeAdapter-Y6H6XRIH.js +0 -310
  498. package/localRuntimeAuthority-Q5C2KWGF.js +0 -45
  499. package/localRuntimeDb-MM3DINZM.js +0 -12
  500. package/machineInfo-HNPJHQFU.js +0 -14
  501. package/machineWsRunDispatch-Y5SJGCEE.js +0 -228
  502. package/models-TOXYINNM.js +0 -10
  503. package/oauthTokenStore-RUYNYALS.js +0 -24
  504. package/overlay-JA3SPVUS.js +0 -15
  505. package/parityCommands-5OCBPVES.js +0 -613
  506. package/processSpawn-6GEO77KV.js +0 -11
  507. package/profileConfig-KOWK4HOG.js +0 -49
  508. package/projectArchive-WE3VVPZ2.js +0 -132
  509. package/providerPresetApply-YCVSP2WX.js +0 -235
  510. package/providerRegistry-26PAUYH2.js +0 -24
  511. package/read-D4WYJQJQ.js +0 -32
  512. package/readDocTool-3S3OQFOH.js +0 -22
  513. package/rememberExplicit-ZPI6KK5M.js +0 -16
  514. package/remove-AHRMUDMH.js +0 -32
  515. package/removeDialogAgentAction-AALRBFSA.js +0 -81
  516. package/secretCommands-2PSS3QNZ.js +0 -24
  517. package/setDialogExtraReferencesAction-SLHQ3GYL.js +0 -39
  518. package/setPrimaryDialogAgentAction-XKCSGJ7M.js +0 -96
  519. package/skillDiscovery-IUEZZG2B.js +0 -29
  520. package/skillSummaryMarker-62UW7HI7.js +0 -9
  521. package/slateToRenderMarkdown-R3X74MCX.js +0 -7
  522. package/slateUtils-ESQAJ6RN.js +0 -19
  523. package/store-WSAVTR32.js +0 -50
  524. package/switchDialogAgentAction-YJIWQGIR.js +0 -70
  525. package/tombstones-FQQMEDOW.js +0 -32
  526. package/toolApiClient-FVXTIIEN.js +0 -42
  527. package/tools-WN4AVSNS.js +0 -147
  528. package/tuiRestart-LU2BDLAW.js +0 -50
  529. package/tuiSummaryLlmCaller-Z2ZVBIGN.js +0 -53
  530. package/updateCommands-4QP7WJLA.js +0 -63
  531. package/usageCommand-AZX7D3LB.js +0 -31
  532. package/usageRebuildCommand-XV5QQCHK.js +0 -623
  533. package/userDataMerge-HT2ZVHBJ.js +0 -13
  534. package/windowsSelfUpdate-5OFKSW6Y.js +0 -14
  535. package/workContext-ZAW6VXT7.js +0 -18
  536. package/workContextAccess-VU5I4LKZ.js +0 -11
  537. package/workContextWriteNotice-YCSSMHN4.js +0 -7
  538. /package/{chunk-BYXBJQAS.js → chunk-0bcc25vg.js} +0 -0
@@ -1,235 +1,174 @@
1
1
  import {
2
- getLocalProviderSecret
3
- } from "./chunk-56OAS5RZ.js";
4
- import {
5
- performServerProxyFetchWithRetry
6
- } from "./chunk-LYPJYBE5.js";
7
- import {
8
- fetchServerSyncedCredential
9
- } from "./chunk-TKLBBR7P.js";
10
- import {
11
- getRuntimeServerSnapshot,
12
- getSessionSnapshotForState,
13
- resolveDesktopSafeServer,
14
- resolveUserAuthorityServer
15
- } from "./chunk-HI5RS2O4.js";
2
+ isLoopbackHostname,
3
+ isLoopbackUrl,
4
+ normalizeKnownServerOrigin,
5
+ API_ENDPOINTS
6
+ } from "./chunk-j0yxesh3.js";
16
7
  import {
17
- googleSessionRequestToken,
18
- googleSessionServer,
19
- isGoogleAuthoritySession
20
- } from "./chunk-K7HLFORE.js";
8
+ isModelSupportReasoningEffort,
9
+ clampReasoningEffort,
10
+ getModelConfig,
11
+ OPENAI_RESPONSES_ENDPOINT
12
+ } from "./chunk-kawvydbk.js";
21
13
  import {
22
- buildIdentityBlock,
23
- buildPlatformStaticContextLayers,
24
- buildResponseGuidelines,
25
- buildRuntimeGuidanceBlocks,
26
- compileContextLayers,
27
- resolveToolGuidedSections
28
- } from "./chunk-NH4PUEWK.js";
14
+ isFireworksKimiModel,
15
+ isDeepInfraKimiModel,
16
+ resolveFireworksKimiModel,
17
+ resolvePlatformHostedRouting,
18
+ usesMimoThinkingWire
19
+ } from "./chunk-fkrgqq8w.js";
29
20
  import {
30
- convertMessagesToResponsesInput,
31
21
  getUsageRequestOptions,
32
- normalizeChatCompletionsBodyForProvider,
33
22
  preserveAgentStateFields,
23
+ shouldStripReasoningContentForOutbound,
34
24
  resolveReasoningReplayOptions,
35
- shouldStripReasoningContentForOutbound
36
- } from "./chunk-DFI7MVCQ.js";
37
- import {
38
- stablePromptCacheKey
39
- } from "./chunk-4IVMDQBA.js";
40
- import {
41
- resolveAgentCallPlan,
42
- resolveClientWire
43
- } from "./chunk-PEXGRTTQ.js";
25
+ convertMessagesToResponsesInput,
26
+ normalizeChatCompletionsBodyForProvider
27
+ } from "./chunk-nvewvf7h.js";
44
28
  import {
45
- detectDispatchIntentFromMessages
46
- } from "./chunk-4Y6CZ2N4.js";
29
+ wrapHistoricalSummaryWithReplayGuard,
30
+ buildSkillGuidancePromptBlock
31
+ } from "./chunk-w820gg1w.js";
47
32
  import {
48
- isGpt62DeveloperPrefixModel,
49
- usesCodexDeveloperPrefix
50
- } from "./chunk-RYMLMTPZ.js";
33
+ canonicalizeToolNames
34
+ } from "./chunk-vep7zkha.js";
51
35
  import {
52
- createFileCredentialBroker
53
- } from "./chunk-E6A5NHDH.js";
36
+ MEMORY_USE_GUIDANCE,
37
+ buildUserResponseLanguageContext,
38
+ compileContextLayers,
39
+ buildIdentityBlock,
40
+ buildPlatformStaticContextLayers,
41
+ buildRuntimeGuidanceBlocks,
42
+ resolveToolGuidedSections,
43
+ buildResponseGuidelines
44
+ } from "./chunk-drqzzzvr.js";
54
45
  import {
55
- buildSkillGuidancePromptBlock
56
- } from "./chunk-HYCVEESH.js";
46
+ detectDispatchIntentFromMessages
47
+ } from "./chunk-s0fpz7ht.js";
57
48
  import {
58
- buildProviderAuthHeaders
59
- } from "./chunk-UYQILGDR.js";
49
+ stablePromptCacheKey
50
+ } from "./chunk-1fv9k8zt.js";
60
51
  import {
61
52
  isAgentCredentialShared,
62
- resolveOutboundProxyApiKey
63
- } from "./chunk-KGKTN2NX.js";
64
- import {
65
- OPENAI_RESPONSES_ENDPOINT
66
- } from "./chunk-BVYHE6QD.js";
53
+ resolveOutboundProxyApiKey,
54
+ buildProviderAuthHeaders
55
+ } from "./chunk-90egc9vb.js";
67
56
  import {
68
- canonicalizeToolNames
69
- } from "./chunk-HJTI7RZV.js";
57
+ resolveClientWire,
58
+ resolveAgentCallPlan
59
+ } from "./chunk-0tsfn0dk.js";
70
60
  import {
71
- clampReasoningEffort,
72
- getModelConfig,
73
- isModelSupportReasoningEffort
74
- } from "./chunk-RI7SXDJW.js";
61
+ isGoogleAuthoritySession,
62
+ googleSessionServer,
63
+ googleSessionRequestToken,
64
+ resolveUserAuthorityServer,
65
+ resolveDesktopSafeServer,
66
+ getRuntimeServerSnapshot,
67
+ getSessionSnapshotForState,
68
+ fetchServerSyncedCredential
69
+ } from "./chunk-c235kypv.js";
75
70
  import {
76
- isRecord
77
- } from "./chunk-KUG52IAP.js";
71
+ getLocalProviderSecret
72
+ } from "./chunk-f3ad6q4h.js";
78
73
  import {
79
- MEMORY_USE_GUIDANCE,
80
- buildUserResponseLanguageContext
81
- } from "./chunk-Z3KTXWWB.js";
74
+ performServerProxyFetchWithRetry
75
+ } from "./chunk-3qfpcdkm.js";
82
76
  import {
83
- wrapHistoricalSummaryWithReplayGuard
84
- } from "./chunk-2SXN7LAY.js";
77
+ isGpt62DeveloperPrefixModel,
78
+ usesCodexDeveloperPrefix
79
+ } from "./chunk-2ygg7azv.js";
85
80
  import {
86
- isDeepInfraKimiModel,
87
- isFireworksKimiModel,
88
- resolveFireworksKimiModel,
89
- resolvePlatformHostedRouting,
90
- usesMimoThinkingWire
91
- } from "./chunk-G22P2J7O.js";
81
+ createFileCredentialBroker
82
+ } from "./chunk-av2mzeqz.js";
92
83
  import {
93
84
  asTrimmedLowercaseString
94
- } from "./chunk-QSJ3HFEF.js";
85
+ } from "./chunk-h1hzmqph.js";
86
+ import {
87
+ isRecord
88
+ } from "./chunk-ws402twv.js";
95
89
  import {
96
90
  toErrorMessage
97
- } from "./chunk-HNMXYYJR.js";
91
+ } from "./chunk-jec44fkj.js";
98
92
  import {
99
93
  asTrimmedString
100
- } from "./chunk-3EUW3WEO.js";
101
- import {
102
- API_ENDPOINTS,
103
- normalizeKnownServerOrigin
104
- } from "./chunk-JKVOKKMQ.js";
105
- import {
106
- isLoopbackHostname,
107
- isLoopbackUrl
108
- } from "./chunk-4SN6J65J.js";
94
+ } from "./chunk-wfvvnmmj.js";
109
95
  import {
110
96
  asOptionalTrimmedString
111
- } from "./chunk-G3SUCT4W.js";
112
-
113
- // packages/agent-runtime/responsesConversationState.ts
114
- function supportsResponsesConversationState(agent) {
115
- return normalizeIdentityPart(agent.provider) === "openai";
116
- }
117
- var normalizeIdentityPart = (value) => typeof value === "string" ? value.trim().toLowerCase() : "";
118
- function normalizeResponsesConversationState(value) {
119
- if (!value || typeof value !== "object") return null;
120
- const raw = value;
121
- const provider = normalizeIdentityPart(raw.provider);
122
- const model = normalizeIdentityPart(raw.model);
123
- const responseId = typeof raw.responseId === "string" ? raw.responseId.trim() : "";
124
- if (!provider || !model || !responseId) return null;
125
- return { provider, model, responseId };
126
- }
127
- function selectResponsesConversationState(value, agent) {
128
- if (!supportsResponsesConversationState(agent)) return null;
129
- const state = normalizeResponsesConversationState(value);
130
- if (!state) return null;
131
- if (state.provider !== normalizeIdentityPart(agent.provider)) return null;
132
- if (state.model !== normalizeIdentityPart(agent.model)) return null;
133
- return state;
134
- }
135
- function updateResponsesConversationState(agent, responseId) {
136
- if (!supportsResponsesConversationState(agent)) return null;
137
- const provider = normalizeIdentityPart(agent.provider);
138
- const model = normalizeIdentityPart(agent.model);
139
- const normalizedResponseId = typeof responseId === "string" ? responseId.trim() : "";
140
- if (!provider || !model || !normalizedResponseId) return null;
141
- return { provider, model, responseId: normalizedResponseId };
142
- }
143
- function isResponsesConversationStateRejection(status, responseBody) {
144
- if (![400, 404, 409].includes(status)) return false;
145
- const text = typeof responseBody === "string" ? responseBody.trim().toLowerCase() : "";
146
- if (!text) return false;
147
- const mentionsResponseState = /previous[\s_-]*response/.test(text) || /response[\s_-]*(?:id|state)/.test(text);
148
- const rejectsState = /not[\s_-]*found/.test(text) || /does not exist/.test(text) || /invalid/.test(text) || /expired/.test(text) || /unknown/.test(text);
149
- return mentionsResponseState && rejectsState;
150
- }
151
-
97
+ } from "./chunk-p1vg4bx8.js";
152
98
  // packages/ai/agent/buildSystemPrompt.ts
153
- var CLARIFICATION_MODE_INSTRUCTIONS = `\u5728\u4F60\u8FD8\u4E0D\u4E86\u89E3\u7528\u6237\u610F\u56FE\u65F6\uFF0C\u901A\u8FC7\u63D0\u95EE\u6765\u6F84\u6E05\u9700\u6C42\uFF0C\u800C\u4E0D\u662F\u4ED3\u4FC3\u7ED9\u51FA\u7B54\u6848\u3002`;
99
+ var CLARIFICATION_MODE_INSTRUCTIONS = `在你还不了解用户意图时,通过提问来澄清需求,而不是仓促给出答案。`;
154
100
  var isBrowser = typeof window !== "undefined";
155
- var CONTEXT_USAGE_INSTRUCTIONS = `\u53C2\u8003\u8D44\u6599\u4F7F\u7528\u8BF4\u660E\uFF1A
156
- - \u4E0B\u65B9\u63D0\u4F9B\u7684\u8D44\u6599\u662F\u4F60\u7684\u4E3B\u8981\u6743\u5A01\u4FE1\u606F\u6765\u6E90\u3002
157
- - \u56DE\u7B54\u95EE\u9898\u65F6\uFF0C\u5E94\u4F18\u5148\u4F9D\u8D56\u8FD9\u4E9B\u8D44\u6599\u3002\u5B83\u4EEC\u6309\u4F18\u5148\u7EA7\u4ECE\u9AD8\u5230\u4F4E\u6392\u5217\u3002
158
- - \u4F7F\u7528\u5176\u4E2D\u7684\u4E8B\u5B9E\u3001\u6570\u636E\u548C\u540D\u79F0\u65F6\uFF0C\u8981\u4FDD\u6301\u7CBE\u51C6\u3002
159
- - \u5982\u679C\u8D44\u6599\u4E2D\u6CA1\u6709\u5305\u542B\u7B54\u6848\uFF0C\u5E94\u8BF4\u660E\u8FD9\u4E00\u70B9\uFF0C\u7136\u540E\u518D\u4F7F\u7528\u4F60\u7684\u901A\u7528\u77E5\u8BC6\u8FDB\u884C\u56DE\u7B54\u3002
160
- - \u5982\u679C\u4F60\u5728\u8D44\u6599\u4E2D\u53D1\u73B0\u76F8\u4E92\u77DB\u76FE\u7684\u4FE1\u606F\uFF0C\u4E5F\u8981\u5728\u56DE\u7B54\u4E2D\u6307\u51FA\u8FD9\u4E00\u70B9\u3002
161
- - \u5F53\u901A\u7528\u6307\u4EE4\u4E0E\u66F4\u5177\u4F53\u7684"\u6309 Agent / \u6309\u6587\u6863"\u7684\u89C4\u5219\u53D1\u751F\u51B2\u7A81\u65F6\uFF0C\u5FC5\u987B\u4F18\u5148\u9075\u5B88\u66F4\u5177\u4F53\u3001\u4F18\u5148\u7EA7\u66F4\u9AD8\u7684\u89C4\u5219\u3002`;
101
+ var CONTEXT_USAGE_INSTRUCTIONS = `参考资料使用说明:
102
+ - 下方提供的资料是你的主要权威信息来源。
103
+ - 回答问题时,应优先依赖这些资料。它们按优先级从高到低排列。
104
+ - 使用其中的事实、数据和名称时,要保持精准。
105
+ - 如果资料中没有包含答案,应说明这一点,然后再使用你的通用知识进行回答。
106
+ - 如果你在资料中发现相互矛盾的信息,也要在回答中指出这一点。
107
+ - 当通用指令与更具体的"按 Agent / 按文档"的规则发生冲突时,必须优先遵守更具体、优先级更高的规则。`;
162
108
  var createContextSection = (title, description, content) => content ? `### ${title}
163
109
  ${description}
164
110
 
165
111
  ${content} ` : "";
166
112
  var buildReferenceMaterialsBlock = (contexts) => {
167
113
  const sections = [
168
- createContextSection(
169
- "\u8BF4\u660E\u6027\u6587\u6863\uFF08Instructional Documents\uFF09",
170
- "\uFF08\u6700\u9AD8\u4F18\u5148\u7EA7\uFF1A\u5177\u4F53\u89C4\u5219\u4E0E\u6D41\u7A0B\uFF09",
171
- contexts.botInstructionsContext
172
- ),
173
- createContextSection(
174
- "\u5F53\u524D\u8F93\u5165\u4E0A\u4E0B\u6587\uFF08Current Input Context\uFF09",
175
- "\uFF08\u9AD8\u4F18\u5148\u7EA7\uFF1A\u6765\u81EA\u7528\u6237\u672C\u6B21\u8F93\u5165\uFF09",
176
- contexts.currentInputContext
177
- ),
178
- createContextSection(
179
- "\u4F1A\u8BDD\u5386\u53F2\u5F15\u7528\uFF08Conversation History References\uFF09",
180
- "\uFF08\u4E2D\u7B49\u4F18\u5148\u7EA7\uFF1A\u6765\u81EA\u8FC7\u5F80\u6D88\u606F\uFF09",
181
- contexts.historyContext
182
- ),
183
- createContextSection(
184
- "\u77E5\u8BC6\u5E93\u6587\u6863\uFF08Knowledge Base Documents\uFF09",
185
- "\uFF08\u53C2\u8003\u4F18\u5148\u7EA7\uFF1A\u7528\u4E8E\u901A\u7528\u67E5\u9605\uFF09",
186
- contexts.botKnowledgeContext
187
- )
114
+ createContextSection("说明性文档(Instructional Documents)", "(最高优先级:具体规则与流程)", contexts.botInstructionsContext),
115
+ createContextSection("当前输入上下文(Current Input Context)", "(高优先级:来自用户本次输入)", contexts.currentInputContext),
116
+ createContextSection("会话历史引用(Conversation History References)", "(中等优先级:来自过往消息)", contexts.historyContext),
117
+ createContextSection("知识库文档(Knowledge Base Documents)", "(参考优先级:用于通用查阅)", contexts.botKnowledgeContext)
188
118
  ].filter(Boolean);
189
119
  if (sections.length === 0) {
190
120
  return "";
191
121
  }
192
122
  return [
193
- "--- \u53C2\u8003\u8D44\u6599 ---",
123
+ "--- 参考资料 ---",
194
124
  CONTEXT_USAGE_INSTRUCTIONS,
195
125
  "",
196
- sections.join("\n\n")
197
- ].join("\n");
126
+ sections.join(`
127
+
128
+ `)
129
+ ].join(`
130
+ `);
198
131
  };
199
132
  var buildEditingContextBlock = (contexts) => {
200
- if (!contexts.editingContext) return "";
133
+ if (!contexts.editingContext)
134
+ return "";
201
135
  return [
202
- "--- \u5F53\u524D\u7F16\u8F91\u4E0A\u4E0B\u6587 ---",
203
- "\u4E0B\u9762\u662F\u7528\u6237\u5F53\u524D\u6B63\u5728\u67E5\u770B\u6216\u7F16\u8F91\u7684\u5BF9\u8C61\u63CF\u8FF0\uFF0C\u8BF7\u5728\u6D89\u53CA\u4FEE\u6539\u3001\u5EFA\u8BAE\u6216\u7ED3\u6784\u6027\u64CD\u4F5C\u65F6\u4F18\u5148\u53C2\u8003\u8FD9\u91CC\uFF1A",
136
+ "--- 当前编辑上下文 ---",
137
+ "下面是用户当前正在查看或编辑的对象描述,请在涉及修改、建议或结构性操作时优先参考这里:",
204
138
  "",
205
139
  contexts.editingContext
206
- ].join("\n");
140
+ ].join(`
141
+ `);
207
142
  };
208
143
  var buildAppWorkingMemoryBlock = (contexts) => {
209
- if (!contexts.appWorkingMemory) return "";
144
+ if (!contexts.appWorkingMemory)
145
+ return "";
210
146
  return [
211
- "--- \u6700\u8FD1\u5E94\u7528\u5DE5\u4F5C\u8BB0\u5FC6 ---",
212
- "\u4E0B\u9762\u662F\u4ECE\u5F53\u524D\u5BF9\u8BDD\u6700\u8FD1\u7684\u5E94\u7528\u76F8\u5173\u5DE5\u5177\u8C03\u7528\u4E2D\u63D0\u70BC\u51FA\u7684\u771F\u503C\u3002\u5373\u4F7F\u7528\u6237\u6CA1\u6709\u6253\u5F00\u53F3\u4FA7\u5E94\u7528\u4FA7\u680F\uFF0C\u53EA\u8981\u4ED6\u8BF4\u201C\u521A\u624D\u90A3\u4E2A app / \u90A3\u4E2A\u7F51\u7AD9 / \u90A3\u4E2A\u9879\u76EE\u201D\uFF0C\u4E5F\u4F18\u5148\u53C2\u8003\u8FD9\u91CC\uFF1A",
147
+ "--- 最近应用工作记忆 ---",
148
+ "下面是从当前对话最近的应用相关工具调用中提炼出的真值。即使用户没有打开右侧应用侧栏,只要他说“刚才那个 app / 那个网站 / 那个项目”,也优先参考这里:",
213
149
  "",
214
150
  contexts.appWorkingMemory
215
- ].join("\n");
151
+ ].join(`
152
+ `);
216
153
  };
217
154
  var buildSpaceContextBlock = (contexts) => {
218
- if (!contexts.spaceContext) return "";
155
+ if (!contexts.spaceContext)
156
+ return "";
219
157
  return [
220
158
  contexts.spaceContext,
221
159
  "",
222
- "\u91CD\u8981\u6307\u4EE4 (Space Awareness)\uFF1A",
223
- "- \u4F60\u6B63\u5904\u4E8E\u4E0A\u8FF0\u5DE5\u4F5C\u7A7A\u95F4\u4E2D\u3002\u5982\u679C\u7528\u6237\u7684\u95EE\u9898\u6D89\u53CA\u5230\u8BE5\u7A7A\u95F4\u7684\u5185\u5BB9\u3001\u6587\u4EF6\u6216\u77E5\u8BC6\uFF1A",
224
- " - \u4F7F\u7528 `read` \u5DE5\u5177\u67E5\u9605\u666E\u901A\u6570\u636E\u8BB0\u5F55\u6216\u6570\u636E\u8868\u9879\u3002",
225
- "- \u5982\u679C\u4F60\u5728\u5BF9\u8BDD\u4E2D\u4EA7\u51FA\u4E86\u503C\u5F97\u4FDD\u5B58\u7684\u91CD\u8981\u4FE1\u606F\uFF08\u5982\u603B\u7ED3\u3001\u65B9\u6848\u3001\u4EE3\u7801\u7247\u6BB5\u7B49\uFF09\uFF0C\u8BF7\u4E3B\u52A8\u8BE2\u95EE\u7528\u6237\u6216\u4F7F\u7528 `createDoc` \u5DE5\u5177\u5C06\u5176\u4FDD\u5B58\u4E3A\u65B0\u9875\u9762\uFF0C\u4EE5\u4FBF\u4F5C\u4E3A\u957F\u671F\u8BB0\u5FC6\u7559\u5B58\u3002",
160
+ "重要指令 (Space Awareness):",
161
+ "- 你正处于上述工作空间中。如果用户的问题涉及到该空间的内容、文件或知识:",
162
+ " - 使用 `read` 工具查阅普通数据记录或数据表项。",
163
+ "- 如果你在对话中产出了值得保存的重要信息(如总结、方案、代码片段等),请主动询问用户或使用 `createDoc` 工具将其保存为新页面,以便作为长期记忆留存。",
226
164
  "",
227
- "\u8DE8\u7A7A\u95F4\u5BFC\u822A (Cross-Space Navigation)\uFF1A",
228
- "- \u4F7F\u7528 `listUserSpaces` \u5DE5\u5177\u53EF\u83B7\u53D6\u7528\u6237\u6240\u6709\u53EF\u8BBF\u95EE\u7684 Space \u5217\u8868\uFF08ID \u548C\u540D\u79F0\uFF09\u3002",
229
- '- \u4F7F\u7528 `read({ dbKey: "space-{spaceId}" })` \u53EF\u83B7\u53D6\u6307\u5B9A Space \u7684\u5B8C\u6574\u6570\u636E\uFF0C\u5305\u62EC\uFF1A',
230
- " - categories: \u5206\u7C7B\u5B57\u5178\uFF0Ckey \u662F\u5206\u7C7B ID\uFF0Cvalue \u5305\u542B name \u548C order",
231
- " - contents: \u5185\u5BB9\u5B57\u5178\uFF0C\u6BCF\u9879\u5305\u542B contentKey\uFF08dbKey\uFF09\u3001title\u3001type\u3001categoryId"
232
- ].join("\n");
165
+ "跨空间导航 (Cross-Space Navigation):",
166
+ "- 使用 `listUserSpaces` 工具可获取用户所有可访问的 Space 列表(ID 和名称)。",
167
+ '- 使用 `read({ dbKey: "space-{spaceId}" })` 可获取指定 Space 的完整数据,包括:',
168
+ " - categories: 分类字典,key 是分类 ID,value 包含 name 和 order",
169
+ " - contents: 内容字典,每项包含 contentKey(dbKey)、title、type、categoryId"
170
+ ].join(`
171
+ `);
233
172
  };
234
173
  var buildSkillGuidanceBlock = (agentConfig) => {
235
174
  const recommendedSkillHints = Array.isArray(agentConfig.recommendedSkillHints) ? agentConfig.recommendedSkillHints.filter(Boolean) : [];
@@ -238,7 +177,7 @@ var buildSkillGuidanceBlock = (agentConfig) => {
238
177
  return "";
239
178
  }
240
179
  return buildSkillGuidancePromptBlock({
241
- title: "--- \u6280\u80FD\u63D0\u793A ---",
180
+ title: "--- 技能提示 ---",
242
181
  recommendedSkillHints,
243
182
  skillPromptPatches
244
183
  });
@@ -250,7 +189,7 @@ var buildSystemPromptContext = (options) => {
250
189
  contexts = {},
251
190
  viewport,
252
191
  mobileBreakpoint = 768,
253
- now = /* @__PURE__ */ new Date(),
192
+ now = new Date,
254
193
  timeZone
255
194
  } = options;
256
195
  const safeLanguage = options.language ?? (typeof navigator !== "undefined" ? navigator.language : "en");
@@ -260,14 +199,12 @@ var buildSystemPromptContext = (options) => {
260
199
  agentId: dbKey,
261
200
  model
262
201
  });
263
- const corePersonaSection = mainPrompt ? `-- - \u6838\u5FC3\u89D2\u8272\u4E0E\u4EFB\u52A1-- -
202
+ const corePersonaSection = mainPrompt ? `-- - 核心角色与任务-- -
264
203
  ${mainPrompt}` : "";
265
204
  const agentTools = canonicalizeToolNames(agentConfig.tools ?? []);
266
205
  const hasAskTool = agentTools.includes("ask_user");
267
206
  const toolSections = resolveToolGuidedSections(agentTools, {
268
207
  dispatchIntent: options.dispatchIntent === true,
269
- // 安全透传:两者缺省均为 undefined,resolveToolGuidedSections 不追加任何文本,
270
- // 因此未接线调用方拿到的 prompt 与既往逐字相同。
271
208
  callerModel: options.callerModel,
272
209
  callerIsPoolTop: options.callerIsPoolTop,
273
210
  externalAgentCount: options.externalAgentCount
@@ -280,25 +217,24 @@ ${mainPrompt}` : "";
280
217
  const clarifyingSection = !mainPrompt || hasAskTool ? CLARIFICATION_MODE_INSTRUCTIONS : "";
281
218
  const userGlobalPromptSection = "";
282
219
  const effectiveViewport = viewport ?? contexts.viewport;
283
- const isMobile = effectiveViewport !== void 0 ? effectiveViewport.width < mobileBreakpoint : typeof contexts.isMobile === "boolean" ? contexts.isMobile : isBrowser && typeof window !== "undefined" ? window.innerWidth < mobileBreakpoint : false;
220
+ const isMobile = effectiveViewport !== undefined ? effectiveViewport.width < mobileBreakpoint : typeof contexts.isMobile === "boolean" ? contexts.isMobile : isBrowser && typeof window !== "undefined" ? window.innerWidth < mobileBreakpoint : false;
284
221
  const responseGuidelinesSection = buildResponseGuidelines(isMobile);
285
222
  const editingContextSection = buildEditingContextBlock(contexts);
286
223
  const appWorkingMemorySection = buildAppWorkingMemoryBlock(contexts);
287
224
  const spaceContextSection = buildSpaceContextBlock(contexts);
288
225
  const rawMemoryOverlay = asOptionalTrimmedString(contexts.memoryOverlay) ?? "";
289
226
  const memoryOverlaySection = rawMemoryOverlay;
290
- const hasMemoryTools = Array.isArray(agentConfig.tools) && agentConfig.tools.some(
291
- (t) => /memory/i.test(t)
292
- );
227
+ const hasMemoryTools = Array.isArray(agentConfig.tools) && agentConfig.tools.some((t) => /memory/i.test(t));
293
228
  const memoryUseGuidanceSection = hasMemoryTools ? MEMORY_USE_GUIDANCE : "";
294
229
  const skillGuidanceSection = buildSkillGuidanceBlock(agentConfig);
295
230
  const referenceMaterialsSection = buildReferenceMaterialsBlock(contexts);
296
- const requestContextBlocksSection = (contexts.requestContextBlocks ?? []).map((block) => typeof block === "string" ? block.trim() : "").filter((block) => block.length > 0).join("\n\n");
297
- const dialogSummarySection = contexts.dialogSummary?.trim() ? `--- \u5386\u53F2\u5BF9\u8BDD\u6458\u8981 ---
231
+ const requestContextBlocksSection = (contexts.requestContextBlocks ?? []).map((block) => typeof block === "string" ? block.trim() : "").filter((block) => block.length > 0).join(`
232
+
233
+ `);
234
+ const dialogSummarySection = contexts.dialogSummary?.trim() ? `--- 历史对话摘要 ---
298
235
  ${wrapHistoricalSummaryWithReplayGuard(contexts.dialogSummary)}` : "";
299
236
  return compileContextLayers([
300
- // 顶部固定平台层(唯一真源见 agent-runtime/platformStaticPromptLayers.ts)。
301
- ...buildPlatformStaticContextLayers(),
237
+ ...buildPlatformStaticContextLayers({ toolNames: agentTools }),
302
238
  { id: "identity", owner: "platform", cacheScope: "session", content: identitySection },
303
239
  { id: "user-response-language", owner: "platform", cacheScope: "session", content: buildUserResponseLanguageContext({ language: safeLanguage }) },
304
240
  { id: "startup-protocol", owner: "platform", cacheScope: "static", content: startupProtocol },
@@ -341,7 +277,6 @@ ${wrapHistoricalSummaryWithReplayGuard(contexts.dialogSummary)}` : "";
341
277
  { id: "editing-context", owner: "runtime", cacheScope: "turn", content: editingContextSection }
342
278
  ]);
343
279
  };
344
-
345
280
  // packages/integrations/openai/generateOpenAIRequestBody.ts
346
281
  var isClaudeModel = (model) => !!model && (model.includes("claude") || model.includes("anthropic"));
347
282
  var applyClaudeCache = (stableContent, dynamicContent) => {
@@ -359,8 +294,10 @@ var applyClaudeCache = (stableContent, dynamicContent) => {
359
294
  return parts.length > 0 ? parts : stableContent;
360
295
  };
361
296
  var prependPromptMessage = (messages, agentConfig, resolvedModel, language, contexts, prependSystemPrompt = true, preservePromptBoundary = false, preservePromptProvenance = preservePromptBoundary) => {
362
- if (!prependSystemPrompt) return messages;
363
- if (!contexts && !agentConfig.prompt) return messages;
297
+ if (!prependSystemPrompt)
298
+ return messages;
299
+ if (!contexts && !agentConfig.prompt)
300
+ return messages;
364
301
  const dispatchIntent = detectDispatchIntentFromMessages(messages);
365
302
  if (isClaudeModel(resolvedModel)) {
366
303
  const compiled = buildSystemPromptContext({
@@ -370,13 +307,11 @@ var prependPromptMessage = (messages, agentConfig, resolvedModel, language, cont
370
307
  dispatchIntent,
371
308
  callerModel: agentConfig?.model
372
309
  });
373
- if (!compiled.content.trim()) return messages;
374
- const content = applyClaudeCache(
375
- compiled.stablePrefixContent,
376
- compiled.dynamicContent
377
- );
378
- const systemMessage2 = { role: "system", content };
379
- return [systemMessage2, ...messages];
310
+ if (!compiled.content.trim())
311
+ return messages;
312
+ const content = applyClaudeCache(compiled.stablePrefixContent, compiled.dynamicContent);
313
+ const systemMessage = { role: "system", content };
314
+ return [systemMessage, ...messages];
380
315
  }
381
316
  const promptProvenance = preservePromptProvenance && agentConfig.prompt?.trim() ? { agent_prompt_in_messages: true } : {};
382
317
  if (preservePromptBoundary) {
@@ -387,7 +322,8 @@ var prependPromptMessage = (messages, agentConfig, resolvedModel, language, cont
387
322
  dispatchIntent,
388
323
  callerModel: agentConfig?.model
389
324
  });
390
- if (!compiled.content.trim()) return messages;
325
+ if (!compiled.content.trim())
326
+ return messages;
391
327
  return [{
392
328
  role: "system",
393
329
  content: compiled.content,
@@ -396,24 +332,31 @@ var prependPromptMessage = (messages, agentConfig, resolvedModel, language, cont
396
332
  }, ...messages];
397
333
  }
398
334
  const promptContent = buildSystemPrompt({ agentConfig, language, contexts, dispatchIntent, callerModel: agentConfig?.model });
399
- if (!promptContent.trim()) return messages;
335
+ if (!promptContent.trim())
336
+ return messages;
400
337
  const systemMessage = { role: "system", content: promptContent, ...promptProvenance };
401
338
  return [systemMessage, ...messages];
402
339
  };
403
340
  var resolveLlamaCppThinkingToggle = (agentConfig) => {
404
- if (!isLoopbackUrl(agentConfig.customProviderUrl) || !/qwen/i.test(agentConfig.model ?? "")) return void 0;
341
+ if (!isLoopbackUrl(agentConfig.customProviderUrl) || !/qwen/i.test(agentConfig.model ?? ""))
342
+ return;
405
343
  const effort = agentConfig.reasoning_effort?.toLowerCase();
406
- return effort ? effort !== "none" && effort !== "off" : agentConfig.enableThinking ?? void 0;
344
+ return effort ? effort !== "none" && effort !== "off" : agentConfig.enableThinking ?? undefined;
407
345
  };
408
346
  var shouldDisableKimiThinking = (agentConfig, providerName, resolvedModel) => {
409
- if (agentConfig.reasoning_effort || agentConfig.enableThinking !== false) return false;
410
- if (providerName === "deepinfra") return isDeepInfraKimiModel(resolvedModel);
411
- if (providerName === "fireworks") return isFireworksKimiModel(resolvedModel);
347
+ if (agentConfig.reasoning_effort || agentConfig.enableThinking !== false)
348
+ return false;
349
+ if (providerName === "deepinfra")
350
+ return isDeepInfraKimiModel(resolvedModel);
351
+ if (providerName === "fireworks")
352
+ return isFireworksKimiModel(resolvedModel);
412
353
  return false;
413
354
  };
414
355
  var normalizeChatCompletionsContent = (content) => {
415
- if (typeof content === "string" || Array.isArray(content)) return content;
416
- if (content == null) return null;
356
+ if (typeof content === "string" || Array.isArray(content))
357
+ return content;
358
+ if (content == null)
359
+ return null;
417
360
  return JSON.stringify(content);
418
361
  };
419
362
  var sanitizeChatCompletionsMessage = (message, options) => {
@@ -422,21 +365,15 @@ var sanitizeChatCompletionsMessage = (message, options) => {
422
365
  content: normalizeChatCompletionsContent(message.content)
423
366
  };
424
367
  const name = asOptionalTrimmedString(message.name);
425
- if (name) sanitized.name = name;
426
- const shouldStripReasoning = shouldStripReasoningContentForOutbound(
427
- options?.provider,
428
- options?.model
429
- );
368
+ if (name)
369
+ sanitized.name = name;
370
+ const shouldStripReasoning = shouldStripReasoningContentForOutbound(options?.provider, options?.model);
430
371
  return preserveAgentStateFields(message, sanitized, {
431
372
  targetProvider: options?.provider,
432
373
  targetModel: options?.model,
433
374
  stripReasoningContent: shouldStripReasoning,
434
375
  ...options?.shapingCounts ? { shapingCounts: options.shapingCounts } : {},
435
- ...resolveReasoningReplayOptions(
436
- options?.provider,
437
- options?.model,
438
- shouldStripReasoning
439
- )
376
+ ...resolveReasoningReplayOptions(options?.provider, options?.model, shouldStripReasoning)
440
377
  });
441
378
  };
442
379
  var buildRequestBody = (options) => {
@@ -462,7 +399,7 @@ var buildRequestBody = (options) => {
462
399
  ...shapingCounts ? { shapingCounts } : {}
463
400
  });
464
401
  if (message.role === "system") {
465
- if (preservePromptBoundary && message.stable_prefix_chars !== void 0) {
402
+ if (preservePromptBoundary && message.stable_prefix_chars !== undefined) {
466
403
  sanitized.stable_prefix_chars = message.stable_prefix_chars;
467
404
  }
468
405
  if (preservePromptProvenance && message.agent_prompt_in_messages === true) {
@@ -483,22 +420,21 @@ var buildRequestBody = (options) => {
483
420
  Object.assign(bodyData, usageRequestOptions);
484
421
  const effectiveProviderForReasoning = providerName?.toLowerCase() === "openrouter" || customProviderUrl?.toLowerCase().includes("openrouter.ai") ? "openrouter" : providerName;
485
422
  if (reasoning_effort && isModelSupportReasoningEffort(model, effectiveProviderForReasoning)) {
486
- const clamped = clampReasoningEffort(
487
- reasoning_effort,
488
- effectiveProviderForReasoning,
489
- model
490
- );
423
+ const clamped = clampReasoningEffort(reasoning_effort, effectiveProviderForReasoning, model);
491
424
  if (clamped) {
492
425
  bodyData.reasoning_effort = clamped;
493
426
  }
494
427
  }
495
- if (typeof temperature === "number") bodyData.temperature = temperature;
496
- if (typeof top_p === "number") bodyData.top_p = top_p;
428
+ if (typeof temperature === "number")
429
+ bodyData.temperature = temperature;
430
+ if (typeof top_p === "number")
431
+ bodyData.top_p = top_p;
497
432
  if (typeof frequency_penalty === "number")
498
433
  bodyData.frequency_penalty = frequency_penalty;
499
434
  if (typeof presence_penalty === "number")
500
435
  bodyData.presence_penalty = presence_penalty;
501
- if (typeof max_tokens === "number") bodyData.max_tokens = max_tokens;
436
+ if (typeof max_tokens === "number")
437
+ bodyData.max_tokens = max_tokens;
502
438
  return bodyData;
503
439
  };
504
440
  var generateOpenAIRequestBody = (agentConfig, providerName, messages, contexts, stableMessages = [], prependSystemPrompt = true, shapingCounts, preservePromptBoundary = false, preservePromptProvenance = preservePromptBoundary) => {
@@ -519,24 +455,13 @@ var generateOpenAIRequestBody = (agentConfig, providerName, messages, contexts,
519
455
  const lastPartIdx = targetContent.length - 1;
520
456
  processedStable[idx] = {
521
457
  ...processedStable[idx],
522
- content: targetContent.map(
523
- (part, pIdx) => pIdx === lastPartIdx && typeof part === "object" && part !== null ? { ...part, cache_control: { type: "ephemeral" } } : part
524
- )
458
+ content: targetContent.map((part, pIdx) => pIdx === lastPartIdx && typeof part === "object" && part !== null ? { ...part, cache_control: { type: "ephemeral" } } : part)
525
459
  };
526
460
  }
527
461
  }
528
462
  }
529
463
  const fullMessages = [...processedStable, ...messages];
530
- const messagesWithPrompt = prependPromptMessage(
531
- fullMessages,
532
- agentConfig,
533
- resolvedModel,
534
- typeof navigator !== "undefined" ? navigator.language : "en",
535
- contexts,
536
- prependSystemPrompt,
537
- preservePromptBoundary,
538
- preservePromptProvenance
539
- );
464
+ const messagesWithPrompt = prependPromptMessage(fullMessages, agentConfig, resolvedModel, typeof navigator !== "undefined" ? navigator.language : "en", contexts, prependSystemPrompt, preservePromptBoundary, preservePromptProvenance);
540
465
  const requestBody = buildRequestBody({
541
466
  model: resolvedModel,
542
467
  messages: messagesWithPrompt,
@@ -553,7 +478,7 @@ var generateOpenAIRequestBody = (agentConfig, providerName, messages, contexts,
553
478
  ...shapingCounts ? { shapingCounts } : {}
554
479
  });
555
480
  const llamaCppThinking = resolveLlamaCppThinkingToggle(agentConfig);
556
- if (llamaCppThinking !== void 0) {
481
+ if (llamaCppThinking !== undefined) {
557
482
  delete requestBody.reasoning_effort;
558
483
  requestBody.chat_template_kwargs = {
559
484
  ...requestBody.chat_template_kwargs ?? {},
@@ -566,14 +491,16 @@ var generateOpenAIRequestBody = (agentConfig, providerName, messages, contexts,
566
491
  requestBody.thinking = { type: "disabled" };
567
492
  } else if (effort) {
568
493
  const depth = clampReasoningEffort(effort, "mimo", resolvedModel);
569
- if (depth) requestBody.reasoning_effort = depth;
494
+ if (depth)
495
+ requestBody.reasoning_effort = depth;
570
496
  } else if (agentConfig.enableThinking !== true) {
571
497
  requestBody.thinking = { type: "disabled" };
572
498
  }
573
499
  }
574
500
  if (shouldDisableKimiThinking(agentConfig, providerName, resolvedModel)) {
575
501
  requestBody.thinking = { type: "disabled" };
576
- if (providerName !== "deepinfra") requestBody.reasoning_effort = "none";
502
+ if (providerName !== "deepinfra")
503
+ requestBody.reasoning_effort = "none";
577
504
  requestBody.reasoning = { enabled: false };
578
505
  }
579
506
  return normalizeChatCompletionsBodyForProvider({
@@ -584,11 +511,61 @@ var generateOpenAIRequestBody = (agentConfig, providerName, messages, contexts,
584
511
  });
585
512
  };
586
513
 
514
+ // packages/agent-runtime/responsesConversationState.ts
515
+ function supportsResponsesConversationState(agent) {
516
+ return normalizeIdentityPart(agent.provider) === "openai";
517
+ }
518
+ var normalizeIdentityPart = (value) => typeof value === "string" ? value.trim().toLowerCase() : "";
519
+ function normalizeResponsesConversationState(value) {
520
+ if (!value || typeof value !== "object")
521
+ return null;
522
+ const raw = value;
523
+ const provider = normalizeIdentityPart(raw.provider);
524
+ const model = normalizeIdentityPart(raw.model);
525
+ const responseId = typeof raw.responseId === "string" ? raw.responseId.trim() : "";
526
+ if (!provider || !model || !responseId)
527
+ return null;
528
+ return { provider, model, responseId };
529
+ }
530
+ function selectResponsesConversationState(value, agent) {
531
+ if (!supportsResponsesConversationState(agent))
532
+ return null;
533
+ const state = normalizeResponsesConversationState(value);
534
+ if (!state)
535
+ return null;
536
+ if (state.provider !== normalizeIdentityPart(agent.provider))
537
+ return null;
538
+ if (state.model !== normalizeIdentityPart(agent.model))
539
+ return null;
540
+ return state;
541
+ }
542
+ function updateResponsesConversationState(agent, responseId) {
543
+ if (!supportsResponsesConversationState(agent))
544
+ return null;
545
+ const provider = normalizeIdentityPart(agent.provider);
546
+ const model = normalizeIdentityPart(agent.model);
547
+ const normalizedResponseId = typeof responseId === "string" ? responseId.trim() : "";
548
+ if (!provider || !model || !normalizedResponseId)
549
+ return null;
550
+ return { provider, model, responseId: normalizedResponseId };
551
+ }
552
+ function isResponsesConversationStateRejection(status, responseBody) {
553
+ if (![400, 404, 409].includes(status))
554
+ return false;
555
+ const text = typeof responseBody === "string" ? responseBody.trim().toLowerCase() : "";
556
+ if (!text)
557
+ return false;
558
+ const mentionsResponseState = /previous[\s_-]*response/.test(text) || /response[\s_-]*(?:id|state)/.test(text);
559
+ const rejectsState = /not[\s_-]*found/.test(text) || /does not exist/.test(text) || /invalid/.test(text) || /expired/.test(text) || /unknown/.test(text);
560
+ return mentionsResponseState && rejectsState;
561
+ }
562
+
587
563
  // packages/integrations/openai/generateResponseRequestBody.ts
588
- var DEFAULT_RESPONSES_COMPACTION_THRESHOLD = 2e5;
564
+ var DEFAULT_RESPONSES_COMPACTION_THRESHOLD = 200000;
589
565
  function usesGpt62DeveloperPrefix(agentConfig) {
590
566
  const provider = asTrimmedLowercaseString(agentConfig.provider);
591
- if (agentConfig.customProviderUrl || agentConfig.apiSource === "custom") return false;
567
+ if (agentConfig.customProviderUrl || agentConfig.apiSource === "custom")
568
+ return false;
592
569
  let model = asTrimmedLowercaseString(agentConfig.model).replace(/^openai\//, "");
593
570
  if (provider === "nolo") {
594
571
  const route = resolvePlatformHostedRouting(agentConfig.model);
@@ -602,14 +579,12 @@ function usesGpt62DeveloperPrefix(agentConfig) {
602
579
  return isGpt62DeveloperPrefixModel(model);
603
580
  }
604
581
  function resolveResponsesCompactionThreshold(agentConfig) {
605
- const configured = Number(
606
- agentConfig.responsesCompactionThreshold ?? agentConfig.responses_compaction_threshold
607
- );
582
+ const configured = Number(agentConfig.responsesCompactionThreshold ?? agentConfig.responses_compaction_threshold);
608
583
  return Number.isFinite(configured) && configured > 0 ? Math.floor(configured) : DEFAULT_RESPONSES_COMPACTION_THRESHOLD;
609
584
  }
610
585
  function selectResponsesContinuationMessages(msgs) {
611
586
  let lastAssistantIndex = -1;
612
- for (let index = msgs.length - 1; index >= 0; index -= 1) {
587
+ for (let index = msgs.length - 1;index >= 0; index -= 1) {
613
588
  if (msgs[index]?.role === "assistant") {
614
589
  lastAssistantIndex = index;
615
590
  break;
@@ -620,15 +595,10 @@ function selectResponsesContinuationMessages(msgs) {
620
595
  }
621
596
  function generateResponseRequestBody(agentConfig, msgs, contexts, prependSystemPrompt = true, responsesState) {
622
597
  const language = typeof navigator !== "undefined" && navigator.language ? navigator.language : "zh-CN";
623
- const state = selectResponsesConversationState(
624
- responsesState === void 0 ? agentConfig.responsesState : responsesState,
625
- agentConfig
626
- );
598
+ const state = selectResponsesConversationState(responsesState === undefined ? agentConfig.responsesState : responsesState, agentConfig);
627
599
  const supportsServerState = supportsResponsesConversationState(agentConfig);
628
600
  const stateful = supportsServerState && state && agentConfig.store !== false ? state : null;
629
- const input = convertMessagesToResponsesInput(
630
- stateful ? selectResponsesContinuationMessages(msgs) : msgs
631
- );
601
+ const input = convertMessagesToResponsesInput(stateful ? selectResponsesContinuationMessages(msgs) : msgs);
632
602
  const body = {
633
603
  model: agentConfig.model,
634
604
  input,
@@ -640,11 +610,10 @@ function generateResponseRequestBody(agentConfig, msgs, contexts, prependSystemP
640
610
  agentConfig,
641
611
  language,
642
612
  contexts,
643
- // 按当前用户输入检测派发意图:无意图只注入最小派发协议(安全硬门常在)。
644
613
  dispatchIntent: detectDispatchIntentFromMessages(msgs),
645
614
  callerModel: agentConfig?.model
646
615
  });
647
- const legacyContinuation = supportsServerState && responsesState === void 0 && agentConfig.previous_response_id !== void 0;
616
+ const legacyContinuation = supportsServerState && responsesState === undefined && agentConfig.previous_response_id !== undefined;
648
617
  if (!stateful && !legacyContinuation && usesGpt62DeveloperPrefix(agentConfig)) {
649
618
  if (compiled.stablePrefixContent) {
650
619
  input.unshift({
@@ -653,35 +622,36 @@ function generateResponseRequestBody(agentConfig, msgs, contexts, prependSystemP
653
622
  content: [{ type: "input_text", text: compiled.stablePrefixContent }]
654
623
  });
655
624
  }
656
- if (compiled.dynamicContent) body.instructions = compiled.dynamicContent;
625
+ if (compiled.dynamicContent)
626
+ body.instructions = compiled.dynamicContent;
657
627
  } else {
658
628
  body.instructions = compiled.content;
659
629
  }
660
630
  }
661
- if (agentConfig.temperature !== void 0) {
631
+ if (agentConfig.temperature !== undefined) {
662
632
  body.temperature = agentConfig.temperature;
663
633
  }
664
- if (agentConfig.top_p !== void 0) {
634
+ if (agentConfig.top_p !== undefined) {
665
635
  body.top_p = agentConfig.top_p;
666
636
  }
667
- if (agentConfig.max_tokens !== void 0) {
637
+ if (agentConfig.max_tokens !== undefined) {
668
638
  body.max_output_tokens = agentConfig.max_tokens;
669
639
  }
670
- if (agentConfig.max_tool_calls !== void 0) {
640
+ if (agentConfig.max_tool_calls !== undefined) {
671
641
  body.max_tool_calls = agentConfig.max_tool_calls;
672
642
  }
673
- if (agentConfig.user !== void 0) {
643
+ if (agentConfig.user !== undefined) {
674
644
  body.user = agentConfig.user;
675
645
  }
676
- if (agentConfig.include !== void 0) {
646
+ if (agentConfig.include !== undefined) {
677
647
  body.include = agentConfig.include;
678
648
  }
679
- if (agentConfig.metadata !== void 0) {
649
+ if (agentConfig.metadata !== undefined) {
680
650
  body.metadata = agentConfig.metadata;
681
651
  }
682
652
  if (stateful) {
683
653
  body.previous_response_id = stateful.responseId;
684
- if (agentConfig.context_management === void 0) {
654
+ if (agentConfig.context_management === undefined) {
685
655
  body.context_management = [
686
656
  {
687
657
  type: "compaction",
@@ -689,13 +659,13 @@ function generateResponseRequestBody(agentConfig, msgs, contexts, prependSystemP
689
659
  }
690
660
  ];
691
661
  }
692
- } else if (supportsServerState && responsesState === void 0 && agentConfig.previous_response_id !== void 0) {
662
+ } else if (supportsServerState && responsesState === undefined && agentConfig.previous_response_id !== undefined) {
693
663
  body.previous_response_id = agentConfig.previous_response_id;
694
664
  }
695
- if (supportsServerState && agentConfig.store !== void 0) {
665
+ if (supportsServerState && agentConfig.store !== undefined) {
696
666
  body.store = agentConfig.store;
697
667
  }
698
- if (supportsServerState && agentConfig.context_management !== void 0) {
668
+ if (supportsServerState && agentConfig.context_management !== undefined) {
699
669
  body.context_management = agentConfig.context_management;
700
670
  }
701
671
  return body;
@@ -727,7 +697,8 @@ var getImageOutputSettings = (agentConfig, provider) => {
727
697
  }
728
698
  };
729
699
  var withImageOutputPromptGuard = (agentConfig, shouldEnableImage) => {
730
- if (!shouldEnableImage) return agentConfig;
700
+ if (!shouldEnableImage)
701
+ return agentConfig;
731
702
  const basePrompt = asTrimmedString(agentConfig.prompt);
732
703
  if (basePrompt.includes(IMAGE_OUTPUT_EXECUTION_PROMPT)) {
733
704
  return agentConfig;
@@ -740,15 +711,12 @@ ${IMAGE_OUTPUT_EXECUTION_PROMPT}` : IMAGE_OUTPUT_EXECUTION_PROMPT
740
711
  };
741
712
  };
742
713
  var applyImageConfigIfNeeded = (body, agentConfig, provider) => {
743
- const { shouldEnableImage, modelConfig } = getImageOutputSettings(
744
- agentConfig,
745
- provider
746
- );
714
+ const { shouldEnableImage, modelConfig } = getImageOutputSettings(agentConfig, provider);
747
715
  const agentImageCfg = agentConfig.imageConfig;
748
716
  if (!shouldEnableImage || !modelConfig) {
749
717
  return body;
750
718
  }
751
- const modalities = agentImageCfg?.forceModalities ?? modelConfig.defaultModalities ?? (modelConfig.requiresImageModalities ? ["image", "text"] : void 0);
719
+ const modalities = agentImageCfg?.forceModalities ?? modelConfig.defaultModalities ?? (modelConfig.requiresImageModalities ? ["image", "text"] : undefined);
752
720
  if (modalities && !body.modalities) {
753
721
  body.modalities = modalities;
754
722
  }
@@ -769,7 +737,7 @@ var applyImageConfigIfNeeded = (body, agentConfig, provider) => {
769
737
  };
770
738
  function canonicalizeJsonValue(val) {
771
739
  if (val === null || typeof val !== "object") {
772
- return typeof val === "function" ? void 0 : val;
740
+ return typeof val === "function" ? undefined : val;
773
741
  }
774
742
  if (Array.isArray(val)) {
775
743
  return val.map(canonicalizeJsonValue);
@@ -779,7 +747,7 @@ function canonicalizeJsonValue(val) {
779
747
  const res = {};
780
748
  for (const k of sortedKeys) {
781
749
  const v = canonicalizeJsonValue(obj[k]);
782
- if (v !== void 0) {
750
+ if (v !== undefined) {
783
751
  res[k] = v;
784
752
  }
785
753
  }
@@ -791,22 +759,22 @@ function serializeToolsForCacheKey(tools) {
791
759
  }
792
760
  const items = [];
793
761
  for (const tool of tools) {
794
- if (!tool || typeof tool !== "object") continue;
762
+ if (!tool || typeof tool !== "object")
763
+ continue;
795
764
  const t = tool;
796
- const fn = typeof t.function === "object" && t.function !== null ? t.function : void 0;
765
+ const fn = typeof t.function === "object" && t.function !== null ? t.function : undefined;
797
766
  const name = fn?.name ?? t.name ?? (t.type ? String(t.type) : "");
798
767
  const description = fn?.description ?? t.description ?? "";
799
- const rawParams = fn?.parameters !== void 0 ? fn.parameters : t.parameters;
800
- const parameters = rawParams !== void 0 ? canonicalizeJsonValue(rawParams) ?? null : null;
801
- items.push(
802
- JSON.stringify({
803
- description: typeof description === "string" ? description : String(description),
804
- name: typeof name === "string" ? name : String(name),
805
- parameters
806
- })
807
- );
808
- }
809
- if (items.length === 0) return "";
768
+ const rawParams = fn?.parameters !== undefined ? fn.parameters : t.parameters;
769
+ const parameters = rawParams !== undefined ? canonicalizeJsonValue(rawParams) ?? null : null;
770
+ items.push(JSON.stringify({
771
+ description: typeof description === "string" ? description : String(description),
772
+ name: typeof name === "string" ? name : String(name),
773
+ parameters
774
+ }));
775
+ }
776
+ if (items.length === 0)
777
+ return "";
810
778
  items.sort();
811
779
  return items.join(";");
812
780
  }
@@ -821,1014 +789,1027 @@ var generateRequestBody = ({
821
789
  }) => {
822
790
  const provider = (agentConfig.provider || "").toLowerCase();
823
791
  const imageSettings = getImageOutputSettings(agentConfig, provider);
824
- const agentConfigForRequest = withImageOutputPromptGuard(
825
- agentConfig,
826
- imageSettings.shouldEnableImage
827
- );
792
+ const agentConfigForRequest = withImageOutputPromptGuard(agentConfig, imageSettings.shouldEnableImage);
828
793
  const plan = resolveAgentCallPlan(agentConfigForRequest, {});
829
794
  const clientWire = resolveClientWire(plan);
830
795
  if (clientWire === "responses") {
831
- const body = generateResponseRequestBody(
832
- agentConfigForRequest,
833
- [...stableMessages ?? [], ...messages],
834
- contexts,
835
- prependSystemPrompt,
836
- responsesState
837
- );
796
+ const body = generateResponseRequestBody(agentConfigForRequest, [...stableMessages ?? [], ...messages], contexts, prependSystemPrompt, responsesState);
838
797
  const serializedTools = serializeToolsForCacheKey(tools);
839
- body.prompt_cache_key ??= stablePromptCacheKey(
840
- [
841
- agentConfigForRequest.model,
842
- agentConfigForRequest.dbKey ?? "",
843
- agentConfigForRequest.prompt ?? "",
844
- serializedTools
845
- ],
846
- "nolo-openai"
847
- );
798
+ body.prompt_cache_key ??= stablePromptCacheKey([
799
+ agentConfigForRequest.model,
800
+ agentConfigForRequest.dbKey ?? "",
801
+ agentConfigForRequest.prompt ?? "",
802
+ serializedTools
803
+ ], "nolo-openai");
848
804
  return body;
849
805
  }
850
806
  const codexOAuth = plan.authMethod.kind === "oauth" && plan.authMethod.ref === "chatgpt";
851
- const baseBody = generateOpenAIRequestBody(
852
- agentConfigForRequest,
853
- provider,
854
- messages,
855
- contexts,
856
- stableMessages,
857
- prependSystemPrompt,
858
- void 0,
859
- codexOAuth && usesCodexDeveloperPrefix(agentConfigForRequest, agentConfigForRequest.model),
860
- codexOAuth
861
- );
807
+ const baseBody = generateOpenAIRequestBody(agentConfigForRequest, provider, messages, contexts, stableMessages, prependSystemPrompt, undefined, codexOAuth && usesCodexDeveloperPrefix(agentConfigForRequest, agentConfigForRequest.model), codexOAuth);
862
808
  return applyImageConfigIfNeeded(baseBody, agentConfigForRequest, provider);
863
809
  };
864
810
 
865
- // packages/ai/chat/resolveDirectRequestApiKey.ts
866
- var DIRECT_API_KEY_UNAVAILABLE_MESSAGE = "\u5F53\u524D\u6B65\u9AA4\u9700\u8981\u63D0\u4F9B API \u51ED\u636E\uFF0C\u8BF7\u91CD\u65B0\u63D0\u4F9B\u5BC6\u94A5\uFF0C\u6216\u786E\u8BA4\u672C\u673A\u51ED\u636E\u53EF\u7528\u3002";
867
- var DirectApiKeyResolutionError = class extends Error {
868
- kind = "credential_missing";
869
- credentialRef;
870
- constructor(credentialRefOrOptions, message = DIRECT_API_KEY_UNAVAILABLE_MESSAGE) {
871
- let resolvedRef;
872
- let resolvedMessage = DIRECT_API_KEY_UNAVAILABLE_MESSAGE;
873
- if (typeof credentialRefOrOptions === "string") {
874
- resolvedRef = credentialRefOrOptions;
875
- if (message !== DIRECT_API_KEY_UNAVAILABLE_MESSAGE) {
876
- resolvedMessage = message;
877
- }
878
- } else if (credentialRefOrOptions && typeof credentialRefOrOptions === "object") {
879
- resolvedRef = credentialRefOrOptions.credentialRef;
880
- resolvedMessage = credentialRefOrOptions.message ?? DIRECT_API_KEY_UNAVAILABLE_MESSAGE;
811
+ // packages/core/redactUrlUserinfo.ts
812
+ var REDACTED_USERINFO = "[REDACTED]@";
813
+ var REDACTED = "[REDACTED]";
814
+ var SPECIAL_SCHEMES = new Set(["http", "https", "ws", "wss", "ftp"]);
815
+ var MAX_SCHEME_CHARS = 8;
816
+ var isTabOrNewline = (char) => char === "\t" || char === `
817
+ ` || char === "\r";
818
+ var isAsciiAlpha = (char) => char >= "a" && char <= "z" || char >= "A" && char <= "Z";
819
+ var isSchemeChar = (char) => isAsciiAlpha(char) || char >= "0" && char <= "9" || char === "+" || char === "-" || char === ".";
820
+ var isPrecededBySchemeWord = (text, idx) => {
821
+ let index = idx - 1;
822
+ if (index < 0 || !isSchemeChar(text[index]))
823
+ return false;
824
+ while (index > 0 && isSchemeChar(text[index - 1]))
825
+ index -= 1;
826
+ return isAsciiAlpha(text[index]);
827
+ };
828
+ var matchSpecialSchemeBeforeColon = (text, colonIdx) => {
829
+ let chars = "";
830
+ let index = colonIdx - 1;
831
+ while (index >= 0 && chars.length < 5) {
832
+ const char = text[index];
833
+ if (isTabOrNewline(char)) {
834
+ index -= 1;
835
+ continue;
881
836
  }
882
- super(resolvedMessage);
883
- this.name = "DirectApiKeyResolutionError";
884
- this.credentialRef = resolvedRef;
837
+ if (!isAsciiAlpha(char))
838
+ break;
839
+ chars = char.toLowerCase() + chars;
840
+ if (SPECIAL_SCHEMES.has(chars) && !isPrecededBySchemeWord(text, index))
841
+ return true;
842
+ index -= 1;
885
843
  }
844
+ return false;
886
845
  };
887
- var createDirectCredentialBroker = createFileCredentialBroker;
888
- function readNonEmpty(value) {
889
- return asTrimmedString(value);
890
- }
891
- async function resolveDirectRequestApiKey(agentConfig, options) {
892
- const rawKey = readNonEmpty(agentConfig.apiKey);
893
- if (rawKey) return rawKey;
894
- const credentialRef = readNonEmpty(agentConfig.credentialRef);
895
- if (!credentialRef) return void 0;
896
- const factory = options?.brokerFactory ?? createDirectCredentialBroker;
897
- const broker = factory();
898
- const local = await safeBrokerGet(broker, credentialRef);
899
- if (local) return local;
900
- if (isAgentCredentialShared(agentConfig) && credentialRef.startsWith("provider-key:") && options?.providerSecretFetcher) {
901
- const providerSecret = await options.providerSecretFetcher(credentialRef);
902
- if (providerSecret) return providerSecret;
846
+ var isFullSpecialSchemeBeforeColon = (text, colonIdx) => {
847
+ let index = colonIdx - 1;
848
+ let chars = "";
849
+ while (index >= 0 && chars.length <= MAX_SCHEME_CHARS) {
850
+ const char = text[index];
851
+ if (isTabOrNewline(char)) {
852
+ index -= 1;
853
+ continue;
854
+ }
855
+ if (!isSchemeChar(char))
856
+ break;
857
+ chars = char.toLowerCase() + chars;
858
+ index -= 1;
903
859
  }
904
- if (isAgentCredentialShared(agentConfig) && options?.syncFetcher) {
905
- const synced = await options.syncFetcher(credentialRef);
906
- const trimmed = asTrimmedString(synced);
907
- if (trimmed) {
908
- try {
909
- await broker.put(credentialRef, trimmed);
910
- } catch {
911
- }
912
- return trimmed;
860
+ if (chars.length > MAX_SCHEME_CHARS)
861
+ return false;
862
+ if (!isAsciiAlpha(chars[0] ?? ""))
863
+ return false;
864
+ return SPECIAL_SCHEMES.has(chars);
865
+ };
866
+ var hasValidSchemeBeforeColon = (text, colonIdx) => {
867
+ let index = colonIdx - 1;
868
+ let sawAlpha = false;
869
+ while (index >= 0) {
870
+ const char = text[index];
871
+ if (isTabOrNewline(char)) {
872
+ index -= 1;
873
+ continue;
913
874
  }
875
+ if (!isSchemeChar(char))
876
+ break;
877
+ if (isAsciiAlpha(char))
878
+ sawAlpha = true;
879
+ index -= 1;
914
880
  }
915
- throw new DirectApiKeyResolutionError(credentialRef);
916
- }
917
- async function safeBrokerGet(broker, ref) {
918
- try {
919
- return asTrimmedString(await broker.get(ref)) || null;
920
- } catch {
921
- return null;
922
- }
923
- }
924
-
925
- // packages/ai/chat/buildProxyPayload.ts
926
- var buildProxyPayload = (bodyData, api, agentConfig, dialogId) => {
927
- const apiSource = agentConfig.apiSource === "custom" || agentConfig.apiSource === "cli" ? agentConfig.apiSource : void 0;
928
- const provider = bodyData.provider || agentConfig.provider || (apiSource === "custom" ? "custom" : void 0);
929
- const apiKey = resolveOutboundProxyApiKey(agentConfig);
930
- return {
931
- ...bodyData,
932
- url: api,
933
- provider,
934
- agentKey: agentConfig.dbKey,
935
- ...asOptionalTrimmedString(dialogId) ? { dialogId: asOptionalTrimmedString(dialogId) } : {},
936
- ...apiSource ? { apiSource } : {},
937
- ...agentConfig.apiKeyHeader ? { apiKeyHeader: agentConfig.apiKeyHeader } : {},
938
- KEY: apiKey
939
- };
881
+ return sawAlpha;
940
882
  };
941
-
942
- // packages/ai/chat/fetchUtils.ts
943
- var fetchDirectly = async (params) => {
944
- const { api, agentConfig, bodyData, signal, currentServer, token, dialogId } = params;
945
- try {
946
- const apiKey = await resolveDirectRequestApiKey(agentConfig, {
947
- syncFetcher: currentServer && token ? (ref) => fetchServerSyncedCredential({ currentServer, authToken: token }, ref) : void 0,
948
- providerSecretFetcher: isAgentCredentialShared(agentConfig) && currentServer && token ? async (ref) => {
949
- const presetId = ref.startsWith("provider-key:") ? ref.slice("provider-key:".length) : ref;
950
- const local = getLocalProviderSecret(presetId);
951
- if (local) return local;
952
- try {
953
- const response = await fetch(`${currentServer}/api/user-secrets/get?presetId=${encodeURIComponent(presetId)}`, { headers: { Authorization: `Bearer ${token}` } });
954
- if (!response.ok) return null;
955
- return (await response.json()).value ?? null;
956
- } catch {
957
- return null;
958
- }
959
- } : void 0
960
- });
961
- const authHeaders = buildProviderAuthHeaders({
962
- endpoint: api,
963
- apiKey: apiKey ?? "",
964
- apiKeyHeader: agentConfig.apiKeyHeader,
965
- sessionId: dialogId || agentConfig.dbKey || agentConfig.key
966
- });
967
- return await fetch(api, {
968
- method: "POST",
969
- headers: {
970
- "Content-Type": "application/json",
971
- ...authHeaders,
972
- ...api.includes("openrouter.ai") ? {
973
- "HTTP-Referer": "https://nolo.chat",
974
- "X-Title": "nolo"
975
- } : {}
976
- },
977
- body: JSON.stringify(bodyData),
978
- signal
979
- // 可选参数,直接传递
980
- });
981
- } catch (error) {
982
- if (!(error instanceof DirectApiKeyResolutionError) && error?.kind !== "credential_missing") {
983
- console.error("[fetchDirectly] \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25:", error);
883
+ var matchDoubleSlashAfterColon = (text, colonIdx) => {
884
+ let index = colonIdx + 1;
885
+ let slashes = 0;
886
+ while (index < text.length && slashes < 2) {
887
+ const char = text[index];
888
+ if (isTabOrNewline(char)) {
889
+ index += 1;
890
+ continue;
984
891
  }
985
- throw error;
892
+ if (char === "/") {
893
+ slashes += 1;
894
+ index += 1;
895
+ continue;
896
+ }
897
+ return -1;
986
898
  }
899
+ return slashes === 2 ? index : -1;
987
900
  };
988
- var fetchWithServerProxy = async ({
989
- currentServer,
990
- api,
991
- bodyData,
992
- agentConfig,
993
- token,
994
- signal,
995
- dialogId,
996
- onRetry
997
- }) => {
998
- try {
999
- const payload = buildProxyPayload(bodyData, api, agentConfig, dialogId);
1000
- return await performServerProxyFetchWithRetry({
1001
- signal,
1002
- onRetry,
1003
- execute: () => fetch(`${currentServer}${API_ENDPOINTS.CHAT}`, {
1004
- method: "POST",
1005
- headers: {
1006
- "Content-Type": "application/json",
1007
- Authorization: `Bearer ${token}`
1008
- // 使用 Authorization 头传递 token
1009
- },
1010
- body: JSON.stringify(payload),
1011
- signal
1012
- })
1013
- });
1014
- } catch (error) {
1015
- console.error("[fetchWithServerProxy] \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25:", error);
1016
- throw error;
901
+ var skipSpecialAuthorityPrefix = (text, colonIdx) => {
902
+ let index = colonIdx + 1;
903
+ while (index < text.length) {
904
+ const char = text[index];
905
+ if (char === "/" || char === "\\" || isTabOrNewline(char))
906
+ index += 1;
907
+ else
908
+ break;
1017
909
  }
910
+ return index;
1018
911
  };
1019
- var formatFriendlyNetworkErrorMessage = (error) => {
1020
- if (typeof window !== "undefined" && typeof navigator !== "undefined" && navigator.onLine === false) {
1021
- return "\u7F51\u7EDC\u8FDE\u63A5\u5DF2\u65AD\u5F00\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5";
912
+ var authorityCandidates = (text, colonIdx) => {
913
+ const fullSchemeIsSpecial = isFullSpecialSchemeBeforeColon(text, colonIdx);
914
+ if (!fullSchemeIsSpecial && !hasValidSchemeBeforeColon(text, colonIdx))
915
+ return [];
916
+ const candidates = [];
917
+ const afterSlashes = matchDoubleSlashAfterColon(text, colonIdx);
918
+ if (!fullSchemeIsSpecial && afterSlashes !== -1) {
919
+ candidates.push({ start: afterSlashes, isSpecial: false });
1022
920
  }
1023
- const rawMessage = toErrorMessage(error);
1024
- if (/failed to fetch|networkerror|network error|econnrefused|econnreset|socket hang up/i.test(
1025
- rawMessage
1026
- )) {
1027
- return "\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u6216\u4EE3\u7406/VPN\u8BBE\u7F6E";
921
+ if (fullSchemeIsSpecial || matchSpecialSchemeBeforeColon(text, colonIdx)) {
922
+ candidates.push({ start: skipSpecialAuthorityPrefix(text, colonIdx), isSpecial: true });
1028
923
  }
1029
- return rawMessage;
924
+ return candidates;
1030
925
  };
1031
- var performFetchRequest = async (params) => {
1032
- let direct = false;
1033
- try {
1034
- const { agentConfig, bodyData } = params;
1035
- const credentialRef = "credentialRef" in agentConfig && typeof agentConfig.credentialRef === "string" ? agentConfig.credentialRef : void 0;
1036
- const plan = resolveAgentCallPlan({
1037
- key: "",
1038
- provider: bodyData.provider || agentConfig.provider,
1039
- model: agentConfig.model,
1040
- apiSource: agentConfig.apiSource,
1041
- cliProvider: agentConfig.cliProvider ?? void 0,
1042
- customProviderUrl: agentConfig.customProviderUrl,
1043
- apiKey: agentConfig.apiKey ?? void 0,
1044
- apiKeyRef: agentConfig.apiKeyRef,
1045
- credentialRef,
1046
- credentialSynced: agentConfig.credentialSynced,
1047
- useServerProxy: agentConfig.useServerProxy
1048
- }, void 0, { canResolveLocalCredential: true });
1049
- direct = plan.transport === "direct";
1050
- return direct ? await fetchDirectly(params) : await fetchWithServerProxy(params);
1051
- } catch (error) {
1052
- if (error instanceof DirectApiKeyResolutionError || error?.kind === "credential_missing") {
1053
- throw error;
926
+ var findNextStop = (text, from, includeBackslash) => {
927
+ for (let index = from;index < text.length; index += 1) {
928
+ const char = text[index];
929
+ if (char === "/" || char === "?" || char === "#" || includeBackslash && char === "\\") {
930
+ return index;
1054
931
  }
1055
- console.error("[performFetchRequest] \u8BF7\u6C42\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:", error);
1056
- if (params.preserveStructuredError || params.signal?.aborted || error?.name === "AbortError") throw error;
1057
- const rawMessage = toErrorMessage(error);
1058
- const friendlyMsg = direct && /failed to fetch|networkerror|network error|load failed/i.test(rawMessage) && !(typeof navigator !== "undefined" && navigator.onLine === false) ? "\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF1A\u6D4F\u89C8\u5668\u76F4\u8FDE\u670D\u52A1\u5546\u65F6\uFF0C\u53EF\u80FD\u88AB\u670D\u52A1\u5546\u7684\u8DE8\u57DF\u9650\u5236\uFF08CORS\uFF09\u62E6\u622A\u3002" : formatFriendlyNetworkErrorMessage(error);
1059
- throw new Error(
1060
- friendlyMsg.startsWith("\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25") ? friendlyMsg : `\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25: ${friendlyMsg}`
1061
- );
1062
932
  }
933
+ return text.length;
1063
934
  };
1064
-
1065
- // packages/ai/chat/toolCallArgumentGuard.ts
1066
- var INVALID_TOOL_ARGS_REPLACEMENT = '{"_invalid":true,"_reason":"arguments truncated or malformed"}';
1067
- var INVALID_TOOL_ARGS_OUTBOUND_REPLACEMENT = '{"_invalid":true}';
1068
- var INVALID_TOOL_RESULT_HINT = "\u5DE5\u5177\u53C2\u6570 JSON \u88AB\u622A\u65AD\uFF08\u5927\u6982\u7387\u8D85\u51FA\u8F93\u51FA\u957F\u5EA6\uFF09\u3002\u4E0D\u8981\u628A\u5B8C\u6574\u6E90\u7801\u585E\u8FDB\u4E00\u6B21\u5DE5\u5177\u8C03\u7528\uFF1A\u5148\u7528 appFileWrite \u5206\u6587\u4EF6\u591A\u6B21\u5199\u5165\uFF0C\u518D\u8C03\u7528\u4E0D\u5E26\u5185\u8054\u5927\u53C2\u6570\u7684 appPreflight/appDeploy\u3002";
1069
- var ORPHAN_TOOL_RESULT_PLACEHOLDER = '{"error":"tool call was interrupted"}';
1070
- function parseToolCallArguments(args) {
1071
- if (isRecord(args)) {
1072
- return { valid: true, parsed: args };
1073
- }
1074
- if (typeof args !== "string") return { valid: false };
1075
- const trimmed = args.trim();
1076
- if (!trimmed) return { valid: false };
1077
- try {
1078
- const parsed = JSON.parse(trimmed);
1079
- if (!isRecord(parsed)) {
1080
- return { valid: false };
1081
- }
1082
- return { valid: true, parsed };
1083
- } catch {
1084
- return { valid: false };
935
+ var hasNonIgnoredChar = (text, start, end) => {
936
+ for (let index = start;index < end; index += 1) {
937
+ if (!isTabOrNewline(text[index]))
938
+ return true;
1085
939
  }
1086
- }
1087
- function buildInvalidToolCallSelfHealResult(callId, toolName) {
1088
- return JSON.stringify({
1089
- error: true,
1090
- toolCallId: callId,
1091
- ...toolName ? { toolName } : {},
1092
- message: INVALID_TOOL_RESULT_HINT
1093
- });
1094
- }
1095
- function isHexDigit(ch) {
1096
- return ch >= "0" && ch <= "9" || ch >= "a" && ch <= "f" || ch >= "A" && ch <= "F";
1097
- }
1098
- function sanitizeTextContent(text) {
1099
- if (typeof text !== "string") return text;
1100
- let out = "";
1101
- let i = 0;
1102
- const n = text.length;
1103
- while (i < n) {
1104
- const code = text.charCodeAt(i);
1105
- if (code >= 55296 && code <= 56319) {
1106
- const next = i + 1 < n ? text.charCodeAt(i + 1) : -1;
1107
- if (next >= 56320 && next <= 57343) {
1108
- out += text[i] + text[i + 1];
1109
- i += 2;
1110
- continue;
1111
- }
1112
- out += "\uFFFD";
1113
- i += 1;
940
+ return false;
941
+ };
942
+ function redactUrlUserinfo(text) {
943
+ const lastAtInText = text.lastIndexOf("@");
944
+ if (lastAtInText === -1 || !text.includes(":"))
945
+ return text;
946
+ let output = "";
947
+ let cursor = 0;
948
+ let scanFrom = 0;
949
+ let nextAt = -1;
950
+ let nextSpecialStop = -1;
951
+ let nextNonSpecialStop = -1;
952
+ while (scanFrom < lastAtInText) {
953
+ const colonIdx = text.indexOf(":", scanFrom);
954
+ if (colonIdx === -1 || colonIdx >= lastAtInText)
955
+ break;
956
+ scanFrom = colonIdx + 1;
957
+ const candidates = authorityCandidates(text, colonIdx);
958
+ if (candidates.length === 0)
1114
959
  continue;
960
+ let authorityStart = -1;
961
+ let authorityEnd = -1;
962
+ for (const candidate of candidates) {
963
+ if (nextAt < candidate.start) {
964
+ nextAt = text.indexOf("@", candidate.start);
965
+ if (nextAt === -1)
966
+ break;
967
+ }
968
+ const end = candidate.isSpecial ? nextSpecialStop < candidate.start ? nextSpecialStop = findNextStop(text, candidate.start, true) : nextSpecialStop : nextNonSpecialStop < candidate.start ? nextNonSpecialStop = findNextStop(text, candidate.start, false) : nextNonSpecialStop;
969
+ if (nextAt >= end)
970
+ continue;
971
+ authorityStart = candidate.start;
972
+ authorityEnd = end;
973
+ break;
1115
974
  }
1116
- if (code >= 56320 && code <= 57343) {
1117
- out += "\uFFFD";
1118
- i += 1;
975
+ if (authorityStart === -1) {
976
+ if (nextAt === -1)
977
+ break;
1119
978
  continue;
1120
979
  }
1121
- if (code === 92) {
1122
- let backslashRun = 0;
1123
- let k = i;
1124
- while (k >= 0 && text.charCodeAt(k) === 92) {
1125
- backslashRun++;
1126
- k--;
1127
- }
1128
- const alreadyEscaped = backslashRun % 2 === 0;
1129
- const nextCh = i + 1 < n ? text[i + 1] : "";
1130
- if (!alreadyEscaped && (nextCh === "x" || nextCh === "u")) {
1131
- const hexLen = nextCh === "x" ? 2 : 4;
1132
- let hexCount = 0;
1133
- let j = i + 2;
1134
- while (j < n && hexCount < hexLen && isHexDigit(text[j])) {
1135
- hexCount++;
1136
- j++;
1137
- }
1138
- if (hexCount < hexLen) {
1139
- out += "\\\\";
1140
- i += 1;
1141
- continue;
1142
- }
1143
- out += text[i];
1144
- i += 1;
1145
- continue;
1146
- }
1147
- }
1148
- out += text[i];
1149
- i += 1;
1150
- }
1151
- return out;
1152
- }
1153
- function sanitizeContentText(content) {
1154
- if (typeof content === "string") {
1155
- return sanitizeTextContent(content);
1156
- }
1157
- if (Array.isArray(content)) {
1158
- return content.map((part) => {
1159
- if (part && typeof part === "object") {
1160
- const p = part;
1161
- if (typeof p.text === "string") {
1162
- return { ...p, text: sanitizeTextContent(p.text) };
1163
- }
1164
- }
1165
- return part;
1166
- });
1167
- }
1168
- return content;
1169
- }
1170
- function sanitizeResponsesItemText(item) {
1171
- if (!item || typeof item !== "object") return item;
1172
- const type = item.type;
1173
- if (type === "input_text" || type === "output_text") {
1174
- if (typeof item.text === "string") {
1175
- return { ...item, text: sanitizeTextContent(item.text) };
1176
- }
1177
- return item;
1178
- }
1179
- if (type === "function_call_output") {
1180
- if (typeof item.output === "string") {
1181
- return { ...item, output: sanitizeTextContent(item.output) };
1182
- }
1183
- if (Array.isArray(item.output)) {
1184
- return { ...item, output: sanitizeContentText(item.output) };
1185
- }
1186
- return item;
1187
- }
1188
- if (type === "message" && "content" in item) {
1189
- return { ...item, content: sanitizeContentText(item.content) };
1190
- }
1191
- return item;
1192
- }
1193
- function normalizeToolCallArgumentsInPlace(call, replacement) {
1194
- if (!call || typeof call !== "object") return;
1195
- const fn = call.function;
1196
- if (!fn || typeof fn !== "object") return;
1197
- const { valid } = parseToolCallArguments(fn.arguments);
1198
- if (!valid) {
1199
- fn.arguments = replacement;
1200
- } else if (typeof fn.arguments !== "string") {
1201
- try {
1202
- fn.arguments = JSON.stringify(fn.arguments);
1203
- } catch {
1204
- fn.arguments = replacement;
980
+ const lastAt = text.lastIndexOf("@", authorityEnd - 1);
981
+ if (lastAt <= authorityStart)
982
+ continue;
983
+ if (!hasNonIgnoredChar(text, authorityStart, lastAt))
984
+ continue;
985
+ if (text.slice(authorityStart, lastAt) === "[REDACTED]") {
986
+ scanFrom = lastAt + 1;
987
+ continue;
1205
988
  }
989
+ output += `${text.slice(cursor, authorityStart)}${REDACTED_USERINFO}`;
990
+ cursor = lastAt + 1;
991
+ scanFrom = cursor;
1206
992
  }
993
+ return cursor === 0 ? text : output + text.slice(cursor);
1207
994
  }
1208
- function sanitizeOutboundMessages(messages, opts = {}) {
1209
- if (!Array.isArray(messages) || messages.length === 0) return messages ?? [];
1210
- const argsReplacement = opts.argsReplacement ?? INVALID_TOOL_ARGS_OUTBOUND_REPLACEMENT;
1211
- const orphanReplacement = opts.orphanReplacement ?? ORPHAN_TOOL_RESULT_PLACEHOLDER;
1212
- const cloned = messages.map((msg) => ({ ...msg }));
1213
- const answeredCallIds = /* @__PURE__ */ new Set();
1214
- for (const msg of cloned) {
1215
- if (msg?.role === "tool" && typeof msg.tool_call_id === "string") {
1216
- answeredCallIds.add(msg.tool_call_id);
1217
- }
1218
- }
1219
- const result = [];
1220
- for (const msg of cloned) {
1221
- if (msg && typeof msg === "object" && "content" in msg) {
1222
- msg.content = sanitizeContentText(msg.content);
995
+ function redactUrlQueryAndFragment(text) {
996
+ if (!text.includes(":") || !text.includes("?") && !text.includes("#"))
997
+ return text;
998
+ let output = "";
999
+ let cursor = 0;
1000
+ let scanFrom = 0;
1001
+ while (scanFrom < text.length) {
1002
+ const colonIdx = text.indexOf(":", scanFrom);
1003
+ if (colonIdx === -1)
1004
+ break;
1005
+ scanFrom = colonIdx + 1;
1006
+ let urlStart = -1;
1007
+ for (const candidate of authorityCandidates(text, colonIdx)) {
1008
+ if (urlStart === -1 || candidate.start < urlStart)
1009
+ urlStart = candidate.start;
1223
1010
  }
1224
- if (msg?.role === "assistant" && Array.isArray(msg.tool_calls)) {
1225
- msg.tool_calls = msg.tool_calls.map((call) => ({
1226
- ...call,
1227
- function: { ...call?.function ?? {} }
1228
- }));
1229
- for (const call of msg.tool_calls) {
1230
- normalizeToolCallArgumentsInPlace(call, argsReplacement);
1231
- }
1232
- result.push(msg);
1233
- for (const call of msg.tool_calls) {
1234
- const callId = typeof call?.id === "string" ? call.id : void 0;
1235
- if (!callId) continue;
1236
- if (answeredCallIds.has(callId)) continue;
1237
- answeredCallIds.add(callId);
1238
- result.push({
1239
- role: "tool",
1240
- tool_call_id: callId,
1241
- content: orphanReplacement
1242
- });
1243
- }
1011
+ if (urlStart === -1 && hasValidSchemeBeforeColon(text, colonIdx))
1012
+ urlStart = colonIdx + 1;
1013
+ if (urlStart === -1)
1244
1014
  continue;
1245
- }
1246
- result.push(msg);
1247
- }
1248
- return result;
1249
- }
1250
- function sanitizeOutboundResponsesInput(input, opts = {}) {
1251
- if (!Array.isArray(input) || input.length === 0) return input ?? [];
1252
- const argsReplacement = opts.argsReplacement ?? INVALID_TOOL_ARGS_OUTBOUND_REPLACEMENT;
1253
- const orphanReplacement = opts.orphanReplacement ?? ORPHAN_TOOL_RESULT_PLACEHOLDER;
1254
- const answeredCallIds = /* @__PURE__ */ new Set();
1255
- for (const item of input) {
1256
- if (item?.type === "function_call_output" && typeof item.call_id === "string") {
1257
- answeredCallIds.add(item.call_id);
1258
- }
1259
- }
1260
- const result = [];
1261
- for (const item of input) {
1262
- if (item?.type === "function_call") {
1263
- const cloned = { ...item };
1264
- const { valid } = parseToolCallArguments(cloned.arguments);
1265
- if (!valid) {
1266
- cloned.arguments = argsReplacement;
1267
- } else if (typeof cloned.arguments !== "string") {
1268
- try {
1269
- cloned.arguments = JSON.stringify(cloned.arguments);
1270
- } catch {
1271
- cloned.arguments = argsReplacement;
1272
- }
1273
- }
1274
- result.push(cloned);
1275
- const callId = typeof cloned.call_id === "string" ? cloned.call_id : void 0;
1276
- if (callId && !answeredCallIds.has(callId)) {
1277
- answeredCallIds.add(callId);
1278
- result.push({
1279
- type: "function_call_output",
1280
- call_id: callId,
1281
- output: orphanReplacement
1282
- });
1283
- }
1015
+ if (urlStart < cursor)
1284
1016
  continue;
1017
+ let marker = -1;
1018
+ for (let index = urlStart;index < text.length; index += 1) {
1019
+ const char = text[index];
1020
+ if (char === "?" || char === "#") {
1021
+ marker = index;
1022
+ break;
1023
+ }
1285
1024
  }
1286
- result.push(sanitizeResponsesItemText(item));
1025
+ if (marker === -1)
1026
+ break;
1027
+ output += `${text.slice(cursor, marker)}${text[marker]}${REDACTED}`;
1028
+ cursor = text.length;
1029
+ scanFrom = text.length;
1287
1030
  }
1288
- return result;
1031
+ return cursor === 0 ? text : output + text.slice(cursor);
1289
1032
  }
1290
- function sanitizeOutboundBody(body) {
1291
- const next = { ...body };
1292
- if (Array.isArray(body.messages)) {
1293
- next.messages = sanitizeOutboundMessages(body.messages);
1294
- } else if (Array.isArray(body.input)) {
1295
- next.input = sanitizeOutboundResponsesInput(body.input);
1033
+
1034
+ // packages/ai/agent/toolErrorReport.ts
1035
+ var TOOL_ERROR_REPORT_PATH = "/api/diagnostics/tool-errors";
1036
+ var REPORT_TIMEOUT_MS = 3000;
1037
+ var MAX_INFLIGHT_REPORTS = 1;
1038
+ var MAX_DEDUPE_ENTRIES = 100;
1039
+ var MESSAGE_MAX_CHARS = 1000;
1040
+ var STACK_MAX_CHARS = 4000;
1041
+ var ERROR_CLASS_MAX_CHARS = 120;
1042
+ var IDENTIFIER_MAX_CHARS = 200;
1043
+ var TOOL_ERROR_REPORT_MAX_BODY_BYTES = 16 * 1024;
1044
+ var CONTROL_CHARS_PATTERN = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;
1045
+ var REDACTED2 = "[REDACTED]";
1046
+ var TOOL_ERROR_REPORT_ALLOWED_FIELDS = [
1047
+ "dialogId",
1048
+ "callId",
1049
+ "toolName",
1050
+ "errorClass",
1051
+ "message",
1052
+ "stack",
1053
+ "clientVersion"
1054
+ ];
1055
+ var dedupeKeys = new Map;
1056
+ var inflightReports = 0;
1057
+ var sanitizedBoundedString = (value, maxChars) => {
1058
+ if (typeof value !== "string")
1059
+ return;
1060
+ const cleaned = sanitizeToolErrorText(value).trim();
1061
+ if (!cleaned)
1062
+ return;
1063
+ return cleaned.length > maxChars ? cleaned.slice(0, maxChars) : cleaned;
1064
+ };
1065
+ function sanitizeToolErrorText(input) {
1066
+ if (typeof input !== "string" || !input)
1067
+ return "";
1068
+ let text = input;
1069
+ text = text.replace(CONTROL_CHARS_PATTERN, "");
1070
+ text = redactUrlUserinfo(text);
1071
+ text = redactUrlQueryAndFragment(text);
1072
+ text = text.replace(/([?&](?:access[_-]?token|refresh[_-]?token|api[_-]?key|apikey|token|secret|password|sig|signature|key)=)[^&\s"'<>[\]]+/gi, (_match, prefix) => `${prefix}${REDACTED2}`);
1073
+ text = text.replace(/\b(bearer)\s+[A-Za-z0-9._~+/=-]{4,}/gi, (_match, scheme) => `${scheme} ${REDACTED2}`);
1074
+ text = text.replace(/\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\b/g, REDACTED2);
1075
+ text = text.replace(/((?:api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|token|password|secret|authorization)["']?\s*[:=]\s*)("?)([^\s"',;}\][]+)/gi, (_match, prefix, quote) => `${prefix}${quote}${REDACTED2}`);
1076
+ text = text.replace(/\bsk-[A-Za-z0-9_-]{12,}/g, REDACTED2);
1077
+ return text;
1078
+ }
1079
+ var resolveErrorClass = (error) => {
1080
+ if (error && typeof error === "object") {
1081
+ const record = error;
1082
+ const name = sanitizedBoundedString(record.name, ERROR_CLASS_MAX_CHARS) ?? sanitizedBoundedString(record.constructor?.name, ERROR_CLASS_MAX_CHARS);
1083
+ if (name)
1084
+ return name;
1085
+ return "Error";
1296
1086
  }
1297
- return next;
1087
+ return "Error";
1088
+ };
1089
+ var resolveErrorMessage = (error, errorClass) => {
1090
+ const raw = error && typeof error === "object" ? error.message : error;
1091
+ const text = typeof raw === "string" ? raw : raw === undefined || raw === null ? "" : String(raw);
1092
+ const sanitized = sanitizeToolErrorText(text).trim();
1093
+ const bounded = sanitized.length > MESSAGE_MAX_CHARS ? sanitized.slice(0, MESSAGE_MAX_CHARS) : sanitized;
1094
+ return bounded || errorClass;
1095
+ };
1096
+ var resolveStack = (error) => {
1097
+ if (!error || typeof error !== "object")
1098
+ return;
1099
+ const stack = error.stack;
1100
+ if (typeof stack !== "string")
1101
+ return;
1102
+ const sanitized = sanitizeToolErrorText(stack).trim();
1103
+ if (!sanitized)
1104
+ return;
1105
+ return sanitized.length > STACK_MAX_CHARS ? sanitized.slice(0, STACK_MAX_CHARS) : sanitized;
1106
+ };
1107
+ function buildToolErrorReportPayload(input) {
1108
+ const dialogId = sanitizedBoundedString(input.dialogId, IDENTIFIER_MAX_CHARS);
1109
+ const callId = sanitizedBoundedString(input.callId, IDENTIFIER_MAX_CHARS);
1110
+ const toolName = sanitizedBoundedString(input.toolName, IDENTIFIER_MAX_CHARS);
1111
+ if (!dialogId || !callId || !toolName)
1112
+ return null;
1113
+ const errorClass = resolveErrorClass(input.error);
1114
+ const message = sanitizeToolErrorText(resolveErrorMessage(input.error, errorClass)) || errorClass;
1115
+ const stack = resolveStack(input.error);
1116
+ return {
1117
+ dialogId,
1118
+ callId,
1119
+ toolName,
1120
+ errorClass,
1121
+ message,
1122
+ ...stack ? { stack } : {}
1123
+ };
1298
1124
  }
1299
-
1300
- // packages/core/redactUrlUserinfo.ts
1301
- var REDACTED_USERINFO = "[REDACTED]@";
1302
- var REDACTED = "[REDACTED]";
1303
- var SPECIAL_SCHEMES = /* @__PURE__ */ new Set(["http", "https", "ws", "wss", "ftp"]);
1304
- var MAX_SCHEME_CHARS = 8;
1305
- var isTabOrNewline = (char) => char === " " || char === "\n" || char === "\r";
1306
- var isAsciiAlpha = (char) => char >= "a" && char <= "z" || char >= "A" && char <= "Z";
1307
- var isSchemeChar = (char) => isAsciiAlpha(char) || char >= "0" && char <= "9" || char === "+" || char === "-" || char === ".";
1308
- var isPrecededBySchemeWord = (text, idx) => {
1309
- let index = idx - 1;
1310
- if (index < 0 || !isSchemeChar(text[index])) return false;
1311
- while (index > 0 && isSchemeChar(text[index - 1])) index -= 1;
1312
- return isAsciiAlpha(text[index]);
1125
+ var pickAllowedFields = (payload) => {
1126
+ const out = {};
1127
+ for (const field of TOOL_ERROR_REPORT_ALLOWED_FIELDS) {
1128
+ const value = payload[field];
1129
+ if (typeof value === "string" && value)
1130
+ out[field] = value;
1131
+ }
1132
+ return out;
1313
1133
  };
1314
- var matchSpecialSchemeBeforeColon = (text, colonIdx) => {
1315
- let chars = "";
1316
- let index = colonIdx - 1;
1317
- while (index >= 0 && chars.length < 5) {
1318
- const char = text[index];
1319
- if (isTabOrNewline(char)) {
1320
- index -= 1;
1321
- continue;
1322
- }
1323
- if (!isAsciiAlpha(char)) break;
1324
- chars = char.toLowerCase() + chars;
1325
- if (SPECIAL_SCHEMES.has(chars) && !isPrecededBySchemeWord(text, index)) return true;
1326
- index -= 1;
1134
+ var truncateToUtf8Bytes = (value, maxBytes) => {
1135
+ if (maxBytes <= 0)
1136
+ return "";
1137
+ const encoder = new TextEncoder;
1138
+ if (encoder.encode(value).length <= maxBytes)
1139
+ return value;
1140
+ let used = 0;
1141
+ let out = "";
1142
+ for (const char of value) {
1143
+ const size = encoder.encode(char).length;
1144
+ if (used + size > maxBytes)
1145
+ break;
1146
+ used += size;
1147
+ out += char;
1327
1148
  }
1328
- return false;
1149
+ return out;
1329
1150
  };
1330
- var isFullSpecialSchemeBeforeColon = (text, colonIdx) => {
1331
- let index = colonIdx - 1;
1332
- let chars = "";
1333
- while (index >= 0 && chars.length <= MAX_SCHEME_CHARS) {
1334
- const char = text[index];
1335
- if (isTabOrNewline(char)) {
1336
- index -= 1;
1337
- continue;
1151
+ var utf8ByteLength = (value) => new TextEncoder().encode(value).length;
1152
+ var buildBoundedBody = (fields) => {
1153
+ const withoutStack = { ...fields };
1154
+ delete withoutStack.stack;
1155
+ const attempts = fields.stack ? [fields, withoutStack] : [withoutStack];
1156
+ for (const attempt of attempts) {
1157
+ const serialized = JSON.stringify(attempt);
1158
+ if (utf8ByteLength(serialized) <= TOOL_ERROR_REPORT_MAX_BODY_BYTES)
1159
+ return serialized;
1160
+ }
1161
+ const base = { ...withoutStack, message: "" };
1162
+ const budgetForMessage = TOOL_ERROR_REPORT_MAX_BODY_BYTES - utf8ByteLength(JSON.stringify(base));
1163
+ if (budgetForMessage > 0) {
1164
+ const shrunk = truncateToUtf8Bytes(withoutStack.message ?? "", budgetForMessage);
1165
+ if (shrunk) {
1166
+ const serialized = JSON.stringify({ ...withoutStack, message: shrunk });
1167
+ if (utf8ByteLength(serialized) <= TOOL_ERROR_REPORT_MAX_BODY_BYTES)
1168
+ return serialized;
1338
1169
  }
1339
- if (!isSchemeChar(char)) break;
1340
- chars = char.toLowerCase() + chars;
1341
- index -= 1;
1342
1170
  }
1343
- if (chars.length > MAX_SCHEME_CHARS) return false;
1344
- if (!isAsciiAlpha(chars[0] ?? "")) return false;
1345
- return SPECIAL_SCHEMES.has(chars);
1171
+ const fallback = JSON.stringify({
1172
+ ...withoutStack,
1173
+ message: withoutStack.errorClass ?? ""
1174
+ });
1175
+ return utf8ByteLength(fallback) <= TOOL_ERROR_REPORT_MAX_BODY_BYTES ? fallback : null;
1346
1176
  };
1347
- var hasValidSchemeBeforeColon = (text, colonIdx) => {
1348
- let index = colonIdx - 1;
1349
- let sawAlpha = false;
1350
- while (index >= 0) {
1351
- const char = text[index];
1352
- if (isTabOrNewline(char)) {
1353
- index -= 1;
1354
- continue;
1177
+ function resolveSafeReportOrigin(value) {
1178
+ if (typeof value !== "string" || !value.trim())
1179
+ return null;
1180
+ let url;
1181
+ try {
1182
+ url = new URL(value.trim());
1183
+ } catch {
1184
+ return null;
1185
+ }
1186
+ if (url.protocol !== "https:" && url.protocol !== "http:")
1187
+ return null;
1188
+ if (url.username || url.password)
1189
+ return null;
1190
+ if (url.search || url.hash)
1191
+ return null;
1192
+ if (url.pathname !== "/" && url.pathname !== "")
1193
+ return null;
1194
+ if (url.protocol === "http:" && !isLoopbackHostname(url.hostname))
1195
+ return null;
1196
+ return url.origin;
1197
+ }
1198
+ var collectConfiguredOrigins = (runtime) => {
1199
+ const origins = new Set;
1200
+ const push = (value) => {
1201
+ const normalized = normalizeKnownServerOrigin(value);
1202
+ if (normalized)
1203
+ origins.add(normalized);
1204
+ };
1205
+ push(runtime.currentServer);
1206
+ const syncServers = runtime.syncServers;
1207
+ if (Array.isArray(syncServers))
1208
+ syncServers.forEach(push);
1209
+ const registry = runtime.userAuthorityRegistry;
1210
+ if (registry && typeof registry === "object") {
1211
+ for (const entry of Object.values(registry)) {
1212
+ if (typeof entry === "string") {
1213
+ push(entry);
1214
+ continue;
1215
+ }
1216
+ if (entry && typeof entry === "object") {
1217
+ const record = entry;
1218
+ push(record.authorityServer);
1219
+ push(record.homeServer);
1220
+ push(record.primaryServer);
1221
+ }
1355
1222
  }
1356
- if (!isSchemeChar(char)) break;
1357
- if (isAsciiAlpha(char)) sawAlpha = true;
1358
- index -= 1;
1359
1223
  }
1360
- return sawAlpha;
1224
+ return origins;
1361
1225
  };
1362
- var matchDoubleSlashAfterColon = (text, colonIdx) => {
1363
- let index = colonIdx + 1;
1364
- let slashes = 0;
1365
- while (index < text.length && slashes < 2) {
1366
- const char = text[index];
1367
- if (isTabOrNewline(char)) {
1368
- index += 1;
1369
- continue;
1370
- }
1371
- if (char === "/") {
1372
- slashes += 1;
1373
- index += 1;
1374
- continue;
1375
- }
1376
- return -1;
1226
+ function resolveToolErrorReportTarget(state, runtime = getRuntimeServerSnapshot(state)) {
1227
+ if (!state || typeof state !== "object")
1228
+ return null;
1229
+ const snapshot = getSessionSnapshotForState(state);
1230
+ const activeAccountId = typeof snapshot?.activeAccountId === "string" ? snapshot.activeAccountId.trim() : "";
1231
+ const rawToken = typeof snapshot?.activeToken === "string" ? snapshot.activeToken.trim() : "";
1232
+ if (!activeAccountId || !rawToken)
1233
+ return null;
1234
+ const configuredOrigins = collectConfiguredOrigins(runtime);
1235
+ if (isGoogleAuthoritySession(rawToken)) {
1236
+ const sameOrigin = resolveSafeReportOrigin(googleSessionServer(rawToken));
1237
+ if (!sameOrigin)
1238
+ return null;
1239
+ return { baseUrl: sameOrigin, token: rawToken };
1377
1240
  }
1378
- return slashes === 2 ? index : -1;
1379
- };
1380
- var skipSpecialAuthorityPrefix = (text, colonIdx) => {
1381
- let index = colonIdx + 1;
1382
- while (index < text.length) {
1383
- const char = text[index];
1384
- if (char === "/" || char === "\\" || isTabOrNewline(char)) index += 1;
1385
- else break;
1241
+ const authorityServer = resolveUserAuthorityServer({
1242
+ ownerUserId: activeAccountId,
1243
+ registry: runtime.userAuthorityRegistry ?? null
1244
+ });
1245
+ const authorityOrigin = resolveSafeReportOrigin(authorityServer);
1246
+ const currentOrigin = resolveSafeReportOrigin(resolveDesktopSafeServer(runtime.currentServer));
1247
+ const authorityKnown = typeof authorityServer === "string" && authorityServer.trim().length > 0;
1248
+ const candidate = authorityKnown ? authorityOrigin : currentOrigin;
1249
+ if (!candidate)
1250
+ return null;
1251
+ if (!configuredOrigins.has(candidate))
1252
+ return null;
1253
+ return { baseUrl: candidate, token: rawToken };
1254
+ }
1255
+ var dedupeKeyOf = (payload) => `${payload.dialogId}|${payload.callId}|${payload.toolName}|${payload.errorClass}`;
1256
+ var rememberDedupeKey = (key) => {
1257
+ dedupeKeys.set(key, true);
1258
+ while (dedupeKeys.size > MAX_DEDUPE_ENTRIES) {
1259
+ const oldest = dedupeKeys.keys().next();
1260
+ if (oldest.done)
1261
+ break;
1262
+ dedupeKeys.delete(oldest.value);
1386
1263
  }
1387
- return index;
1388
1264
  };
1389
- var authorityCandidates = (text, colonIdx) => {
1390
- const fullSchemeIsSpecial = isFullSpecialSchemeBeforeColon(text, colonIdx);
1391
- if (!fullSchemeIsSpecial && !hasValidSchemeBeforeColon(text, colonIdx)) return [];
1392
- const candidates = [];
1393
- const afterSlashes = matchDoubleSlashAfterColon(text, colonIdx);
1394
- if (!fullSchemeIsSpecial && afterSlashes !== -1) {
1395
- candidates.push({ start: afterSlashes, isSpecial: false });
1265
+ async function reportToolError(args) {
1266
+ const key = dedupeKeyOf(args.payload);
1267
+ if (dedupeKeys.has(key))
1268
+ return false;
1269
+ if (inflightReports >= MAX_INFLIGHT_REPORTS)
1270
+ return false;
1271
+ const baseUrl = resolveSafeReportOrigin(args.baseUrl);
1272
+ if (!baseUrl)
1273
+ return false;
1274
+ const requestUrl = `${baseUrl}${TOOL_ERROR_REPORT_PATH}`;
1275
+ let requestToken;
1276
+ try {
1277
+ requestToken = googleSessionRequestToken(args.token, requestUrl);
1278
+ } catch {
1279
+ return false;
1396
1280
  }
1397
- if (fullSchemeIsSpecial || matchSpecialSchemeBeforeColon(text, colonIdx)) {
1398
- candidates.push({ start: skipSpecialAuthorityPrefix(text, colonIdx), isSpecial: true });
1281
+ if (!requestToken)
1282
+ return false;
1283
+ if (typeof AbortController !== "function")
1284
+ return false;
1285
+ const timeoutMs = typeof args.timeoutMs === "number" && args.timeoutMs > 0 ? args.timeoutMs : REPORT_TIMEOUT_MS;
1286
+ rememberDedupeKey(key);
1287
+ inflightReports += 1;
1288
+ const controller = new AbortController;
1289
+ const timer = setTimeout(() => {
1290
+ try {
1291
+ controller.abort();
1292
+ } catch {}
1293
+ }, timeoutMs);
1294
+ try {
1295
+ const fetchImpl = args.fetchImpl ?? (typeof fetch === "function" ? fetch : undefined);
1296
+ if (!fetchImpl)
1297
+ return false;
1298
+ const body = buildBoundedBody(pickAllowedFields(args.payload));
1299
+ if (!body)
1300
+ return false;
1301
+ const response = await fetchImpl(requestUrl, {
1302
+ method: "POST",
1303
+ headers: {
1304
+ "Content-Type": "application/json",
1305
+ Authorization: `Bearer ${requestToken}`
1306
+ },
1307
+ body,
1308
+ redirect: "error",
1309
+ credentials: "omit",
1310
+ signal: controller.signal
1311
+ });
1312
+ return response?.ok === true;
1313
+ } catch {
1314
+ return false;
1315
+ } finally {
1316
+ clearTimeout(timer);
1317
+ inflightReports -= 1;
1399
1318
  }
1400
- return candidates;
1319
+ }
1320
+ var isBrowserRuntime = () => typeof window !== "undefined" && typeof document !== "undefined";
1321
+ function reportToolExecutionErrorInBackground(args) {
1322
+ try {
1323
+ if (!isBrowserRuntime())
1324
+ return;
1325
+ const payload = buildToolErrorReportPayload(args);
1326
+ if (!payload)
1327
+ return;
1328
+ const target = resolveToolErrorReportTarget(args.thunkApi?.getState?.(), args.thunkApi?.runtimeServers);
1329
+ if (!target)
1330
+ return;
1331
+ reportToolError({ ...target, payload }).catch(() => {});
1332
+ } catch {}
1333
+ }
1334
+
1335
+ // packages/ai/tools/stripModelConfirmationFlags.ts
1336
+ var CONFIRMATION_INPUT_KEYS = {
1337
+ knowledge_capture_requires_confirmation: "__confirmedKnowledgeCapture",
1338
+ self_evolution_requires_confirmation: "__confirmedSelfEvolution",
1339
+ agent_update_requires_confirmation: "__confirmedSelfEvolution",
1340
+ media_job_start_requires_confirmation: "__confirmedMediaJobStart"
1401
1341
  };
1402
- var findNextStop = (text, from, includeBackslash) => {
1403
- for (let index = from; index < text.length; index += 1) {
1404
- const char = text[index];
1405
- if (char === "/" || char === "?" || char === "#" || includeBackslash && char === "\\") {
1406
- return index;
1407
- }
1342
+ function stripModelConfirmationFlags(value) {
1343
+ if (!value || typeof value !== "object" || Array.isArray(value))
1344
+ return value;
1345
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !key.startsWith("__confirmed")));
1346
+ }
1347
+ var MODEL_DIALOG_BINDING_STRIPPED_TOOLS = new Set([
1348
+ "mediaJobTool",
1349
+ "transcribe",
1350
+ "translate",
1351
+ "exportDocument",
1352
+ "readArtifact"
1353
+ ]);
1354
+ var TRUSTED_ONLY_MODEL_INPUT_KEYS = new Set(["confirmationToken", "expectedExecutionRevision"]);
1355
+ function stripModelToolArgs(canonicalToolName, value) {
1356
+ const base = stripModelConfirmationFlags(value);
1357
+ if (!base || typeof base !== "object" || Array.isArray(base))
1358
+ return base;
1359
+ const withoutTrustedOnlyKeys = Object.fromEntries(Object.entries(base).filter(([key]) => !TRUSTED_ONLY_MODEL_INPUT_KEYS.has(key)));
1360
+ if (!MODEL_DIALOG_BINDING_STRIPPED_TOOLS.has(canonicalToolName)) {
1361
+ return withoutTrustedOnlyKeys;
1408
1362
  }
1409
- return text.length;
1410
- };
1411
- var hasNonIgnoredChar = (text, start, end) => {
1412
- for (let index = start; index < end; index += 1) {
1413
- if (!isTabOrNewline(text[index])) return true;
1363
+ if (!withoutTrustedOnlyKeys || typeof withoutTrustedOnlyKeys !== "object" || Array.isArray(withoutTrustedOnlyKeys)) {
1364
+ return withoutTrustedOnlyKeys;
1414
1365
  }
1415
- return false;
1366
+ return Object.fromEntries(Object.entries(withoutTrustedOnlyKeys).filter(([key]) => key !== "dialogId" && key !== "autoApproveCredits"));
1367
+ }
1368
+
1369
+ // packages/ai/chat/buildProxyPayload.ts
1370
+ var buildProxyPayload = (bodyData, api, agentConfig, dialogId) => {
1371
+ const apiSource = agentConfig.apiSource === "custom" || agentConfig.apiSource === "cli" ? agentConfig.apiSource : undefined;
1372
+ const provider = bodyData.provider || agentConfig.provider || (apiSource === "custom" ? "custom" : undefined);
1373
+ const apiKey = resolveOutboundProxyApiKey(agentConfig);
1374
+ return {
1375
+ ...bodyData,
1376
+ url: api,
1377
+ provider,
1378
+ agentKey: agentConfig.dbKey,
1379
+ ...asOptionalTrimmedString(dialogId) ? { dialogId: asOptionalTrimmedString(dialogId) } : {},
1380
+ ...apiSource ? { apiSource } : {},
1381
+ ...agentConfig.apiKeyHeader ? { apiKeyHeader: agentConfig.apiKeyHeader } : {},
1382
+ KEY: apiKey
1383
+ };
1416
1384
  };
1417
- function redactUrlUserinfo(text) {
1418
- const lastAtInText = text.lastIndexOf("@");
1419
- if (lastAtInText === -1 || !text.includes(":")) return text;
1420
- let output = "";
1421
- let cursor = 0;
1422
- let scanFrom = 0;
1423
- let nextAt = -1;
1424
- let nextSpecialStop = -1;
1425
- let nextNonSpecialStop = -1;
1426
- while (scanFrom < lastAtInText) {
1427
- const colonIdx = text.indexOf(":", scanFrom);
1428
- if (colonIdx === -1 || colonIdx >= lastAtInText) break;
1429
- scanFrom = colonIdx + 1;
1430
- const candidates = authorityCandidates(text, colonIdx);
1431
- if (candidates.length === 0) continue;
1432
- let authorityStart = -1;
1433
- let authorityEnd = -1;
1434
- for (const candidate of candidates) {
1435
- if (nextAt < candidate.start) {
1436
- nextAt = text.indexOf("@", candidate.start);
1437
- if (nextAt === -1) break;
1385
+
1386
+ // packages/ai/chat/resolveDirectRequestApiKey.ts
1387
+ var DIRECT_API_KEY_UNAVAILABLE_MESSAGE = "当前步骤需要提供 API 凭据,请重新提供密钥,或确认本机凭据可用。";
1388
+
1389
+ class DirectApiKeyResolutionError extends Error {
1390
+ kind = "credential_missing";
1391
+ credentialRef;
1392
+ constructor(credentialRefOrOptions, message = DIRECT_API_KEY_UNAVAILABLE_MESSAGE) {
1393
+ let resolvedRef;
1394
+ let resolvedMessage = DIRECT_API_KEY_UNAVAILABLE_MESSAGE;
1395
+ if (typeof credentialRefOrOptions === "string") {
1396
+ resolvedRef = credentialRefOrOptions;
1397
+ if (message !== DIRECT_API_KEY_UNAVAILABLE_MESSAGE) {
1398
+ resolvedMessage = message;
1438
1399
  }
1439
- const end = candidate.isSpecial ? nextSpecialStop < candidate.start ? nextSpecialStop = findNextStop(text, candidate.start, true) : nextSpecialStop : nextNonSpecialStop < candidate.start ? nextNonSpecialStop = findNextStop(text, candidate.start, false) : nextNonSpecialStop;
1440
- if (nextAt >= end) continue;
1441
- authorityStart = candidate.start;
1442
- authorityEnd = end;
1443
- break;
1444
- }
1445
- if (authorityStart === -1) {
1446
- if (nextAt === -1) break;
1447
- continue;
1448
- }
1449
- const lastAt = text.lastIndexOf("@", authorityEnd - 1);
1450
- if (lastAt <= authorityStart) continue;
1451
- if (!hasNonIgnoredChar(text, authorityStart, lastAt)) continue;
1452
- if (text.slice(authorityStart, lastAt) === "[REDACTED]") {
1453
- scanFrom = lastAt + 1;
1454
- continue;
1400
+ } else if (credentialRefOrOptions && typeof credentialRefOrOptions === "object") {
1401
+ resolvedRef = credentialRefOrOptions.credentialRef;
1402
+ resolvedMessage = credentialRefOrOptions.message ?? DIRECT_API_KEY_UNAVAILABLE_MESSAGE;
1455
1403
  }
1456
- output += `${text.slice(cursor, authorityStart)}${REDACTED_USERINFO}`;
1457
- cursor = lastAt + 1;
1458
- scanFrom = cursor;
1404
+ super(resolvedMessage);
1405
+ this.name = "DirectApiKeyResolutionError";
1406
+ this.credentialRef = resolvedRef;
1459
1407
  }
1460
- return cursor === 0 ? text : output + text.slice(cursor);
1461
1408
  }
1462
- function redactUrlQueryAndFragment(text) {
1463
- if (!text.includes(":") || !text.includes("?") && !text.includes("#")) return text;
1464
- let output = "";
1465
- let cursor = 0;
1466
- let scanFrom = 0;
1467
- while (scanFrom < text.length) {
1468
- const colonIdx = text.indexOf(":", scanFrom);
1469
- if (colonIdx === -1) break;
1470
- scanFrom = colonIdx + 1;
1471
- let urlStart = -1;
1472
- for (const candidate of authorityCandidates(text, colonIdx)) {
1473
- if (urlStart === -1 || candidate.start < urlStart) urlStart = candidate.start;
1474
- }
1475
- if (urlStart === -1 && hasValidSchemeBeforeColon(text, colonIdx)) urlStart = colonIdx + 1;
1476
- if (urlStart === -1) continue;
1477
- if (urlStart < cursor) continue;
1478
- let marker = -1;
1479
- for (let index = urlStart; index < text.length; index += 1) {
1480
- const char = text[index];
1481
- if (char === "?" || char === "#") {
1482
- marker = index;
1483
- break;
1484
- }
1409
+ var createDirectCredentialBroker = createFileCredentialBroker;
1410
+ function readNonEmpty(value) {
1411
+ return asTrimmedString(value);
1412
+ }
1413
+ async function resolveDirectRequestApiKey(agentConfig, options) {
1414
+ const rawKey = readNonEmpty(agentConfig.apiKey);
1415
+ if (rawKey)
1416
+ return rawKey;
1417
+ const credentialRef = readNonEmpty(agentConfig.credentialRef);
1418
+ if (!credentialRef)
1419
+ return;
1420
+ const factory = options?.brokerFactory ?? createDirectCredentialBroker;
1421
+ const broker = factory();
1422
+ const local = await safeBrokerGet(broker, credentialRef);
1423
+ if (local)
1424
+ return local;
1425
+ if (isAgentCredentialShared(agentConfig) && credentialRef.startsWith("provider-key:") && options?.providerSecretFetcher) {
1426
+ const providerSecret = await options.providerSecretFetcher(credentialRef);
1427
+ if (providerSecret)
1428
+ return providerSecret;
1429
+ }
1430
+ if (isAgentCredentialShared(agentConfig) && options?.syncFetcher) {
1431
+ const synced = await options.syncFetcher(credentialRef);
1432
+ const trimmed = asTrimmedString(synced);
1433
+ if (trimmed) {
1434
+ try {
1435
+ await broker.put(credentialRef, trimmed);
1436
+ } catch {}
1437
+ return trimmed;
1485
1438
  }
1486
- if (marker === -1) break;
1487
- output += `${text.slice(cursor, marker)}${text[marker]}${REDACTED}`;
1488
- cursor = text.length;
1489
- scanFrom = text.length;
1490
1439
  }
1491
- return cursor === 0 ? text : output + text.slice(cursor);
1492
- }
1493
-
1494
- // packages/ai/agent/toolErrorReport.ts
1495
- var TOOL_ERROR_REPORT_PATH = "/api/diagnostics/tool-errors";
1496
- var REPORT_TIMEOUT_MS = 3e3;
1497
- var MAX_INFLIGHT_REPORTS = 1;
1498
- var MAX_DEDUPE_ENTRIES = 100;
1499
- var MESSAGE_MAX_CHARS = 1e3;
1500
- var STACK_MAX_CHARS = 4e3;
1501
- var ERROR_CLASS_MAX_CHARS = 120;
1502
- var IDENTIFIER_MAX_CHARS = 200;
1503
- var TOOL_ERROR_REPORT_MAX_BODY_BYTES = 16 * 1024;
1504
- var CONTROL_CHARS_PATTERN = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;
1505
- var REDACTED2 = "[REDACTED]";
1506
- var TOOL_ERROR_REPORT_ALLOWED_FIELDS = [
1507
- "dialogId",
1508
- "callId",
1509
- "toolName",
1510
- "errorClass",
1511
- "message",
1512
- "stack",
1513
- "clientVersion"
1514
- ];
1515
- var dedupeKeys = /* @__PURE__ */ new Map();
1516
- var inflightReports = 0;
1517
- var sanitizedBoundedString = (value, maxChars) => {
1518
- if (typeof value !== "string") return void 0;
1519
- const cleaned = sanitizeToolErrorText(value).trim();
1520
- if (!cleaned) return void 0;
1521
- return cleaned.length > maxChars ? cleaned.slice(0, maxChars) : cleaned;
1522
- };
1523
- function sanitizeToolErrorText(input) {
1524
- if (typeof input !== "string" || !input) return "";
1525
- let text = input;
1526
- text = text.replace(CONTROL_CHARS_PATTERN, "");
1527
- text = redactUrlUserinfo(text);
1528
- text = redactUrlQueryAndFragment(text);
1529
- text = text.replace(
1530
- /([?&](?:access[_-]?token|refresh[_-]?token|api[_-]?key|apikey|token|secret|password|sig|signature|key)=)[^&\s"'<>[\]]+/gi,
1531
- (_match, prefix) => `${prefix}${REDACTED2}`
1532
- );
1533
- text = text.replace(
1534
- /\b(bearer)\s+[A-Za-z0-9._~+/=-]{4,}/gi,
1535
- (_match, scheme) => `${scheme} ${REDACTED2}`
1536
- );
1537
- text = text.replace(
1538
- /\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\b/g,
1539
- REDACTED2
1540
- );
1541
- text = text.replace(
1542
- /((?:api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|token|password|secret|authorization)["']?\s*[:=]\s*)("?)([^\s"',;}\][]+)/gi,
1543
- (_match, prefix, quote) => `${prefix}${quote}${REDACTED2}`
1544
- );
1545
- text = text.replace(/\bsk-[A-Za-z0-9_-]{12,}/g, REDACTED2);
1546
- return text;
1440
+ throw new DirectApiKeyResolutionError(credentialRef);
1547
1441
  }
1548
- var resolveErrorClass = (error) => {
1549
- if (error && typeof error === "object") {
1550
- const record = error;
1551
- const name = sanitizedBoundedString(record.name, ERROR_CLASS_MAX_CHARS) ?? sanitizedBoundedString(record.constructor?.name, ERROR_CLASS_MAX_CHARS);
1552
- if (name) return name;
1553
- return "Error";
1442
+ async function safeBrokerGet(broker, ref) {
1443
+ try {
1444
+ return asTrimmedString(await broker.get(ref)) || null;
1445
+ } catch {
1446
+ return null;
1554
1447
  }
1555
- return "Error";
1556
- };
1557
- var resolveErrorMessage = (error, errorClass) => {
1558
- const raw = error && typeof error === "object" ? error.message : error;
1559
- const text = typeof raw === "string" ? raw : raw === void 0 || raw === null ? "" : String(raw);
1560
- const sanitized = sanitizeToolErrorText(text).trim();
1561
- const bounded = sanitized.length > MESSAGE_MAX_CHARS ? sanitized.slice(0, MESSAGE_MAX_CHARS) : sanitized;
1562
- return bounded || errorClass;
1563
- };
1564
- var resolveStack = (error) => {
1565
- if (!error || typeof error !== "object") return void 0;
1566
- const stack = error.stack;
1567
- if (typeof stack !== "string") return void 0;
1568
- const sanitized = sanitizeToolErrorText(stack).trim();
1569
- if (!sanitized) return void 0;
1570
- return sanitized.length > STACK_MAX_CHARS ? sanitized.slice(0, STACK_MAX_CHARS) : sanitized;
1571
- };
1572
- function buildToolErrorReportPayload(input) {
1573
- const dialogId = sanitizedBoundedString(input.dialogId, IDENTIFIER_MAX_CHARS);
1574
- const callId = sanitizedBoundedString(input.callId, IDENTIFIER_MAX_CHARS);
1575
- const toolName = sanitizedBoundedString(input.toolName, IDENTIFIER_MAX_CHARS);
1576
- if (!dialogId || !callId || !toolName) return null;
1577
- const errorClass = resolveErrorClass(input.error);
1578
- const message = sanitizeToolErrorText(resolveErrorMessage(input.error, errorClass)) || errorClass;
1579
- const stack = resolveStack(input.error);
1580
- return {
1581
- dialogId,
1582
- callId,
1583
- toolName,
1584
- errorClass,
1585
- message,
1586
- ...stack ? { stack } : {}
1587
- };
1588
1448
  }
1589
- var pickAllowedFields = (payload) => {
1590
- const out = {};
1591
- for (const field of TOOL_ERROR_REPORT_ALLOWED_FIELDS) {
1592
- const value = payload[field];
1593
- if (typeof value === "string" && value) out[field] = value;
1449
+
1450
+ // packages/ai/chat/fetchUtils.ts
1451
+ var fetchDirectly = async (params) => {
1452
+ const { api, agentConfig, bodyData, signal, currentServer, token, dialogId } = params;
1453
+ try {
1454
+ const apiKey = await resolveDirectRequestApiKey(agentConfig, {
1455
+ syncFetcher: currentServer && token ? (ref) => fetchServerSyncedCredential({ currentServer, authToken: token }, ref) : undefined,
1456
+ providerSecretFetcher: isAgentCredentialShared(agentConfig) && currentServer && token ? async (ref) => {
1457
+ const presetId = ref.startsWith("provider-key:") ? ref.slice("provider-key:".length) : ref;
1458
+ const local = getLocalProviderSecret(presetId);
1459
+ if (local)
1460
+ return local;
1461
+ try {
1462
+ const response = await fetch(`${currentServer}/api/user-secrets/get?presetId=${encodeURIComponent(presetId)}`, { headers: { Authorization: `Bearer ${token}` } });
1463
+ if (!response.ok)
1464
+ return null;
1465
+ return (await response.json()).value ?? null;
1466
+ } catch {
1467
+ return null;
1468
+ }
1469
+ } : undefined
1470
+ });
1471
+ const authHeaders = buildProviderAuthHeaders({
1472
+ endpoint: api,
1473
+ apiKey: apiKey ?? "",
1474
+ apiKeyHeader: agentConfig.apiKeyHeader,
1475
+ sessionId: dialogId || agentConfig.dbKey || agentConfig.key
1476
+ });
1477
+ return await fetch(api, {
1478
+ method: "POST",
1479
+ headers: {
1480
+ "Content-Type": "application/json",
1481
+ ...authHeaders,
1482
+ ...api.includes("openrouter.ai") ? {
1483
+ "HTTP-Referer": "https://nolo.chat",
1484
+ "X-Title": "nolo"
1485
+ } : {}
1486
+ },
1487
+ body: JSON.stringify(bodyData),
1488
+ signal
1489
+ });
1490
+ } catch (error) {
1491
+ if (!(error instanceof DirectApiKeyResolutionError) && error?.kind !== "credential_missing") {
1492
+ console.error("[fetchDirectly] 网络请求失败:", error);
1493
+ }
1494
+ throw error;
1594
1495
  }
1595
- return out;
1596
1496
  };
1597
- var truncateToUtf8Bytes = (value, maxBytes) => {
1598
- if (maxBytes <= 0) return "";
1599
- const encoder = new TextEncoder();
1600
- if (encoder.encode(value).length <= maxBytes) return value;
1601
- let used = 0;
1602
- let out = "";
1603
- for (const char of value) {
1604
- const size = encoder.encode(char).length;
1605
- if (used + size > maxBytes) break;
1606
- used += size;
1607
- out += char;
1497
+ var fetchWithServerProxy = async ({
1498
+ currentServer,
1499
+ api,
1500
+ bodyData,
1501
+ agentConfig,
1502
+ token,
1503
+ signal,
1504
+ dialogId,
1505
+ onRetry
1506
+ }) => {
1507
+ try {
1508
+ const payload = buildProxyPayload(bodyData, api, agentConfig, dialogId);
1509
+ return await performServerProxyFetchWithRetry({
1510
+ signal,
1511
+ onRetry,
1512
+ execute: () => fetch(`${currentServer}${API_ENDPOINTS.CHAT}`, {
1513
+ method: "POST",
1514
+ headers: {
1515
+ "Content-Type": "application/json",
1516
+ Authorization: `Bearer ${token}`
1517
+ },
1518
+ body: JSON.stringify(payload),
1519
+ signal
1520
+ })
1521
+ });
1522
+ } catch (error) {
1523
+ console.error("[fetchWithServerProxy] 网络请求失败:", error);
1524
+ throw error;
1608
1525
  }
1609
- return out;
1610
1526
  };
1611
- var utf8ByteLength = (value) => new TextEncoder().encode(value).length;
1612
- var buildBoundedBody = (fields) => {
1613
- const withoutStack = { ...fields };
1614
- delete withoutStack.stack;
1615
- const attempts = fields.stack ? [fields, withoutStack] : [withoutStack];
1616
- for (const attempt of attempts) {
1617
- const serialized = JSON.stringify(attempt);
1618
- if (utf8ByteLength(serialized) <= TOOL_ERROR_REPORT_MAX_BODY_BYTES) return serialized;
1527
+ var formatFriendlyNetworkErrorMessage = (error) => {
1528
+ if (typeof window !== "undefined" && typeof navigator !== "undefined" && navigator.onLine === false) {
1529
+ return "网络连接已断开,请检查网络连接后重试";
1619
1530
  }
1620
- const base = { ...withoutStack, message: "" };
1621
- const budgetForMessage = TOOL_ERROR_REPORT_MAX_BODY_BYTES - utf8ByteLength(JSON.stringify(base));
1622
- if (budgetForMessage > 0) {
1623
- const shrunk = truncateToUtf8Bytes(withoutStack.message ?? "", budgetForMessage);
1624
- if (shrunk) {
1625
- const serialized = JSON.stringify({ ...withoutStack, message: shrunk });
1626
- if (utf8ByteLength(serialized) <= TOOL_ERROR_REPORT_MAX_BODY_BYTES) return serialized;
1531
+ const rawMessage = toErrorMessage(error);
1532
+ if (/failed to fetch|networkerror|network error|econnrefused|econnreset|socket hang up/i.test(rawMessage)) {
1533
+ return "网络请求失败,请检查网络连接或代理/VPN设置";
1534
+ }
1535
+ return rawMessage;
1536
+ };
1537
+ var performFetchRequest = async (params) => {
1538
+ let direct = false;
1539
+ try {
1540
+ const { agentConfig, bodyData } = params;
1541
+ const credentialRef = "credentialRef" in agentConfig && typeof agentConfig.credentialRef === "string" ? agentConfig.credentialRef : undefined;
1542
+ const plan = resolveAgentCallPlan({
1543
+ key: "",
1544
+ provider: bodyData.provider || agentConfig.provider,
1545
+ model: agentConfig.model,
1546
+ apiSource: agentConfig.apiSource,
1547
+ cliProvider: agentConfig.cliProvider ?? undefined,
1548
+ customProviderUrl: agentConfig.customProviderUrl,
1549
+ apiKey: agentConfig.apiKey ?? undefined,
1550
+ apiKeyRef: agentConfig.apiKeyRef,
1551
+ credentialRef,
1552
+ credentialSynced: agentConfig.credentialSynced,
1553
+ useServerProxy: agentConfig.useServerProxy
1554
+ }, undefined, { canResolveLocalCredential: true });
1555
+ direct = plan.transport === "direct";
1556
+ return direct ? await fetchDirectly(params) : await fetchWithServerProxy(params);
1557
+ } catch (error) {
1558
+ if (error instanceof DirectApiKeyResolutionError || error?.kind === "credential_missing") {
1559
+ throw error;
1627
1560
  }
1561
+ console.error("[performFetchRequest] 请求过程中发生错误:", error);
1562
+ if (params.preserveStructuredError || params.signal?.aborted || error?.name === "AbortError")
1563
+ throw error;
1564
+ const rawMessage = toErrorMessage(error);
1565
+ const friendlyMsg = direct && /failed to fetch|networkerror|network error|load failed/i.test(rawMessage) && !(typeof navigator !== "undefined" && navigator.onLine === false) ? "网络请求失败:浏览器直连服务商时,可能被服务商的跨域限制(CORS)拦截。" : formatFriendlyNetworkErrorMessage(error);
1566
+ throw new Error(friendlyMsg.startsWith("网络请求失败") ? friendlyMsg : `网络请求失败: ${friendlyMsg}`);
1628
1567
  }
1629
- const fallback = JSON.stringify({
1630
- ...withoutStack,
1631
- message: withoutStack.errorClass ?? ""
1632
- });
1633
- return utf8ByteLength(fallback) <= TOOL_ERROR_REPORT_MAX_BODY_BYTES ? fallback : null;
1634
1568
  };
1635
- function resolveSafeReportOrigin(value) {
1636
- if (typeof value !== "string" || !value.trim()) return null;
1637
- let url;
1569
+
1570
+ // packages/ai/chat/toolCallArgumentGuard.ts
1571
+ var INVALID_TOOL_ARGS_REPLACEMENT = '{"_invalid":true,"_reason":"arguments truncated or malformed"}';
1572
+ var INVALID_TOOL_ARGS_OUTBOUND_REPLACEMENT = '{"_invalid":true}';
1573
+ var INVALID_TOOL_RESULT_HINT = "工具参数 JSON 被截断(大概率超出输出长度)。不要把完整源码塞进一次工具调用:先用 appFileWrite 分文件多次写入,再调用不带内联大参数的 appPreflight/appDeploy。";
1574
+ var ORPHAN_TOOL_RESULT_PLACEHOLDER = '{"error":"tool call was interrupted"}';
1575
+ function parseToolCallArguments(args) {
1576
+ if (isRecord(args)) {
1577
+ return { valid: true, parsed: args };
1578
+ }
1579
+ if (typeof args !== "string")
1580
+ return { valid: false };
1581
+ const trimmed = args.trim();
1582
+ if (!trimmed)
1583
+ return { valid: false };
1638
1584
  try {
1639
- url = new URL(value.trim());
1585
+ const parsed = JSON.parse(trimmed);
1586
+ if (!isRecord(parsed)) {
1587
+ return { valid: false };
1588
+ }
1589
+ return { valid: true, parsed };
1640
1590
  } catch {
1641
- return null;
1591
+ return { valid: false };
1642
1592
  }
1643
- if (url.protocol !== "https:" && url.protocol !== "http:") return null;
1644
- if (url.username || url.password) return null;
1645
- if (url.search || url.hash) return null;
1646
- if (url.pathname !== "/" && url.pathname !== "") return null;
1647
- if (url.protocol === "http:" && !isLoopbackHostname(url.hostname)) return null;
1648
- return url.origin;
1649
1593
  }
1650
- var collectConfiguredOrigins = (runtime) => {
1651
- const origins = /* @__PURE__ */ new Set();
1652
- const push = (value) => {
1653
- const normalized = normalizeKnownServerOrigin(value);
1654
- if (normalized) origins.add(normalized);
1655
- };
1656
- push(runtime.currentServer);
1657
- const syncServers = runtime.syncServers;
1658
- if (Array.isArray(syncServers)) syncServers.forEach(push);
1659
- const registry = runtime.userAuthorityRegistry;
1660
- if (registry && typeof registry === "object") {
1661
- for (const entry of Object.values(registry)) {
1662
- if (typeof entry === "string") {
1663
- push(entry);
1594
+ function buildInvalidToolCallSelfHealResult(callId, toolName) {
1595
+ return JSON.stringify({
1596
+ error: true,
1597
+ toolCallId: callId,
1598
+ ...toolName ? { toolName } : {},
1599
+ message: INVALID_TOOL_RESULT_HINT
1600
+ });
1601
+ }
1602
+ function isHexDigit(ch) {
1603
+ return ch >= "0" && ch <= "9" || ch >= "a" && ch <= "f" || ch >= "A" && ch <= "F";
1604
+ }
1605
+ function sanitizeTextContent(text) {
1606
+ if (typeof text !== "string")
1607
+ return text;
1608
+ let out = "";
1609
+ let i = 0;
1610
+ const n = text.length;
1611
+ while (i < n) {
1612
+ const code = text.charCodeAt(i);
1613
+ if (code >= 55296 && code <= 56319) {
1614
+ const next = i + 1 < n ? text.charCodeAt(i + 1) : -1;
1615
+ if (next >= 56320 && next <= 57343) {
1616
+ out += text[i] + text[i + 1];
1617
+ i += 2;
1664
1618
  continue;
1665
1619
  }
1666
- if (entry && typeof entry === "object") {
1667
- const record = entry;
1668
- push(record.authorityServer);
1669
- push(record.homeServer);
1670
- push(record.primaryServer);
1620
+ out += "�";
1621
+ i += 1;
1622
+ continue;
1623
+ }
1624
+ if (code >= 56320 && code <= 57343) {
1625
+ out += "�";
1626
+ i += 1;
1627
+ continue;
1628
+ }
1629
+ if (code === 92) {
1630
+ let backslashRun = 0;
1631
+ let k = i;
1632
+ while (k >= 0 && text.charCodeAt(k) === 92) {
1633
+ backslashRun++;
1634
+ k--;
1635
+ }
1636
+ const alreadyEscaped = backslashRun % 2 === 0;
1637
+ const nextCh = i + 1 < n ? text[i + 1] : "";
1638
+ if (!alreadyEscaped && (nextCh === "x" || nextCh === "u")) {
1639
+ const hexLen = nextCh === "x" ? 2 : 4;
1640
+ let hexCount = 0;
1641
+ let j = i + 2;
1642
+ while (j < n && hexCount < hexLen && isHexDigit(text[j])) {
1643
+ hexCount++;
1644
+ j++;
1645
+ }
1646
+ if (hexCount < hexLen) {
1647
+ out += "\\\\";
1648
+ i += 1;
1649
+ continue;
1650
+ }
1651
+ out += text[i];
1652
+ i += 1;
1653
+ continue;
1671
1654
  }
1672
1655
  }
1656
+ out += text[i];
1657
+ i += 1;
1673
1658
  }
1674
- return origins;
1675
- };
1676
- function resolveToolErrorReportTarget(state, runtime = getRuntimeServerSnapshot(state)) {
1677
- if (!state || typeof state !== "object") return null;
1678
- const snapshot = getSessionSnapshotForState(state);
1679
- const activeAccountId = typeof snapshot?.activeAccountId === "string" ? snapshot.activeAccountId.trim() : "";
1680
- const rawToken = typeof snapshot?.activeToken === "string" ? snapshot.activeToken.trim() : "";
1681
- if (!activeAccountId || !rawToken) return null;
1682
- const configuredOrigins = collectConfiguredOrigins(runtime);
1683
- if (isGoogleAuthoritySession(rawToken)) {
1684
- const sameOrigin = resolveSafeReportOrigin(googleSessionServer(rawToken));
1685
- if (!sameOrigin) return null;
1686
- return { baseUrl: sameOrigin, token: rawToken };
1659
+ return out;
1660
+ }
1661
+ function sanitizeContentText(content) {
1662
+ if (typeof content === "string") {
1663
+ return sanitizeTextContent(content);
1687
1664
  }
1688
- const authorityServer = resolveUserAuthorityServer({
1689
- ownerUserId: activeAccountId,
1690
- registry: runtime.userAuthorityRegistry ?? null
1691
- });
1692
- const authorityOrigin = resolveSafeReportOrigin(authorityServer);
1693
- const currentOrigin = resolveSafeReportOrigin(resolveDesktopSafeServer(runtime.currentServer));
1694
- const authorityKnown = typeof authorityServer === "string" && authorityServer.trim().length > 0;
1695
- const candidate = authorityKnown ? authorityOrigin : currentOrigin;
1696
- if (!candidate) return null;
1697
- if (!configuredOrigins.has(candidate)) return null;
1698
- return { baseUrl: candidate, token: rawToken };
1665
+ if (Array.isArray(content)) {
1666
+ return content.map((part) => {
1667
+ if (part && typeof part === "object") {
1668
+ const p = part;
1669
+ if (typeof p.text === "string") {
1670
+ return { ...p, text: sanitizeTextContent(p.text) };
1671
+ }
1672
+ }
1673
+ return part;
1674
+ });
1675
+ }
1676
+ return content;
1699
1677
  }
1700
- var dedupeKeyOf = (payload) => `${payload.dialogId}|${payload.callId}|${payload.toolName}|${payload.errorClass}`;
1701
- var rememberDedupeKey = (key) => {
1702
- dedupeKeys.set(key, true);
1703
- while (dedupeKeys.size > MAX_DEDUPE_ENTRIES) {
1704
- const oldest = dedupeKeys.keys().next();
1705
- if (oldest.done) break;
1706
- dedupeKeys.delete(oldest.value);
1678
+ function sanitizeResponsesItemText(item) {
1679
+ if (!item || typeof item !== "object")
1680
+ return item;
1681
+ const type = item.type;
1682
+ if (type === "input_text" || type === "output_text") {
1683
+ if (typeof item.text === "string") {
1684
+ return { ...item, text: sanitizeTextContent(item.text) };
1685
+ }
1686
+ return item;
1707
1687
  }
1708
- };
1709
- async function reportToolError(args) {
1710
- const key = dedupeKeyOf(args.payload);
1711
- if (dedupeKeys.has(key)) return false;
1712
- if (inflightReports >= MAX_INFLIGHT_REPORTS) return false;
1713
- const baseUrl = resolveSafeReportOrigin(args.baseUrl);
1714
- if (!baseUrl) return false;
1715
- const requestUrl = `${baseUrl}${TOOL_ERROR_REPORT_PATH}`;
1716
- let requestToken;
1717
- try {
1718
- requestToken = googleSessionRequestToken(args.token, requestUrl);
1719
- } catch {
1720
- return false;
1688
+ if (type === "function_call_output") {
1689
+ if (typeof item.output === "string") {
1690
+ return { ...item, output: sanitizeTextContent(item.output) };
1691
+ }
1692
+ if (Array.isArray(item.output)) {
1693
+ return { ...item, output: sanitizeContentText(item.output) };
1694
+ }
1695
+ return item;
1721
1696
  }
1722
- if (!requestToken) return false;
1723
- if (typeof AbortController !== "function") return false;
1724
- const timeoutMs = typeof args.timeoutMs === "number" && args.timeoutMs > 0 ? args.timeoutMs : REPORT_TIMEOUT_MS;
1725
- rememberDedupeKey(key);
1726
- inflightReports += 1;
1727
- const controller = new AbortController();
1728
- const timer = setTimeout(() => {
1697
+ if (type === "message" && "content" in item) {
1698
+ return { ...item, content: sanitizeContentText(item.content) };
1699
+ }
1700
+ return item;
1701
+ }
1702
+ function normalizeToolCallArgumentsInPlace(call, replacement) {
1703
+ if (!call || typeof call !== "object")
1704
+ return;
1705
+ const fn = call.function;
1706
+ if (!fn || typeof fn !== "object")
1707
+ return;
1708
+ const { valid } = parseToolCallArguments(fn.arguments);
1709
+ if (!valid) {
1710
+ fn.arguments = replacement;
1711
+ } else if (typeof fn.arguments !== "string") {
1729
1712
  try {
1730
- controller.abort();
1713
+ fn.arguments = JSON.stringify(fn.arguments);
1731
1714
  } catch {
1715
+ fn.arguments = replacement;
1732
1716
  }
1733
- }, timeoutMs);
1734
- try {
1735
- const fetchImpl = args.fetchImpl ?? (typeof fetch === "function" ? fetch : void 0);
1736
- if (!fetchImpl) return false;
1737
- const body = buildBoundedBody(pickAllowedFields(args.payload));
1738
- if (!body) return false;
1739
- const response = await fetchImpl(requestUrl, {
1740
- method: "POST",
1741
- headers: {
1742
- "Content-Type": "application/json",
1743
- Authorization: `Bearer ${requestToken}`
1744
- },
1745
- body,
1746
- // 不跟随重定向:避免把 Authorization 带到别处。
1747
- redirect: "error",
1748
- credentials: "omit",
1749
- signal: controller.signal
1750
- });
1751
- return response?.ok === true;
1752
- } catch {
1753
- return false;
1754
- } finally {
1755
- clearTimeout(timer);
1756
- inflightReports -= 1;
1757
1717
  }
1758
1718
  }
1759
- var isBrowserRuntime = () => typeof window !== "undefined" && typeof document !== "undefined";
1760
- function reportToolExecutionErrorInBackground(args) {
1761
- try {
1762
- if (!isBrowserRuntime()) return;
1763
- const payload = buildToolErrorReportPayload(args);
1764
- if (!payload) return;
1765
- const target = resolveToolErrorReportTarget(args.thunkApi?.getState?.(), args.thunkApi?.runtimeServers);
1766
- if (!target) return;
1767
- void reportToolError({ ...target, payload }).catch(() => {
1768
- });
1769
- } catch {
1719
+ function sanitizeOutboundMessages(messages, opts = {}) {
1720
+ if (!Array.isArray(messages) || messages.length === 0)
1721
+ return messages ?? [];
1722
+ const argsReplacement = opts.argsReplacement ?? INVALID_TOOL_ARGS_OUTBOUND_REPLACEMENT;
1723
+ const orphanReplacement = opts.orphanReplacement ?? ORPHAN_TOOL_RESULT_PLACEHOLDER;
1724
+ const cloned = messages.map((msg) => ({ ...msg }));
1725
+ const answeredCallIds = new Set;
1726
+ for (const msg of cloned) {
1727
+ if (msg?.role === "tool" && typeof msg.tool_call_id === "string") {
1728
+ answeredCallIds.add(msg.tool_call_id);
1729
+ }
1770
1730
  }
1731
+ const result = [];
1732
+ for (const msg of cloned) {
1733
+ if (msg && typeof msg === "object" && "content" in msg) {
1734
+ msg.content = sanitizeContentText(msg.content);
1735
+ }
1736
+ if (msg?.role === "assistant" && Array.isArray(msg.tool_calls)) {
1737
+ msg.tool_calls = msg.tool_calls.map((call) => ({
1738
+ ...call,
1739
+ function: { ...call?.function ?? {} }
1740
+ }));
1741
+ for (const call of msg.tool_calls) {
1742
+ normalizeToolCallArgumentsInPlace(call, argsReplacement);
1743
+ }
1744
+ result.push(msg);
1745
+ for (const call of msg.tool_calls) {
1746
+ const callId = typeof call?.id === "string" ? call.id : undefined;
1747
+ if (!callId)
1748
+ continue;
1749
+ if (answeredCallIds.has(callId))
1750
+ continue;
1751
+ answeredCallIds.add(callId);
1752
+ result.push({
1753
+ role: "tool",
1754
+ tool_call_id: callId,
1755
+ content: orphanReplacement
1756
+ });
1757
+ }
1758
+ continue;
1759
+ }
1760
+ result.push(msg);
1761
+ }
1762
+ return result;
1771
1763
  }
1772
-
1773
- // packages/ai/tools/stripModelConfirmationFlags.ts
1774
- var CONFIRMATION_INPUT_KEYS = {
1775
- knowledge_capture_requires_confirmation: "__confirmedKnowledgeCapture",
1776
- self_evolution_requires_confirmation: "__confirmedSelfEvolution",
1777
- agent_update_requires_confirmation: "__confirmedSelfEvolution",
1778
- media_job_start_requires_confirmation: "__confirmedMediaJobStart"
1779
- };
1780
- function stripModelConfirmationFlags(value) {
1781
- if (!value || typeof value !== "object" || Array.isArray(value)) return value;
1782
- return Object.fromEntries(
1783
- Object.entries(value).filter(
1784
- ([key]) => !key.startsWith("__confirmed")
1785
- )
1786
- );
1787
- }
1788
- var MODEL_DIALOG_BINDING_STRIPPED_TOOLS = /* @__PURE__ */ new Set([
1789
- "mediaJobTool",
1790
- "transcribe",
1791
- "translate",
1792
- "exportDocument",
1793
- "readArtifact"
1794
- ]);
1795
- var TRUSTED_ONLY_MODEL_INPUT_KEYS = /* @__PURE__ */ new Set(["confirmationToken", "expectedExecutionRevision"]);
1796
- function stripModelToolArgs(canonicalToolName, value) {
1797
- const base = stripModelConfirmationFlags(value);
1798
- if (!base || typeof base !== "object" || Array.isArray(base)) return base;
1799
- const withoutTrustedOnlyKeys = Object.fromEntries(
1800
- Object.entries(base).filter(
1801
- ([key]) => !TRUSTED_ONLY_MODEL_INPUT_KEYS.has(key)
1802
- )
1803
- );
1804
- if (!MODEL_DIALOG_BINDING_STRIPPED_TOOLS.has(canonicalToolName)) {
1805
- return withoutTrustedOnlyKeys;
1764
+ function sanitizeOutboundResponsesInput(input, opts = {}) {
1765
+ if (!Array.isArray(input) || input.length === 0)
1766
+ return input ?? [];
1767
+ const argsReplacement = opts.argsReplacement ?? INVALID_TOOL_ARGS_OUTBOUND_REPLACEMENT;
1768
+ const orphanReplacement = opts.orphanReplacement ?? ORPHAN_TOOL_RESULT_PLACEHOLDER;
1769
+ const answeredCallIds = new Set;
1770
+ for (const item of input) {
1771
+ if (item?.type === "function_call_output" && typeof item.call_id === "string") {
1772
+ answeredCallIds.add(item.call_id);
1773
+ }
1806
1774
  }
1807
- if (!withoutTrustedOnlyKeys || typeof withoutTrustedOnlyKeys !== "object" || Array.isArray(withoutTrustedOnlyKeys)) {
1808
- return withoutTrustedOnlyKeys;
1775
+ const result = [];
1776
+ for (const item of input) {
1777
+ if (item?.type === "function_call") {
1778
+ const cloned = { ...item };
1779
+ const { valid } = parseToolCallArguments(cloned.arguments);
1780
+ if (!valid) {
1781
+ cloned.arguments = argsReplacement;
1782
+ } else if (typeof cloned.arguments !== "string") {
1783
+ try {
1784
+ cloned.arguments = JSON.stringify(cloned.arguments);
1785
+ } catch {
1786
+ cloned.arguments = argsReplacement;
1787
+ }
1788
+ }
1789
+ result.push(cloned);
1790
+ const callId = typeof cloned.call_id === "string" ? cloned.call_id : undefined;
1791
+ if (callId && !answeredCallIds.has(callId)) {
1792
+ answeredCallIds.add(callId);
1793
+ result.push({
1794
+ type: "function_call_output",
1795
+ call_id: callId,
1796
+ output: orphanReplacement
1797
+ });
1798
+ }
1799
+ continue;
1800
+ }
1801
+ result.push(sanitizeResponsesItemText(item));
1802
+ }
1803
+ return result;
1804
+ }
1805
+ function sanitizeOutboundBody(body) {
1806
+ const next = { ...body };
1807
+ if (Array.isArray(body.messages)) {
1808
+ next.messages = sanitizeOutboundMessages(body.messages);
1809
+ } else if (Array.isArray(body.input)) {
1810
+ next.input = sanitizeOutboundResponsesInput(body.input);
1809
1811
  }
1810
- return Object.fromEntries(
1811
- Object.entries(withoutTrustedOnlyKeys).filter(
1812
- ([key]) => key !== "dialogId" && key !== "autoApproveCredits"
1813
- )
1814
- );
1812
+ return next;
1815
1813
  }
1816
1814
 
1817
- export {
1818
- selectResponsesConversationState,
1819
- updateResponsesConversationState,
1820
- isResponsesConversationStateRejection,
1821
- generateRequestBody,
1822
- sanitizeToolErrorText,
1823
- reportToolExecutionErrorInBackground,
1824
- CONFIRMATION_INPUT_KEYS,
1825
- stripModelToolArgs,
1826
- DirectApiKeyResolutionError,
1827
- performFetchRequest,
1828
- INVALID_TOOL_ARGS_REPLACEMENT,
1829
- parseToolCallArguments,
1830
- buildInvalidToolCallSelfHealResult,
1831
- sanitizeOutboundMessages,
1832
- sanitizeOutboundResponsesInput,
1833
- sanitizeOutboundBody
1834
- };
1815
+ export { selectResponsesConversationState, updateResponsesConversationState, isResponsesConversationStateRejection, generateRequestBody, sanitizeToolErrorText, reportToolExecutionErrorInBackground, CONFIRMATION_INPUT_KEYS, stripModelToolArgs, DirectApiKeyResolutionError, performFetchRequest, INVALID_TOOL_ARGS_REPLACEMENT, parseToolCallArguments, buildInvalidToolCallSelfHealResult, sanitizeOutboundMessages, sanitizeOutboundResponsesInput, sanitizeOutboundBody };