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,356 +1,286 @@
1
1
  import {
2
- buildCliPrompt
3
- } from "./chunk-ATNTHIZI.js";
4
- import {
5
- applyImageConfigRuntimeOverride,
6
- buildDynamicContexts,
7
- buildForegroundTurnAdmissionFetchInit,
8
- buildStaticContexts,
9
- canProxyToExplicitServerBase,
10
- compressOldToolResults,
11
- consumeAgentRunStream,
12
- mergeAgentToolsWithRuntime,
13
- mergeContexts,
14
- projectDesktopToolUiContent,
15
- resolveImageGenerationStreamingState,
16
- resolveTurnToolContext,
17
- validateAccessAndBalance,
18
- withRequestContextBlocks
19
- } from "./chunk-MALPQFGT.js";
20
- import {
21
- resolveUserSkillRuntime
22
- } from "./chunk-TEFD5E2D.js";
23
- import {
24
- buildEmptyCompletionRepairBody,
25
- buildFinalCompletionsRequestBody,
26
- deliverHtmlArtifactToolResult,
27
- filterAndCleanMessages,
28
- handleToolCalls,
29
- persistToolMessages,
30
- readStreamChunk,
31
- sendOpenAICompletionsRequest,
32
- serializeAgentRunMessages,
33
- updateTotalUsage
34
- } from "./chunk-7422ZLGL.js";
35
- import "./chunk-JEXVIMYZ.js";
36
- import {
37
- inlineImageUrlsForCustomProvider,
38
- prepareTools,
39
- shouldInlineImageUrlsForAgent
40
- } from "./chunk-DBEOW57U.js";
41
- import {
42
- DirectApiKeyResolutionError,
43
- INVALID_TOOL_ARGS_REPLACEMENT,
44
- buildInvalidToolCallSelfHealResult,
45
- generateRequestBody,
46
- isResponsesConversationStateRejection,
47
- parseToolCallArguments,
48
- performFetchRequest,
49
- sanitizeOutboundResponsesInput,
50
- selectResponsesConversationState,
51
- updateResponsesConversationState
52
- } from "./chunk-PDSXYHNI.js";
53
- import "./chunk-56OAS5RZ.js";
54
- import {
55
- isWebMcpTurnAllowed,
56
- resolveWebTurnMcpInjection,
57
- stripMcpWebTools
58
- } from "./chunk-EBH4RFJ6.js";
59
- import "./chunk-ZJACPM5O.js";
60
- import "./chunk-NHLLXINQ.js";
61
- import "./chunk-MVOZ22RZ.js";
62
- import "./chunk-4RUQ2PFX.js";
63
- import "./chunk-WDWZPASX.js";
64
- import "./chunk-ZCMAKAZM.js";
2
+ PUBLIC_GPT_IMAGE_2_GENERATOR_AGENT_KEY,
3
+ isSystemBuiltinTrustedAgentKey
4
+ } from "./chunk-6q1b7381.js";
5
+ import"./chunk-7mrqbxe8.js";
65
6
  import {
66
- performServerProxyFetchWithRetry
67
- } from "./chunk-LYPJYBE5.js";
7
+ googleSessionServer,
8
+ getIsDesktopApp,
9
+ resolveDesktopSafeServer,
10
+ getRuntimeServerSnapshot,
11
+ claimDialogTurnPhase,
12
+ setDialogTurnPhase,
13
+ clearDialogTurnPhase,
14
+ addActiveController2,
15
+ removeActiveController2,
16
+ dequeueUserInput2,
17
+ clearPendingUserInputQueue2,
18
+ tokenUsageLiveUpdate2,
19
+ getDialogRuntimeState,
20
+ selectActiveControllers2,
21
+ selectPendingUserInputQueue2,
22
+ subscribe,
23
+ selectIdentityUserId,
24
+ selectIdentityToken,
25
+ selectIdentityUser,
26
+ selectRuntimeCurrentServer,
27
+ selectById2,
28
+ read2,
29
+ write2,
30
+ patch2,
31
+ resolveDialogAgentMode,
32
+ snapshotUserBatchInput,
33
+ createUserBatchExecution,
34
+ selectAdmittedMessages,
35
+ selectAllMsgs,
36
+ toast,
37
+ updateDialogSummaryAction,
38
+ estimateMissingUsage,
39
+ messageStreaming,
40
+ removeTransientMessage,
41
+ finalizeTransientMessageOnError,
42
+ addToolMessage,
43
+ updateToolMessage,
44
+ prepareAndPersistUserMessage,
45
+ runPendingUserBatchRequest,
46
+ messageStreamEnd,
47
+ addUserMessage,
48
+ admitPendingUserMessages,
49
+ startCliChatSession,
50
+ getCliChatSession,
51
+ createCliChatTurnStream,
52
+ getCurrentSpaceId,
53
+ updateTokens2,
54
+ selectCurrentDialogConfig2,
55
+ selectDialogConfigByKey2
56
+ } from "./chunk-c235kypv.js";
57
+ import"./chunk-j0yxesh3.js";
68
58
  import {
59
+ resolveToolBaseUrl2,
60
+ targetForRunKind,
61
+ pushGate,
69
62
  clearGateTurn,
63
+ getUserPreferencesStore,
70
64
  createSSEParser,
71
- pushGate,
72
- targetForRunKind,
73
65
  waitForAbortableDelay
74
- } from "./chunk-ZSZBHRLP.js";
75
- import "./chunk-NF64D32W.js";
66
+ } from "./chunk-ex34n71b.js";
67
+ import"./chunk-8yj4pq79.js";
76
68
  import {
77
- getUserPreferencesStore
78
- } from "./chunk-P62DHV4F.js";
79
- import "./chunk-7E6YXSFZ.js";
80
- import "./chunk-NTUNHTJV.js";
81
- import "./chunk-RIRFHJTW.js";
82
- import "./chunk-WX266G2C.js";
83
- import "./chunk-63W5N6P3.js";
84
- import "./chunk-AGIM7IMJ.js";
85
- import "./chunk-VF4K2QE6.js";
86
- import "./chunk-HXEO5DNV.js";
87
- import "./chunk-TGVVE5BA.js";
69
+ resolveAgentContextWindow3,
70
+ asRecordOrEmpty
71
+ } from "./chunk-2ygg7azv.js";
88
72
  import {
89
- getCurrentSpaceId
90
- } from "./chunk-JDMWYVUF.js";
73
+ resolveAgentProviderMode
74
+ } from "./chunk-90egc9vb.js";
75
+ import"./chunk-fkrgqq8w.js";
91
76
  import {
92
- addToolMessage,
93
- addUserMessage,
94
- admitPendingUserMessages,
95
- createUserBatchExecution,
96
- estimateMissingUsage,
97
- finalizeTransientMessageOnError,
98
- messageStreamEnd,
99
- messageStreaming,
100
- prepareAndPersistUserMessage,
101
- removeTransientMessage,
102
- resolveDialogAgentMode,
103
- runPendingUserBatchRequest,
104
- selectAdmittedMessages,
105
- selectAllMsgs,
106
- selectCurrentDialogConfig,
107
- selectDialogConfigByKey,
108
- snapshotUserBatchInput,
109
- toast,
110
- updateDialogSummaryAction,
111
- updateTokens,
112
- updateToolMessage
113
- } from "./chunk-DBCWXGOC.js";
114
- import "./chunk-KDDXC2IH.js";
115
- import "./chunk-TZXPT53C.js";
116
- import "./chunk-6QDYSCPW.js";
117
- import "./chunk-FGXG6OLW.js";
118
- import "./chunk-TKLBBR7P.js";
119
- import "./chunk-IB5AR52X.js";
120
- import "./chunk-BYXBJQAS.js";
121
- import "./chunk-KZO2MTVM.js";
122
- import "./chunk-E5JV4DCB.js";
123
- import "./chunk-UAD2WT54.js";
77
+ getApiEndpoint,
78
+ isOpenAiResponsesModel
79
+ } from "./chunk-kawvydbk.js";
124
80
  import {
125
- createCliChatTurnStream,
126
- getCliChatSession,
127
- startCliChatSession
128
- } from "./chunk-VXUQWCEZ.js";
129
- import "./chunk-REAE2SZK.js";
130
- import "./chunk-PL5RKESU.js";
81
+ ulid,
82
+ dialogMessageKey2,
83
+ createDialogMessageKeyAndId2
84
+ } from "./chunk-mzadqnyq.js";
85
+ import"./chunk-6yarwtxh.js";
86
+ import {
87
+ splitDialogKeyIdentity
88
+ } from "./chunk-csf18m5w.js";
89
+ import"./chunk-n5ffnhnb.js";
90
+ import"./chunk-f8jepva1.js";
91
+ import {
92
+ toResponsesTools,
93
+ extractTextFromResponseOutput,
94
+ extractImagePartsFromResponseOutput
95
+ } from "./chunk-nvewvf7h.js";
96
+ import"./chunk-v39fea91.js";
97
+ import {
98
+ isContextOverflowText,
99
+ parseApiError
100
+ } from "./chunk-w820gg1w.js";
101
+ import"./chunk-vep7zkha.js";
102
+ import"./chunk-drqzzzvr.js";
103
+ import"./chunk-k2ep3rb2.js";
131
104
  import {
132
105
  isGptProModel,
133
- isPlatformPaidAgentCall,
134
- shouldBlockForGptPro
135
- } from "./chunk-BWJLEN6X.js";
136
- import "./chunk-AMWMV56B.js";
137
- import "./chunk-ADMRXWXJ.js";
138
- import "./chunk-3L2WKC3W.js";
106
+ shouldBlockForGptPro,
107
+ isPlatformPaidAgentCall
108
+ } from "./chunk-mz002yz8.js";
109
+ import"./chunk-s0fpz7ht.js";
139
110
  import {
140
- resolveToolBaseUrl
141
- } from "./chunk-OQH3TAB7.js";
142
- import "./chunk-QYPE3TS3.js";
111
+ getModelInfo
112
+ } from "./chunk-vqgtw1px.js";
113
+ import"./chunk-1fv9k8zt.js";
143
114
  import {
144
- addActiveController,
145
- claimDialogTurnPhase,
146
- clearDialogTurnPhase,
147
- clearPendingUserInputQueue,
148
- dequeueUserInput,
149
- getDialogRuntimeState,
150
- removeActiveController,
151
- selectActiveControllers,
152
- selectPendingUserInputQueue,
153
- setDialogTurnPhase,
154
- subscribe,
155
- tokenUsageLiveUpdate
156
- } from "./chunk-SVKWZ3EG.js";
157
- import "./chunk-S6FAHQDH.js";
158
- import "./chunk-24BICQPB.js";
115
+ resolveClientWire,
116
+ resolveAgentCallPlan
117
+ } from "./chunk-0tsfn0dk.js";
159
118
  import {
160
- patch,
161
- read,
162
- selectById,
163
- write
164
- } from "./chunk-6NYQHXMV.js";
165
- import "./chunk-3PVYUPXK.js";
166
- import "./chunk-HRWRIPTB.js";
167
- import "./chunk-T7KODHYS.js";
119
+ selectResponsesConversationState,
120
+ updateResponsesConversationState,
121
+ isResponsesConversationStateRejection,
122
+ generateRequestBody,
123
+ DirectApiKeyResolutionError,
124
+ performFetchRequest,
125
+ INVALID_TOOL_ARGS_REPLACEMENT,
126
+ parseToolCallArguments,
127
+ buildInvalidToolCallSelfHealResult,
128
+ sanitizeOutboundResponsesInput
129
+ } from "./chunk-c5z7qspt.js";
130
+ import"./chunk-ahhbkad4.js";
131
+ import"./chunk-nyamhphs.js";
132
+ import"./chunk-ac85azv9.js";
168
133
  import {
169
- selectRuntimeCurrentServer
170
- } from "./chunk-MTNQNLSE.js";
171
- import "./chunk-UEILX4EV.js";
172
- import "./chunk-YCITCYSJ.js";
134
+ resolveBuiltinPlatformAgentRecord,
135
+ applyBuiltinAgentRuntimeOverride
136
+ } from "./chunk-nen6rwe4.js";
137
+ import"./chunk-t714r4q0.js";
138
+ import"./chunk-s8q81tda.js";
139
+ import"./chunk-ge97b11r.js";
140
+ import"./chunk-82htft2m.js";
173
141
  import {
174
- getRuntimeServerSnapshot,
175
- resolveDesktopSafeServer,
176
- selectIdentityToken,
177
- selectIdentityUser,
178
- selectIdentityUserId
179
- } from "./chunk-HI5RS2O4.js";
142
+ serializeAgentRunMessages,
143
+ filterAndCleanMessages,
144
+ persistToolMessages,
145
+ deliverHtmlArtifactToolResult,
146
+ handleToolCalls,
147
+ updateTotalUsage,
148
+ readStreamChunk,
149
+ buildFinalCompletionsRequestBody,
150
+ buildEmptyCompletionRepairBody,
151
+ sendOpenAICompletionsRequest
152
+ } from "./chunk-jmnzdwjt.js";
180
153
  import {
181
- getIsDesktopApp,
182
- googleSessionServer
183
- } from "./chunk-K7HLFORE.js";
184
- import "./chunk-MRACVEPZ.js";
185
- import "./chunk-QQ56R7KS.js";
186
- import "./chunk-GBWGPTA7.js";
187
- import "./chunk-S25VJYXV.js";
188
- import "./chunk-VXL2FZTP.js";
154
+ buildForegroundTurnAdmissionFetchInit,
155
+ consumeAgentRunStream,
156
+ projectDesktopToolUiContent,
157
+ compressOldToolResults,
158
+ validateAccessAndBalance,
159
+ buildStaticContexts,
160
+ buildDynamicContexts,
161
+ mergeContexts,
162
+ withRequestContextBlocks,
163
+ canProxyToExplicitServerBase,
164
+ mergeAgentToolsWithRuntime,
165
+ applyImageConfigRuntimeOverride,
166
+ resolveImageGenerationStreamingState,
167
+ resolveTurnToolContext
168
+ } from "./chunk-ek122zzt.js";
169
+ import"./chunk-e3atr4hk.js";
189
170
  import {
190
171
  applyPublicAgentCatalogOverride
191
- } from "./chunk-PHIERFHT.js";
172
+ } from "./chunk-pf5rywc6.js";
173
+ import"./chunk-511q8qzv.js";
192
174
  import {
193
- applyBuiltinAgentRuntimeOverride,
194
- resolveBuiltinPlatformAgentRecord
195
- } from "./chunk-B767MA64.js";
196
- import "./chunk-LLP2NDED.js";
197
- import {
198
- getPublicImageAgentDefaultProfile,
199
- getPublicImageAgentMode
200
- } from "./chunk-VIDPVFP3.js";
201
- import "./chunk-4JH2UMJR.js";
175
+ isWebMcpTurnAllowed,
176
+ stripMcpWebTools,
177
+ resolveWebTurnMcpInjection
178
+ } from "./chunk-dh69vqbd.js";
202
179
  import {
203
- assertDesktopAgentRuntimeTurnBodyHasNoRawSecrets,
204
- buildDesktopAgentRuntimeAgentConfigSnapshot,
205
- buildDesktopAgentRuntimeDialogHistorySnapshot,
206
- evaluateRequestBudget,
207
- extractImageUrlsFromMessages,
208
- stripImagePartsForTextOnlyAgent
209
- } from "./chunk-EZKIRVLJ.js";
210
- import "./chunk-BYXBJQAS.js";
211
- import "./chunk-BAZCS5XG.js";
180
+ resolveRuntimeToolSurfaceForAgent
181
+ } from "./chunk-fs3bvh2p.js";
182
+ import"./chunk-fbdz4f0j.js";
183
+ import"./chunk-j22t9g05.js";
184
+ import"./chunk-jgqdec9b.js";
185
+ import"./chunk-mmdhm4kx.js";
186
+ import"./chunk-r20jw5hb.js";
187
+ import"./chunk-9yr1fy7j.js";
188
+ import"./chunk-9raka469.js";
189
+ import"./chunk-b00vzjkb.js";
190
+ import"./chunk-8dtjbp79.js";
191
+ import"./chunk-eqzvk3xm.js";
192
+ import"./chunk-pkhqb0fs.js";
193
+ import"./chunk-kgah9e46.js";
194
+ import"./chunk-fevdhnbh.js";
195
+ import"./chunk-1ynbq3yr.js";
196
+ import"./chunk-mb5hnfyp.js";
197
+ import"./chunk-nkryrkyp.js";
198
+ import"./chunk-jkw9n4h5.js";
212
199
  import {
213
200
  projectUserPartForModel
214
- } from "./chunk-GH34JXNV.js";
215
- import "./chunk-56GBUMO5.js";
216
- import "./chunk-NH4PUEWK.js";
217
- import {
218
- extractImagePartsFromResponseOutput,
219
- extractTextFromResponseOutput,
220
- toResponsesTools
221
- } from "./chunk-DFI7MVCQ.js";
222
- import "./chunk-4IVMDQBA.js";
223
- import "./chunk-ZV7ZY46L.js";
224
- import "./chunk-LS5KAVFQ.js";
201
+ } from "./chunk-f9yvy9t9.js";
225
202
  import {
226
- isContextOverflowText,
227
- parseApiError
228
- } from "./chunk-2OROOEOQ.js";
203
+ shouldInlineImageUrlsForAgent,
204
+ inlineImageUrlsForCustomProvider,
205
+ prepareTools
206
+ } from "./chunk-gcq01td7.js";
207
+ import"./chunk-x9zfjnrc.js";
229
208
  import {
230
- resolveAgentCallPlan,
231
- resolveClientWire
232
- } from "./chunk-PEXGRTTQ.js";
233
- import "./chunk-D2LTQAGN.js";
234
- import "./chunk-CA7LGAHV.js";
235
- import "./chunk-4Y6CZ2N4.js";
209
+ resolveUserSkillRuntime
210
+ } from "./chunk-zt73yc33.js";
236
211
  import {
237
- resolveAgentContextWindow
238
- } from "./chunk-RYMLMTPZ.js";
239
- import "./chunk-5ZUL4CUO.js";
212
+ evaluateRequestBudget,
213
+ extractImageUrlsFromMessages,
214
+ stripImagePartsForTextOnlyAgent,
215
+ buildDesktopAgentRuntimeAgentConfigSnapshot,
216
+ buildDesktopAgentRuntimeDialogHistorySnapshot,
217
+ assertDesktopAgentRuntimeTurnBodyHasNoRawSecrets
218
+ } from "./chunk-7ks60vxy.js";
240
219
  import {
241
- getModelInfo
242
- } from "./chunk-ZCLSM5AK.js";
243
- import "./chunk-H57T64RA.js";
244
- import "./chunk-5MMAK75Q.js";
245
- import "./chunk-6R4IY46J.js";
246
- import "./chunk-SSGTV4FC.js";
220
+ buildCliPrompt
221
+ } from "./chunk-2pj6qzq5.js";
222
+ import"./chunk-f3ad6q4h.js";
247
223
  import {
248
- asRecordOrEmpty
249
- } from "./chunk-KX6YBIHG.js";
250
- import "./chunk-E6A5NHDH.js";
251
- import "./chunk-DWLEOOGR.js";
224
+ performServerProxyFetchWithRetry
225
+ } from "./chunk-3qfpcdkm.js";
226
+ import"./chunk-p6se1rx0.js";
252
227
  import {
253
- isAbortError
254
- } from "./chunk-7DPNBQSV.js";
255
- import "./chunk-HEVRQGGH.js";
256
- import "./chunk-EWQ3HGNZ.js";
228
+ getPublicImageAgentMode,
229
+ getPublicImageAgentDefaultProfile
230
+ } from "./chunk-n3r1ebdm.js";
257
231
  import {
258
232
  estimateTokenCount
259
- } from "./chunk-PSCNXBYA.js";
260
- import "./chunk-BV3FLP2L.js";
261
- import "./chunk-HYCVEESH.js";
262
- import "./chunk-J42X32PV.js";
263
- import "./chunk-EUGTFFO6.js";
264
- import "./chunk-AETZ7AD6.js";
233
+ } from "./chunk-t6q69p83.js";
234
+ import"./chunk-av2mzeqz.js";
265
235
  import {
266
- resolveRuntimeToolSurfaceForAgent
267
- } from "./chunk-TSBJVMNW.js";
268
- import {
269
- PUBLIC_GPT_IMAGE_2_GENERATOR_AGENT_KEY,
270
- isSystemBuiltinTrustedAgentKey
271
- } from "./chunk-4DBTBNTX.js";
236
+ isAbortError
237
+ } from "./chunk-a7bz6nc3.js";
272
238
  import {
273
239
  extractCustomId
274
- } from "./chunk-M2EJHDJP.js";
275
- import "./chunk-UYQILGDR.js";
276
- import "./chunk-KGKTN2NX.js";
277
- import {
278
- isOpenAiResponsesModel
279
- } from "./chunk-BVYHE6QD.js";
280
- import "./chunk-HJTI7RZV.js";
281
- import "./chunk-ZC3CMUKU.js";
282
- import {
283
- getApiEndpoint
284
- } from "./chunk-RI7SXDJW.js";
285
- import "./chunk-7LR2IFUH.js";
286
- import "./chunk-JRTNUU5Z.js";
240
+ } from "./chunk-srncrd3f.js";
287
241
  import {
288
242
  isRecord
289
- } from "./chunk-KUG52IAP.js";
290
- import "./chunk-Z3KTXWWB.js";
291
- import "./chunk-2SXN7LAY.js";
292
- import "./chunk-KHCLMKZZ.js";
293
- import "./chunk-DSBRIUX5.js";
294
- import "./chunk-35JIFLIG.js";
295
- import "./chunk-SR57FDTX.js";
296
- import "./chunk-MDAYRIP7.js";
297
- import "./chunk-G22P2J7O.js";
298
- import "./chunk-QSJ3HFEF.js";
299
- import "./chunk-G7Y4GXTY.js";
300
- import "./chunk-6UBGXX2W.js";
301
- import "./chunk-OW765XBU.js";
243
+ } from "./chunk-ws402twv.js";
302
244
  import {
303
245
  toErrorMessage
304
- } from "./chunk-HNMXYYJR.js";
305
- import "./chunk-DLXL4NSL.js";
306
- import {
307
- createDialogMessageKeyAndId,
308
- dialogMessageKey,
309
- ulid
310
- } from "./chunk-OJKUU3LP.js";
311
- import {
312
- splitDialogKeyIdentity
313
- } from "./chunk-YZMNK53S.js";
314
- import "./chunk-I42VC5KR.js";
246
+ } from "./chunk-jec44fkj.js";
315
247
  import {
316
248
  asTrimmedString
317
- } from "./chunk-3EUW3WEO.js";
318
- import "./chunk-WWC7I6TA.js";
319
- import "./chunk-U6VC4MU4.js";
320
- import "./chunk-LHTXSC2E.js";
321
- import "./chunk-2LFYMWM3.js";
322
- import "./chunk-JKVOKKMQ.js";
323
- import "./chunk-IV6VUVLJ.js";
324
- import "./chunk-FI4DPLR7.js";
325
- import "./chunk-4SN6J65J.js";
326
- import "./chunk-CF7PE763.js";
249
+ } from "./chunk-wfvvnmmj.js";
327
250
  import {
328
251
  asOptionalTrimmedString
329
- } from "./chunk-G3SUCT4W.js";
330
- import "./chunk-U67V476Y.js";
252
+ } from "./chunk-p1vg4bx8.js";
331
253
 
332
254
  // packages/ai/agent/isVoiceModel.ts
333
255
  function isVoiceModel(model, provider) {
334
256
  const providerLower = String(provider || "").toLowerCase();
335
257
  const modelLower = String(model || "").toLowerCase();
336
- if (providerLower === "openai" && ["gpt-live-1", "gpt-live-1.1"].includes(modelLower)) return true;
337
- if (providerLower === "xai" && modelLower === "grok-voice-latest") return true;
338
- if (providerLower === "google" && modelLower.includes("live")) return true;
339
- if (modelLower.includes("live-preview")) return true;
340
- if (modelLower.includes("live-001")) return true;
341
- if (modelLower.includes("native-audio")) return true;
258
+ if (providerLower === "openai" && ["gpt-live-1", "gpt-live-1.1"].includes(modelLower))
259
+ return true;
260
+ if (providerLower === "xai" && modelLower === "grok-voice-latest")
261
+ return true;
262
+ if (providerLower === "google" && modelLower.includes("live"))
263
+ return true;
264
+ if (modelLower.includes("live-preview"))
265
+ return true;
266
+ if (modelLower.includes("live-001"))
267
+ return true;
268
+ if (modelLower.includes("native-audio"))
269
+ return true;
342
270
  return false;
343
271
  }
344
272
 
345
273
  // packages/ai/agent/isLiveAudioOnlyAgent.ts
346
274
  function isLiveAudioOnlyAgent(agent) {
347
- if (agent.defaultInteractionMode !== "live_audio") return false;
275
+ if (agent.defaultInteractionMode !== "live_audio")
276
+ return false;
348
277
  return isVoiceModel(agent.model, agent.provider);
349
278
  }
350
279
 
351
280
  // packages/ai/agent/desktopTurnSegments.ts
352
281
  function attachToolCallIdToSegment(segments, callId) {
353
- if (!segments || segments.length === 0) return;
282
+ if (!segments || segments.length === 0)
283
+ return;
354
284
  const current = segments[segments.length - 1];
355
285
  if (!current.toolCallIds) {
356
286
  current.toolCallIds = [];
@@ -361,7 +291,7 @@ function resolveSegmentToolCalls(toolCallIds, turnMessages) {
361
291
  if (!toolCallIds || toolCallIds.length === 0 || !Array.isArray(turnMessages) || turnMessages.length === 0) {
362
292
  return [];
363
293
  }
364
- const callMap = /* @__PURE__ */ new Map();
294
+ const callMap = new Map;
365
295
  for (const msg of turnMessages) {
366
296
  if (Array.isArray(msg?.tool_calls)) {
367
297
  for (const tc of msg.tool_calls) {
@@ -381,28 +311,30 @@ function resolveSegmentToolCalls(toolCallIds, turnMessages) {
381
311
  return resolved;
382
312
  }
383
313
  function buildMinimalToolCallsFromIds(toolCallIds, toolNameById) {
384
- if (!toolCallIds || toolCallIds.length === 0) return [];
314
+ if (!toolCallIds || toolCallIds.length === 0)
315
+ return [];
385
316
  const result = [];
386
317
  for (const id of toolCallIds) {
387
- if (!toolNameById.has(id)) continue;
318
+ if (!toolNameById.has(id))
319
+ continue;
388
320
  const name = toolNameById.get(id) || "tool";
389
321
  result.push({ id, type: "function", function: { name, arguments: "{}" } });
390
322
  }
391
323
  return result;
392
324
  }
393
325
  function selectPersistableFinalizedSegments(segments) {
394
- if (!Array.isArray(segments)) return [];
395
- return segments.filter(
396
- (segment) => segment.finalized && (segment.content.length > 0 || segment.toolCallIds && segment.toolCallIds.length > 0)
397
- );
326
+ if (!Array.isArray(segments))
327
+ return [];
328
+ return segments.filter((segment) => segment.finalized && (segment.content.length > 0 || segment.toolCallIds && segment.toolCallIds.length > 0));
398
329
  }
399
330
 
400
331
  // packages/chat/queue/chatQueueLifecycleActions.ts
401
332
  function runChatQueueTurnEnd(payload) {
402
333
  return (_dispatch, _getState, extra) => {
403
334
  const adapter = extra?.chatQueueAdapter;
404
- if (!adapter) return;
405
- void adapter.notifyTurnEnd(payload.dialogKey, {
335
+ if (!adapter)
336
+ return;
337
+ adapter.notifyTurnEnd(payload.dialogKey, {
406
338
  ok: payload.ok,
407
339
  aborted: payload.aborted
408
340
  });
@@ -411,9 +343,10 @@ function runChatQueueTurnEnd(payload) {
411
343
 
412
344
  // packages/agent-runtime/platformAgentCatalogOverrides.ts
413
345
  function applyPlatformAgentOverrides(record, agentKey) {
414
- if (!record || typeof record !== "object") return record;
346
+ if (!record || typeof record !== "object")
347
+ return record;
415
348
  const raw = record;
416
- const effectiveKey = agentKey ?? (typeof raw.dbKey === "string" ? raw.dbKey : void 0) ?? (typeof raw.key === "string" ? raw.key : void 0) ?? (typeof raw.id === "string" ? raw.id : void 0);
349
+ const effectiveKey = agentKey ?? (typeof raw.dbKey === "string" ? raw.dbKey : undefined) ?? (typeof raw.key === "string" ? raw.key : undefined) ?? (typeof raw.id === "string" ? raw.id : undefined);
417
350
  const builtinApplied = effectiveKey ? applyBuiltinAgentRuntimeOverride(effectiveKey, record) : record;
418
351
  return applyPublicAgentCatalogOverride(builtinApplied, effectiveKey);
419
352
  }
@@ -426,17 +359,13 @@ var normalizeInitialStreamRetryAfterMs = (value) => {
426
359
  return Number.isFinite(parsed) && parsed >= 0 ? Math.round(parsed) : DEFAULT_INITIAL_STREAM_RETRY_AFTER_MS;
427
360
  };
428
361
  var isRetryableInitialStreamError = (error) => {
429
- if (!error || isAbortError(error)) return false;
362
+ if (!error || isAbortError(error))
363
+ return false;
430
364
  const message = typeof error?.message === "string" ? error.message : String(error);
431
- return /ECONNRESET|ECONNREFUSED|EPIPE|socket hang up|network error|failed to fetch|fetch failed|load failed|connection closed|stream ended before first visible delta|response stream ended before first visible delta|模型响应流 .* 秒内没有返回新内容/i.test(
432
- message
433
- );
365
+ return /ECONNRESET|ECONNREFUSED|EPIPE|socket hang up|network error|failed to fetch|fetch failed|load failed|connection closed|stream ended before first visible delta|response stream ended before first visible delta|模型响应流 .* 秒内没有返回新内容/i.test(message);
434
366
  };
435
367
  var waitForInitialStreamRetry = async (retryAfterMs, signal) => {
436
- await waitForAbortableDelay(
437
- normalizeInitialStreamRetryAfterMs(retryAfterMs),
438
- signal
439
- );
368
+ await waitForAbortableDelay(normalizeInitialStreamRetryAfterMs(retryAfterMs), signal);
440
369
  };
441
370
 
442
371
  // packages/ai/chat/sendOpenAIResponseRequest.ts
@@ -455,11 +384,10 @@ var withImageGenerationStage = (messageMetadata, stage) => {
455
384
  }
456
385
  };
457
386
  };
458
- var shouldShowImageSavingState = (contentBuffer) => contentBuffer.some((part) => part?.type === "image_url") && !contentBuffer.some(
459
- (part) => part?.type === "text" && typeof part.text === "string" && part.text.trim()
460
- );
387
+ var shouldShowImageSavingState = (contentBuffer) => contentBuffer.some((part) => part?.type === "image_url") && !contentBuffer.some((part) => part?.type === "text" && typeof part.text === "string" && part.text.trim());
461
388
  var logQuickChatPerfStage = (startedAt, stage, details) => {
462
- if (!startedAt) return;
389
+ if (!startedAt)
390
+ return;
463
391
  const now = typeof performance !== "undefined" ? performance.now() : Date.now();
464
392
  console.info("[QuickChatPerf]", {
465
393
  stage,
@@ -469,11 +397,11 @@ var logQuickChatPerfStage = (startedAt, stage, details) => {
469
397
  });
470
398
  };
471
399
  var safeCancel = async (reader) => {
472
- if (!reader) return;
400
+ if (!reader)
401
+ return;
473
402
  try {
474
403
  await reader.cancel();
475
- } catch {
476
- }
404
+ } catch {}
477
405
  };
478
406
  var ensureToolCall = (state, key, partial) => {
479
407
  let toolCall = state.assistantToolCalls.find((call) => call.id === key);
@@ -485,34 +413,41 @@ var ensureToolCall = (state, key, partial) => {
485
413
  };
486
414
  state.assistantToolCalls.push(toolCall);
487
415
  }
488
- if (partial.id) toolCall.id = partial.id;
489
- if (partial.function?.name) toolCall.function.name = partial.function.name;
416
+ if (partial.id)
417
+ toolCall.id = partial.id;
418
+ if (partial.function?.name)
419
+ toolCall.function.name = partial.function.name;
490
420
  if (typeof partial.function?.arguments === "string") {
491
421
  toolCall.function.arguments = partial.function.arguments;
492
422
  }
493
423
  return toolCall;
494
424
  };
495
425
  var extractTextFromOutputItem = (item) => {
496
- if (item?.type !== "message" || !Array.isArray(item.content)) return "";
497
- return item.content.filter(
498
- (content) => content?.type === "output_text" && typeof content.text === "string"
499
- ).map((content) => content.text).join("");
426
+ if (item?.type !== "message" || !Array.isArray(item.content))
427
+ return "";
428
+ return item.content.filter((content) => content?.type === "output_text" && typeof content.text === "string").map((content) => content.text).join("");
500
429
  };
501
430
  var getStreamErrorMessage = (event) => {
502
431
  const directMessage = asOptionalTrimmedString(event?.message);
503
- if (directMessage) return directMessage;
432
+ if (directMessage)
433
+ return directMessage;
504
434
  const nestedMessage = asOptionalTrimmedString(event?.error?.message) ?? asOptionalTrimmedString(event?.error?.msg);
505
- if (nestedMessage) return nestedMessage;
435
+ if (nestedMessage)
436
+ return nestedMessage;
506
437
  const nestedCode = asOptionalTrimmedString(event?.error?.code) ?? asOptionalTrimmedString(event?.code);
507
- if (nestedCode) return nestedCode;
438
+ if (nestedCode)
439
+ return nestedCode;
508
440
  const nestedType = asOptionalTrimmedString(event?.error?.type);
509
- if (nestedType) return nestedType;
441
+ if (nestedType)
442
+ return nestedType;
510
443
  const eventType = asOptionalTrimmedString(event?.type);
511
- if (eventType && eventType !== "error") return eventType;
444
+ if (eventType && eventType !== "error")
445
+ return eventType;
512
446
  return "Unknown error";
513
447
  };
514
448
  var hasReportedTokenOrCostUsage = (usage) => {
515
- if (!usage || typeof usage !== "object") return false;
449
+ if (!usage || typeof usage !== "object")
450
+ return false;
516
451
  const hasTokenField = [
517
452
  "prompt_tokens",
518
453
  "completion_tokens",
@@ -530,9 +465,7 @@ function buildResponsesRequestBodyWithTools(bodyData, agentConfig) {
530
465
  const functionTools = getModelInfo(agentConfig.model)?.hasImageOutput ? [] : prepareTools(agentConfig.tools ?? [], { provider: agentConfig.provider });
531
466
  const imageMode = getPublicImageAgentMode(agentConfig);
532
467
  const imageProfile = imageMode === "continuous" ? getPublicImageAgentDefaultProfile("continuous") : null;
533
- const imageGenerationModel = asOptionalTrimmedString(
534
- agentConfig?.imageModel
535
- );
468
+ const imageGenerationModel = asOptionalTrimmedString(agentConfig?.imageModel);
536
469
  const tools = [
537
470
  ...toResponsesTools(functionTools) ?? [],
538
471
  ...shouldEnableBuiltInImageGeneration(agentConfig) ? [
@@ -552,7 +485,8 @@ function buildResponsesRequestBodyWithTools(bodyData, agentConfig) {
552
485
  ] : []
553
486
  ];
554
487
  const sourceBodyData = agentConfig.dbKey === PUBLIC_GPT_IMAGE_2_GENERATOR_AGENT_KEY && Array.isArray(bodyData.input) ? { ...bodyData, input: bodyData.input.map((item) => {
555
- if (item?.role !== "user" || !Array.isArray(item.content) || !item.content.some((part) => part?.type === "input_image")) return item;
488
+ if (item?.role !== "user" || !Array.isArray(item.content) || !item.content.some((part) => part?.type === "input_image"))
489
+ return item;
556
490
  return { ...item, content: [
557
491
  ...item.content.filter((part) => part?.type !== "input_image"),
558
492
  { type: "input_text", text: "This message includes image attachments. For the current generation request, call openAIGptImageGenerate with the prompt; the runtime supplies current-turn reference images automatically." }
@@ -580,21 +514,21 @@ var sendOpenAIResponseRequest = async ({
580
514
  }) => {
581
515
  const { dispatch, getState, signal: thunkSignal } = thunkApi;
582
516
  const dialogId = splitDialogKeyIdentity(dialogKey)?.dialogId ?? extractCustomId(dialogKey);
583
- const controller = new AbortController();
517
+ const controller = new AbortController;
584
518
  thunkSignal.addEventListener("abort", () => controller.abort());
585
519
  const signal = controller.signal;
586
- const streamSpaceId = getCurrentSpaceId() || void 0;
520
+ const streamSpaceId = getCurrentSpaceId() || undefined;
587
521
  let messageId;
588
522
  let msgKey;
589
523
  if (parentMessageId) {
590
524
  messageId = parentMessageId;
591
525
  msgKey = `msg:${dialogId}:${messageId}`;
592
526
  } else {
593
- const newIds = createDialogMessageKeyAndId(dialogId);
527
+ const newIds = createDialogMessageKeyAndId2(dialogId);
594
528
  messageId = newIds.messageId;
595
529
  msgKey = newIds.key;
596
530
  }
597
- dispatch(addActiveController({ messageId, controller, dialogKey }));
531
+ dispatch(addActiveController2({ messageId, controller, dialogKey }));
598
532
  const state = {
599
533
  content: "",
600
534
  contentBuffer: [],
@@ -612,9 +546,9 @@ var sendOpenAIResponseRequest = async ({
612
546
  hasHandedOff,
613
547
  finishReason,
614
548
  messageId,
615
- usage: state.usage ?? void 0,
549
+ usage: state.usage ?? undefined,
616
550
  billingFailed: state.billingFailed,
617
- responseId: typeof state.completedResponse?.id === "string" ? state.completedResponse.id : void 0,
551
+ responseId: typeof state.completedResponse?.id === "string" ? state.completedResponse.id : undefined,
618
552
  ...state.responsesStateFallback ? { responsesStateFallback: true } : {}
619
553
  });
620
554
  const resetStateForRetry = () => {
@@ -627,20 +561,18 @@ var sendOpenAIResponseRequest = async ({
627
561
  activeMessageMetadata = messageMetadata;
628
562
  };
629
563
  const canRetryInitialResponseAttempt = (attempt, loggedFirstVisibleDelta, finishReason) => attempt < MAX_INITIAL_STREAM_RETRIES && !loggedFirstVisibleDelta && !state.assistantToolCalls.length && !finishReason && !state.completedResponse;
630
- const flush = () => dispatch(
631
- messageStreaming({
632
- id: messageId,
633
- dialogId,
634
- dbKey: msgKey,
635
- content: state.contentBuffer,
636
- thinkContent: state.reasoning,
637
- role: "assistant",
638
- agentKey: agentConfig.dbKey,
639
- cybotKey: agentConfig.dbKey,
640
- ...asOptionalTrimmedString(agentConfig?.name) ? { agentName: asOptionalTrimmedString(agentConfig?.name) } : {},
641
- ...activeMessageMetadata ?? {}
642
- })
643
- );
564
+ const flush = () => dispatch(messageStreaming({
565
+ id: messageId,
566
+ dialogId,
567
+ dbKey: msgKey,
568
+ content: state.contentBuffer,
569
+ thinkContent: state.reasoning,
570
+ role: "assistant",
571
+ agentKey: agentConfig.dbKey,
572
+ cybotKey: agentConfig.dbKey,
573
+ ...asOptionalTrimmedString(agentConfig?.name) ? { agentName: asOptionalTrimmedString(agentConfig?.name) } : {},
574
+ ...activeMessageMetadata ?? {}
575
+ }));
644
576
  const finalize = async () => {
645
577
  if (!state.content) {
646
578
  const completedText = extractTextFromResponseOutput(state.completedResponse);
@@ -660,51 +592,42 @@ var sendOpenAIResponseRequest = async ({
660
592
  if (state.contentBuffer.length === 0 && state.content) {
661
593
  state.contentBuffer = seg(state.content);
662
594
  }
663
- const hasVisibleOutput = state.contentBuffer.some(
664
- (part) => part.type === "image_url" || part.type === "text" && typeof part.text === "string" && part.text.trim()
665
- );
595
+ const hasVisibleOutput = state.contentBuffer.some((part) => part.type === "image_url" || part.type === "text" && typeof part.text === "string" && part.text.trim());
666
596
  if (!hasVisibleOutput && state.assistantToolCalls.length === 0 && !hasReportedTokenOrCostUsage(state.usage)) {
667
597
  state.billingFailed = true;
668
598
  }
669
- activeMessageMetadata = withImageGenerationStage(
670
- activeMessageMetadata,
671
- "saving"
672
- );
599
+ activeMessageMetadata = withImageGenerationStage(activeMessageMetadata, "saving");
673
600
  if (activeMessageMetadata?.imageGenerationState && shouldShowImageSavingState(state.contentBuffer)) {
674
- dispatch(
675
- messageStreaming({
676
- id: messageId,
677
- dialogId,
678
- dbKey: msgKey,
679
- content: "",
680
- thinkContent: state.reasoning,
681
- role: "assistant",
682
- agentKey: agentConfig.dbKey,
683
- cybotKey: agentConfig.dbKey,
684
- ...asOptionalTrimmedString(agentConfig?.name) ? { agentName: asOptionalTrimmedString(agentConfig?.name) } : {},
685
- ...activeMessageMetadata ?? {}
686
- })
687
- );
601
+ dispatch(messageStreaming({
602
+ id: messageId,
603
+ dialogId,
604
+ dbKey: msgKey,
605
+ content: "",
606
+ thinkContent: state.reasoning,
607
+ role: "assistant",
608
+ agentKey: agentConfig.dbKey,
609
+ cybotKey: agentConfig.dbKey,
610
+ ...asOptionalTrimmedString(agentConfig?.name) ? { agentName: asOptionalTrimmedString(agentConfig?.name) } : {},
611
+ ...activeMessageMetadata ?? {}
612
+ }));
688
613
  } else {
689
614
  flush();
690
615
  }
691
- await dispatch(
692
- messageStreamEnd({
693
- finalContentBuffer: state.contentBuffer,
694
- totalUsage: state.usage,
695
- msgKey,
696
- agentConfig,
697
- dialogId,
698
- dialogKey,
699
- messageId,
700
- reasoningBuffer: state.reasoning,
701
- messageMetadata: activeMessageMetadata,
702
- toolCalls: state.assistantToolCalls,
703
- spaceId: streamSpaceId,
704
- billingFailed: state.billingFailed,
705
- skipBilling: state.skipBilling
706
- })
707
- );
616
+ await dispatch(messageStreamEnd({
617
+ finalContentBuffer: state.contentBuffer,
618
+ totalUsage: state.usage,
619
+ msgKey,
620
+ agentConfig,
621
+ dialogId,
622
+ dialogKey,
623
+ messageId,
624
+ reasoningBuffer: state.reasoning,
625
+ messageMetadata: activeMessageMetadata,
626
+ toolCalls: state.assistantToolCalls,
627
+ spaceId: streamSpaceId,
628
+ billingFailed: state.billingFailed,
629
+ skipBilling: state.skipBilling
630
+ }));
708
631
  };
709
632
  const processToolCalls = async () => {
710
633
  if (!state.assistantToolCalls.length) {
@@ -714,7 +637,8 @@ var sendOpenAIResponseRequest = async ({
714
637
  const validCalls = [];
715
638
  const invalidCalls = [];
716
639
  for (const call of state.assistantToolCalls) {
717
- if (!call) continue;
640
+ if (!call)
641
+ continue;
718
642
  if (parseToolCallArguments(call?.function?.arguments).valid) {
719
643
  validCalls.push(call);
720
644
  } else {
@@ -729,13 +653,15 @@ var sendOpenAIResponseRequest = async ({
729
653
  }
730
654
  }
731
655
  if (invalidCalls.length > 0) {
732
- const invalidById = /* @__PURE__ */ new Map();
656
+ const invalidById = new Map;
733
657
  for (const call of invalidCalls) {
734
- if (call?.id) invalidById.set(call.id, call);
658
+ if (call?.id)
659
+ invalidById.set(call.id, call);
735
660
  }
736
661
  state.assistantToolCalls = state.assistantToolCalls.map((call) => {
737
- const invalid = call?.id ? invalidById.get(call.id) : void 0;
738
- if (!invalid) return call;
662
+ const invalid = call?.id ? invalidById.get(call.id) : undefined;
663
+ if (!invalid)
664
+ return call;
739
665
  return {
740
666
  ...call,
741
667
  type: "function",
@@ -745,12 +671,12 @@ var sendOpenAIResponseRequest = async ({
745
671
  }
746
672
  };
747
673
  });
748
- for (let i = 0; i < invalidCalls.length; i++) {
674
+ for (let i = 0;i < invalidCalls.length; i++) {
749
675
  const call = invalidCalls[i];
750
676
  const callId = call?.id || `call_${Date.now()}_${Math.random().toString(36).slice(2)}`;
751
677
  const toolIndex = validCalls.length + i;
752
678
  const runningToolMessageId = `${messageId}-t${String(toolIndex).padStart(3, "0")}`;
753
- const runningToolDbKey = dialogMessageKey(dialogId, runningToolMessageId);
679
+ const runningToolDbKey = dialogMessageKey2(dialogId, runningToolMessageId);
754
680
  const toolName = call?.function?.name || "unknown";
755
681
  const selfHealContent = buildInvalidToolCallSelfHealResult(callId, toolName);
756
682
  const toolMessage = {
@@ -772,20 +698,18 @@ var sendOpenAIResponseRequest = async ({
772
698
  rawToolCall: call,
773
699
  error: {
774
700
  type: "InvalidToolCallArguments",
775
- message: "\u5DE5\u5177\u53C2\u6570 JSON \u88AB\u622A\u65AD\u6216\u975E\u6CD5\uFF0C\u5DF2\u8DF3\u8FC7\u6267\u884C\u5E76\u66FF\u6362\u4E3A\u5360\u4F4D arguments\u3002",
701
+ message: "工具参数 JSON 被截断或非法,已跳过执行并替换为占位 arguments。",
776
702
  retryable: true
777
703
  },
778
- summary: `\u274C ${toolName} \u53C2\u6570\u88AB\u622A\u65AD\uFF0C\u5DF2\u8DF3\u8FC7`
704
+ summary: `❌ ${toolName} 参数被截断,已跳过`
779
705
  }
780
706
  };
781
707
  dispatch(addToolMessage(toolMessage));
782
708
  const { controller: _c, ...messageToWrite } = toolMessage;
783
- await dispatch(
784
- write({
785
- data: { ...messageToWrite, type: "msg" /* MSG */ },
786
- customKey: runningToolDbKey
787
- })
788
- );
709
+ await dispatch(write2({
710
+ data: { ...messageToWrite, type: "msg" /* MSG */ },
711
+ customKey: runningToolDbKey
712
+ }));
789
713
  }
790
714
  }
791
715
  if (!validCalls.length) {
@@ -793,29 +717,25 @@ var sendOpenAIResponseRequest = async ({
793
717
  return buildMeta(false, false, null);
794
718
  }
795
719
  if (state.usage) {
796
- dispatch(
797
- tokenUsageLiveUpdate({
798
- input_tokens: state.usage.prompt_tokens ?? state.usage.input_tokens,
799
- output_tokens: state.usage.completion_tokens ?? state.usage.output_tokens,
800
- cost: state.usage.cost,
801
- dialogKey
802
- })
803
- );
720
+ dispatch(tokenUsageLiveUpdate2({
721
+ input_tokens: state.usage.prompt_tokens ?? state.usage.input_tokens,
722
+ output_tokens: state.usage.completion_tokens ?? state.usage.output_tokens,
723
+ cost: state.usage.cost,
724
+ dialogKey
725
+ }));
804
726
  }
805
- const result = await dispatch(
806
- handleToolCalls({
807
- accumulatedCalls: validCalls,
808
- currentContentBuffer: state.contentBuffer,
809
- agentConfig,
810
- messageId,
811
- dialogId,
812
- dialogKey,
813
- userMessageId,
814
- currentReferenceImageUrls,
815
- serverBase: thunkApi.serverBase,
816
- runtimeServers: thunkApi.runtimeServers
817
- })
818
- ).unwrap();
727
+ const result = await dispatch(handleToolCalls({
728
+ accumulatedCalls: validCalls,
729
+ currentContentBuffer: state.contentBuffer,
730
+ agentConfig,
731
+ messageId,
732
+ dialogId,
733
+ dialogKey,
734
+ userMessageId,
735
+ currentReferenceImageUrls,
736
+ serverBase: thunkApi.serverBase,
737
+ runtimeServers: thunkApi.runtimeServers
738
+ })).unwrap();
819
739
  state.content = Array.isArray(result.finalContentBuffer) ? result.finalContentBuffer.filter((part) => part?.type === "text").map((part) => part.text ?? "").join("") : state.content;
820
740
  state.contentBuffer = Array.isArray(result.finalContentBuffer) ? result.finalContentBuffer : state.contentBuffer;
821
741
  await finalize();
@@ -825,20 +745,18 @@ var sendOpenAIResponseRequest = async ({
825
745
  let responsesStateFallbackUsed = false;
826
746
  try {
827
747
  if (!parentMessageId) {
828
- dispatch(
829
- messageStreaming({
830
- id: messageId,
831
- dialogId,
832
- dbKey: msgKey,
833
- content: "",
834
- role: "assistant",
835
- agentKey: agentConfig.dbKey,
836
- cybotKey: agentConfig.dbKey,
837
- ...asOptionalTrimmedString(agentConfig?.name) ? { agentName: asOptionalTrimmedString(agentConfig?.name) } : {},
838
- ...activeMessageMetadata ?? {},
839
- isStreaming: true
840
- })
841
- );
748
+ dispatch(messageStreaming({
749
+ id: messageId,
750
+ dialogId,
751
+ dbKey: msgKey,
752
+ content: "",
753
+ role: "assistant",
754
+ agentKey: agentConfig.dbKey,
755
+ cybotKey: agentConfig.dbKey,
756
+ ...asOptionalTrimmedString(agentConfig?.name) ? { agentName: asOptionalTrimmedString(agentConfig?.name) } : {},
757
+ ...activeMessageMetadata ?? {},
758
+ isStreaming: true
759
+ }));
842
760
  }
843
761
  const buildRequestBody = (body) => buildResponsesRequestBodyWithTools(body, agentConfig);
844
762
  let requestBody = buildRequestBody(bodyData);
@@ -851,7 +769,7 @@ var sendOpenAIResponseRequest = async ({
851
769
  });
852
770
  const currentServer = thunkApi.serverBase ?? selectRuntimeCurrentServer(getState());
853
771
  attemptLoop:
854
- for (let attempt = 0; attempt <= MAX_INITIAL_STREAM_RETRIES; attempt += 1) {
772
+ for (let attempt = 0;attempt <= MAX_INITIAL_STREAM_RETRIES; attempt += 1) {
855
773
  const response = await performFetchRequest({
856
774
  agentConfig,
857
775
  api,
@@ -861,34 +779,7 @@ var sendOpenAIResponseRequest = async ({
861
779
  token: token ?? "",
862
780
  dialogId,
863
781
  onRetry: (info) => {
864
- dispatch(
865
- messageStreaming({
866
- id: messageId,
867
- dialogId,
868
- dbKey: msgKey,
869
- content: "",
870
- role: "assistant",
871
- agentKey: agentConfig.dbKey,
872
- cybotKey: agentConfig.dbKey,
873
- ...activeMessageMetadata ?? {},
874
- isStreaming: true,
875
- retryProgress: info
876
- })
877
- );
878
- }
879
- });
880
- logQuickChatPerfStage(quickChatPerfStartedAt, "openai-response-fetch-response", {
881
- ok: response.ok,
882
- status: response.status,
883
- dialogKey
884
- });
885
- activeMessageMetadata = withImageGenerationStage(
886
- activeMessageMetadata,
887
- "generating"
888
- );
889
- if (!parentMessageId && activeMessageMetadata?.imageGenerationState) {
890
- dispatch(
891
- messageStreaming({
782
+ dispatch(messageStreaming({
892
783
  id: messageId,
893
784
  dialogId,
894
785
  dbKey: msgKey,
@@ -896,17 +787,34 @@ var sendOpenAIResponseRequest = async ({
896
787
  role: "assistant",
897
788
  agentKey: agentConfig.dbKey,
898
789
  cybotKey: agentConfig.dbKey,
899
- ...asOptionalTrimmedString(agentConfig?.name) ? { agentName: asOptionalTrimmedString(agentConfig?.name) } : {},
900
790
  ...activeMessageMetadata ?? {},
901
- isStreaming: true
902
- })
903
- );
791
+ isStreaming: true,
792
+ retryProgress: info
793
+ }));
794
+ }
795
+ });
796
+ logQuickChatPerfStage(quickChatPerfStartedAt, "openai-response-fetch-response", {
797
+ ok: response.ok,
798
+ status: response.status,
799
+ dialogKey
800
+ });
801
+ activeMessageMetadata = withImageGenerationStage(activeMessageMetadata, "generating");
802
+ if (!parentMessageId && activeMessageMetadata?.imageGenerationState) {
803
+ dispatch(messageStreaming({
804
+ id: messageId,
805
+ dialogId,
806
+ dbKey: msgKey,
807
+ content: "",
808
+ role: "assistant",
809
+ agentKey: agentConfig.dbKey,
810
+ cybotKey: agentConfig.dbKey,
811
+ ...asOptionalTrimmedString(agentConfig?.name) ? { agentName: asOptionalTrimmedString(agentConfig?.name) } : {},
812
+ ...activeMessageMetadata ?? {},
813
+ isStreaming: true
814
+ }));
904
815
  }
905
816
  if (!response.ok) {
906
- const rejectedStoredState = !!requestBody.previous_response_id && !!fallbackRequestBody && isResponsesConversationStateRejection(
907
- response.status,
908
- await response.clone().text().catch(() => "")
909
- );
817
+ const rejectedStoredState = !!requestBody.previous_response_id && !!fallbackRequestBody && isResponsesConversationStateRejection(response.status, await response.clone().text().catch(() => ""));
910
818
  if (!responsesStateFallbackUsed && rejectedStoredState) {
911
819
  responsesStateFallbackUsed = true;
912
820
  state.responsesStateFallback = true;
@@ -915,7 +823,7 @@ var sendOpenAIResponseRequest = async ({
915
823
  continue attemptLoop;
916
824
  }
917
825
  const errorMessage = await parseApiError(response);
918
- state.content = `[\u9519\u8BEF: ${errorMessage}]`;
826
+ state.content = `[错误: ${errorMessage}]`;
919
827
  state.billingFailed = true;
920
828
  await finalize();
921
829
  return buildMeta();
@@ -932,7 +840,7 @@ var sendOpenAIResponseRequest = async ({
932
840
  return buildMeta();
933
841
  }
934
842
  const parseSSE = createSSEParser();
935
- const decoder = new TextDecoder();
843
+ const decoder = new TextDecoder;
936
844
  let finishReason = null;
937
845
  let loggedFirstStreamChunk = false;
938
846
  let loggedFirstParsedEvent = false;
@@ -943,7 +851,7 @@ var sendOpenAIResponseRequest = async ({
943
851
  if (done) {
944
852
  if (canRetryInitialResponseAttempt(attempt, loggedFirstVisibleDelta, finishReason)) {
945
853
  await safeCancel(reader);
946
- reader = void 0;
854
+ reader = undefined;
947
855
  resetStateForRetry();
948
856
  await waitForInitialStreamRetry(1500, signal);
949
857
  continue attemptLoop;
@@ -956,21 +864,13 @@ var sendOpenAIResponseRequest = async ({
956
864
  }
957
865
  if (!loggedFirstStreamChunk) {
958
866
  loggedFirstStreamChunk = true;
959
- logQuickChatPerfStage(
960
- quickChatPerfStartedAt,
961
- "openai-response-first-stream-chunk",
962
- { dialogKey, byteLength: value.byteLength }
963
- );
867
+ logQuickChatPerfStage(quickChatPerfStartedAt, "openai-response-first-stream-chunk", { dialogKey, byteLength: value.byteLength });
964
868
  }
965
869
  const chunk = decoder.decode(value, { stream: true });
966
870
  const events = parseSSE(chunk);
967
871
  if (events.length > 0 && !loggedFirstParsedEvent) {
968
872
  loggedFirstParsedEvent = true;
969
- logQuickChatPerfStage(
970
- quickChatPerfStartedAt,
971
- "openai-response-first-sse-event",
972
- { dialogKey, eventCount: events.length }
973
- );
873
+ logQuickChatPerfStage(quickChatPerfStartedAt, "openai-response-first-sse-event", { dialogKey, eventCount: events.length });
974
874
  }
975
875
  const eventList = Array.isArray(events) ? events : [events];
976
876
  for (const event of eventList) {
@@ -981,7 +881,7 @@ var sendOpenAIResponseRequest = async ({
981
881
  const streamError = new Error(getStreamErrorMessage(event));
982
882
  if (canRetryInitialResponseAttempt(attempt, loggedFirstVisibleDelta, finishReason) && isRetryableInitialStreamError(streamError)) {
983
883
  await safeCancel(reader);
984
- reader = void 0;
884
+ reader = undefined;
985
885
  resetStateForRetry();
986
886
  await waitForInitialStreamRetry(1500, signal);
987
887
  continue attemptLoop;
@@ -999,11 +899,7 @@ var sendOpenAIResponseRequest = async ({
999
899
  state.contentBuffer = seg(state.content);
1000
900
  if (!loggedFirstVisibleDelta) {
1001
901
  loggedFirstVisibleDelta = true;
1002
- logQuickChatPerfStage(
1003
- quickChatPerfStartedAt,
1004
- "openai-response-first-visible-delta",
1005
- { dialogKey }
1006
- );
902
+ logQuickChatPerfStage(quickChatPerfStartedAt, "openai-response-first-visible-delta", { dialogKey });
1007
903
  }
1008
904
  flush();
1009
905
  }
@@ -1036,11 +932,7 @@ var sendOpenAIResponseRequest = async ({
1036
932
  state.contentBuffer = seg(state.content);
1037
933
  if (!loggedFirstVisibleDelta) {
1038
934
  loggedFirstVisibleDelta = true;
1039
- logQuickChatPerfStage(
1040
- quickChatPerfStartedAt,
1041
- "openai-response-first-visible-delta",
1042
- { dialogKey }
1043
- );
935
+ logQuickChatPerfStage(quickChatPerfStartedAt, "openai-response-first-visible-delta", { dialogKey });
1044
936
  }
1045
937
  flush();
1046
938
  }
@@ -1115,11 +1007,9 @@ var sendOpenAIResponseRequest = async ({
1115
1007
  }
1116
1008
  }
1117
1009
  } catch (error) {
1118
- if (canRetryInitialResponseAttempt(attempt, loggedFirstVisibleDelta, finishReason) && isRetryableInitialStreamError(
1119
- error ?? new Error("response stream ended before first visible delta")
1120
- )) {
1010
+ if (canRetryInitialResponseAttempt(attempt, loggedFirstVisibleDelta, finishReason) && isRetryableInitialStreamError(error ?? new Error("response stream ended before first visible delta"))) {
1121
1011
  await safeCancel(reader);
1122
- reader = void 0;
1012
+ reader = undefined;
1123
1013
  resetStateForRetry();
1124
1014
  await waitForInitialStreamRetry(1500, signal);
1125
1015
  continue;
@@ -1130,7 +1020,7 @@ var sendOpenAIResponseRequest = async ({
1130
1020
  return buildMeta(false, false, null);
1131
1021
  } catch (error) {
1132
1022
  const isAbort = isAbortError(error);
1133
- state.content += isAbort ? "[\u7528\u6237\u4E2D\u65AD]" : `[\u5F02\u5E38: ${error?.message || "unknown"}]`;
1023
+ state.content += isAbort ? "[用户中断]" : `[异常: ${error?.message || "unknown"}]`;
1134
1024
  state.billingFailed = isAbort ? state.billingFailed : true;
1135
1025
  state.skipBilling = state.skipBilling || shouldSkipBillingForUserAbort(error, state.usage);
1136
1026
  await finalize();
@@ -1139,14 +1029,15 @@ var sendOpenAIResponseRequest = async ({
1139
1029
  logQuickChatPerfStage(quickChatPerfStartedAt, "openai-response-stream-finished", {
1140
1030
  dialogKey
1141
1031
  });
1142
- dispatch(removeActiveController({ messageId, dialogKey }));
1032
+ dispatch(removeActiveController2({ messageId, dialogKey }));
1143
1033
  await safeCancel(reader);
1144
1034
  }
1145
1035
  };
1146
1036
 
1147
1037
  // packages/ai/agent/cleanAgentMessages.ts
1148
1038
  var isEmptyContent = (content) => {
1149
- if (content == null) return true;
1039
+ if (content == null)
1040
+ return true;
1150
1041
  if (typeof content === "string") {
1151
1042
  return content.trim().length === 0;
1152
1043
  }
@@ -1158,9 +1049,11 @@ var isEmptyContent = (content) => {
1158
1049
  var buildAgentViewMessages = (allMessages, currentAgentKey) => {
1159
1050
  const result = [];
1160
1051
  for (const msg of allMessages) {
1161
- if (!msg) continue;
1052
+ if (!msg)
1053
+ continue;
1162
1054
  const role = msg.role;
1163
- if (!role) continue;
1055
+ if (!role)
1056
+ continue;
1164
1057
  const hasToolCalls = Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0 || Array.isArray(msg.toolCalls) && msg.toolCalls.length > 0;
1165
1058
  const empty = isEmptyContent(msg.content);
1166
1059
  if (role === "assistant" && empty && !hasToolCalls) {
@@ -1183,16 +1076,16 @@ var buildAgentViewMessages = (allMessages, currentAgentKey) => {
1183
1076
  delete cloned.toolCalls;
1184
1077
  }
1185
1078
  const rawAgentName = cloned.agentName;
1186
- const agentName = rawAgentName && String(rawAgentName).trim() ? String(rawAgentName).trim() : "\u5176\u4ED6 Agent";
1079
+ const agentName = rawAgentName && String(rawAgentName).trim() ? String(rawAgentName).trim() : "其他 Agent";
1187
1080
  if (typeof cloned.content === "string") {
1188
1081
  const trimmed = cloned.content.trim();
1189
1082
  if (trimmed) {
1190
- cloned.content = `\u3010${agentName}\u3011 ${trimmed}`;
1083
+ cloned.content = `【${agentName}】 ${trimmed}`;
1191
1084
  } else {
1192
- cloned.content = `\u3010${agentName}\u3011\uFF08\u4F7F\u7528\u4E86\u5DE5\u5177\u751F\u6210\u56DE\u590D\uFF09`;
1085
+ cloned.content = `【${agentName}】(使用了工具生成回复)`;
1193
1086
  }
1194
1087
  } else {
1195
- cloned.content = `\u3010${agentName}\u3011\uFF08\u4F7F\u7528\u4E86\u5DE5\u5177\u751F\u6210\u56DE\u590D\uFF09`;
1088
+ cloned.content = `【${agentName}】(使用了工具生成回复)`;
1196
1089
  }
1197
1090
  result.push(cloned);
1198
1091
  }
@@ -1213,11 +1106,14 @@ var buildAgentViewMessages = (allMessages, currentAgentKey) => {
1213
1106
 
1214
1107
  // packages/ai/agent/requestAdmission.ts
1215
1108
  function projectSummaryHistory(messages, summary, anchor) {
1216
- if (!summary || !anchor) return messages;
1109
+ if (!summary || !anchor)
1110
+ return messages;
1217
1111
  const covered = messages.findIndex((message) => message.id === anchor);
1218
- if (covered < 0) return messages;
1112
+ if (covered < 0)
1113
+ return messages;
1219
1114
  let start = covered + 1;
1220
- while (start > 0 && messages[start]?.role === "tool") start--;
1115
+ while (start > 0 && messages[start]?.role === "tool")
1116
+ start--;
1221
1117
  const latestUser = messages.map((message) => message.role).lastIndexOf("user");
1222
1118
  const suffix = messages.slice(start);
1223
1119
  return latestUser >= 0 && latestUser < start ? [messages[latestUser], ...suffix] : suffix;
@@ -1225,9 +1121,11 @@ function projectSummaryHistory(messages, summary, anchor) {
1225
1121
  var UNKNOWN_IMAGE_RESERVE_TOKENS = 4096;
1226
1122
  function projectWireImageCosts(items) {
1227
1123
  let imageCount = 0;
1228
- if (!Array.isArray(items)) return { projected: items, imageCount };
1124
+ if (!Array.isArray(items))
1125
+ return { projected: items, imageCount };
1229
1126
  const projected = items.map((message) => {
1230
- if (!message || !Array.isArray(message.content)) return message;
1127
+ if (!message || !Array.isArray(message.content))
1128
+ return message;
1231
1129
  return { ...message, content: message.content.map((part) => {
1232
1130
  if (part?.type === "image_url" && typeof part.image_url?.url === "string") {
1233
1131
  imageCount++;
@@ -1256,12 +1154,12 @@ function estimateWebRequestBudget(body, contextWindow) {
1256
1154
  toolSchemaTokens: count(tools),
1257
1155
  otherInputTokens: count(other) + heuristicImageReserveTokens,
1258
1156
  protocolReserveTokens: 1024,
1259
- output: { semantics: "unknown", fallbackReserveTokens: cap === void 0 ? 8192 : Number(cap) }
1157
+ output: { semantics: "unknown", fallbackReserveTokens: cap === undefined ? 8192 : Number(cap) }
1260
1158
  });
1261
1159
  return { ...decision, unknownImageCount, heuristicImageReserveTokens, imageCostBasis: "unknown-provider-heuristic" };
1262
1160
  }
1263
1161
  async function admitWebRequest(options) {
1264
- for (let attempt = 0; attempt < 2; attempt++) {
1162
+ for (let attempt = 0;attempt < 2; attempt++) {
1265
1163
  if (options.signal.aborted) {
1266
1164
  const error = new Error("Request admission aborted");
1267
1165
  error.name = "AbortError";
@@ -1274,8 +1172,10 @@ async function admitWebRequest(options) {
1274
1172
  throw options.signal.reason ?? error;
1275
1173
  }
1276
1174
  const decisions = request.wireBodies.map((body) => estimateWebRequestBudget(body, options.contextWindow));
1277
- if (decisions.length && decisions.every((decision) => decision.fitsEstimate)) return request.value;
1278
- if (attempt) throw new Error("Context budget exceeded after budget_rescue; request not sent (heuristic estimate)");
1175
+ if (decisions.length && decisions.every((decision) => decision.fitsEstimate))
1176
+ return request.value;
1177
+ if (attempt)
1178
+ throw new Error("Context budget exceeded after budget_rescue; request not sent (heuristic estimate)");
1279
1179
  const allowances = request.wireBodies.map((body) => {
1280
1180
  const systemOnly = (items) => Array.isArray(items) ? items.filter((item) => item.role === "system" || item.role === "developer") : items;
1281
1181
  const external = estimateWebRequestBudget({ ...body, messages: systemOnly(body.messages), input: systemOnly(body.input) }, options.contextWindow);
@@ -1291,25 +1191,20 @@ async function persistMessageWithFixedId(dispatch, message) {
1291
1191
  dispatch(addUserMessage(message));
1292
1192
  const { controller, dialogId: _dialogId, ...messageToWrite } = message;
1293
1193
  try {
1294
- const writeRequest = dispatch(
1295
- write({
1296
- data: {
1297
- ...messageToWrite,
1298
- type: "msg" /* MSG */
1299
- },
1300
- customKey: message.dbKey
1301
- })
1302
- );
1194
+ const writeRequest = dispatch(write2({
1195
+ data: {
1196
+ ...messageToWrite,
1197
+ type: "msg" /* MSG */
1198
+ },
1199
+ customKey: message.dbKey
1200
+ }));
1303
1201
  if (writeRequest && typeof writeRequest.unwrap === "function") {
1304
1202
  await writeRequest.unwrap();
1305
1203
  return;
1306
1204
  }
1307
1205
  await writeRequest;
1308
1206
  } catch (error) {
1309
- console.error(
1310
- "[persistMessageWithFixedId] Failed to persist fixed-id message:",
1311
- error
1312
- );
1207
+ console.error("[persistMessageWithFixedId] Failed to persist fixed-id message:", error);
1313
1208
  }
1314
1209
  }
1315
1210
 
@@ -1328,10 +1223,7 @@ function buildDesktopAgentRuntimeTurnBody(args) {
1328
1223
  const continueDialogId = asTrimmedString(args.continueDialogId);
1329
1224
  let agentConfigSnapshot;
1330
1225
  if (args.agentConfigSnapshot && typeof args.agentConfigSnapshot === "object") {
1331
- const built = buildDesktopAgentRuntimeAgentConfigSnapshot(
1332
- args.agentConfigSnapshot,
1333
- args.agentRef
1334
- );
1226
+ const built = buildDesktopAgentRuntimeAgentConfigSnapshot(args.agentConfigSnapshot, args.agentRef);
1335
1227
  if (!built) {
1336
1228
  throw new Error(DESKTOP_AGENT_CONFIG_SNAPSHOT_BUILD_FAILED);
1337
1229
  }
@@ -1344,8 +1236,8 @@ function buildDesktopAgentRuntimeTurnBody(args) {
1344
1236
  dialogHistorySnapshot = buildDesktopAgentRuntimeDialogHistorySnapshot({
1345
1237
  dialogId: continueDialogId,
1346
1238
  messages: args.userMessages?.length ? args.dialogMessages.filter((message) => !args.userMessages.some((user) => user.cliMessageId === message.id)) : args.dialogMessages,
1347
- currentInput: args.userMessages?.length ? void 0 : args.input
1348
- }) ?? void 0;
1239
+ currentInput: args.userMessages?.length ? undefined : args.input
1240
+ }) ?? undefined;
1349
1241
  }
1350
1242
  const body = {
1351
1243
  agentRef: args.agentRef,
@@ -1414,11 +1306,12 @@ async function* runDesktopAgentRuntimeTurnStream({
1414
1306
  yield { type: "error", error: "Response body reader not available" };
1415
1307
  return;
1416
1308
  }
1417
- const decoder = new TextDecoder();
1309
+ const decoder = new TextDecoder;
1418
1310
  let buffer = "";
1419
1311
  const readLine = (line) => {
1420
1312
  const trimmed = line.trim();
1421
- if (!trimmed || !trimmed.startsWith("data: ")) return null;
1313
+ if (!trimmed || !trimmed.startsWith("data: "))
1314
+ return null;
1422
1315
  try {
1423
1316
  return JSON.parse(trimmed.slice(6));
1424
1317
  } catch (e) {
@@ -1439,18 +1332,22 @@ async function* runDesktopAgentRuntimeTurnStream({
1439
1332
  timeoutErrorMessage: `Desktop turn stream stalled: no event within ${noEventWatchdogMs}ms`
1440
1333
  } : {}
1441
1334
  });
1442
- if (done) break;
1335
+ if (done)
1336
+ break;
1443
1337
  buffer += decoder.decode(value, { stream: true });
1444
- const lines = buffer.split("\n");
1338
+ const lines = buffer.split(`
1339
+ `);
1445
1340
  buffer = lines.pop() || "";
1446
1341
  for (const line of lines) {
1447
- const event2 = readLine(line);
1448
- if (event2) yield event2;
1342
+ const event = readLine(line);
1343
+ if (event)
1344
+ yield event;
1449
1345
  }
1450
1346
  }
1451
1347
  buffer += decoder.decode();
1452
1348
  const event = readLine(buffer);
1453
- if (event) yield event;
1349
+ if (event)
1350
+ yield event;
1454
1351
  } catch (error) {
1455
1352
  if (isAbortError(error) || signal?.aborted) {
1456
1353
  yield { type: "error", error: "The operation was aborted." };
@@ -1463,12 +1360,10 @@ async function* runDesktopAgentRuntimeTurnStream({
1463
1360
  } finally {
1464
1361
  try {
1465
1362
  await reader.cancel();
1466
- } catch {
1467
- }
1363
+ } catch {}
1468
1364
  try {
1469
1365
  reader.releaseLock();
1470
- } catch {
1471
- }
1366
+ } catch {}
1472
1367
  }
1473
1368
  } catch (error) {
1474
1369
  if (isAbortError(error) || signal?.aborted) {
@@ -1495,46 +1390,49 @@ var buildDesktopRuntimeToolMessagesForUi = ({
1495
1390
  dialogId,
1496
1391
  turnMessages
1497
1392
  }) => {
1498
- if (!Array.isArray(turnMessages) || turnMessages.length === 0) return [];
1499
- const toolNamesByCallId = /* @__PURE__ */ new Map();
1500
- const activityByCallId = /* @__PURE__ */ new Map();
1393
+ if (!Array.isArray(turnMessages) || turnMessages.length === 0)
1394
+ return [];
1395
+ const toolNamesByCallId = new Map;
1396
+ const activityByCallId = new Map;
1501
1397
  const projected = [];
1502
1398
  for (const message of turnMessages) {
1503
1399
  if (Array.isArray(message?.tool_calls)) {
1504
1400
  for (const call of message.tool_calls) {
1505
1401
  const callId = asTrimmedString(call?.id);
1506
- const toolName2 = asTrimmedString(call?.function?.name);
1507
- if (callId && toolName2) toolNamesByCallId.set(callId, toolName2);
1402
+ const toolName = asTrimmedString(call?.function?.name);
1403
+ if (callId && toolName)
1404
+ toolNamesByCallId.set(callId, toolName);
1508
1405
  if (callId) {
1509
1406
  try {
1510
1407
  const args = typeof call?.function?.arguments === "string" ? JSON.parse(call.function.arguments) : call?.function?.arguments;
1511
- const rawActivity = isRecord(args) ? args._activity : void 0;
1512
- const activity2 = isRecord(rawActivity) ? rawActivity : void 0;
1513
- const legacyTitle = typeof activity2?.title === "string" && activity2.title.trim();
1514
- const action = activity2?.action;
1408
+ const rawActivity = isRecord(args) ? args._activity : undefined;
1409
+ const activity = isRecord(rawActivity) ? rawActivity : undefined;
1410
+ const legacyTitle = typeof activity?.title === "string" && activity.title.trim();
1411
+ const action = activity?.action;
1515
1412
  const actionTitle = isRecord(action) && typeof action.title === "string" && action.title.trim();
1516
- const plan = activity2?.plan;
1413
+ const plan = activity?.plan;
1517
1414
  const hasPlan = isRecord(plan) && Array.isArray(plan.phases) && plan.phases.some((phase) => {
1518
- if (!isRecord(phase)) return false;
1415
+ if (!isRecord(phase))
1416
+ return false;
1519
1417
  return typeof phase.title === "string" && !!phase.title.trim();
1520
1418
  });
1521
- if (activity2 && (legacyTitle || actionTitle || hasPlan)) {
1419
+ if (activity && (legacyTitle || actionTitle || hasPlan)) {
1522
1420
  activityByCallId.set(callId, args._activity);
1523
1421
  }
1524
- } catch {
1525
- }
1422
+ } catch {}
1526
1423
  }
1527
1424
  }
1528
1425
  continue;
1529
1426
  }
1530
- if (message?.role !== "tool") continue;
1427
+ if (message?.role !== "tool")
1428
+ continue;
1531
1429
  const toolCallId = asTrimmedString(message.tool_call_id);
1532
1430
  const metadata = asRecordOrEmpty(message.tool_result_metadata);
1533
1431
  const metadataToolName = asTrimmedString(metadata.toolName);
1534
1432
  const toolName = metadataToolName || (toolCallId ? toolNamesByCallId.get(toolCallId) : "") || "tool";
1535
- const { key: dbKey, messageId } = createDialogMessageKeyAndId(dialogId);
1536
- const resultActivity = metadata.activity && typeof metadata.activity === "object" ? metadata.activity : void 0;
1537
- const callActivity = toolCallId ? activityByCallId.get(toolCallId) : void 0;
1433
+ const { key: dbKey, messageId } = createDialogMessageKeyAndId2(dialogId);
1434
+ const resultActivity = metadata.activity && typeof metadata.activity === "object" ? metadata.activity : undefined;
1435
+ const callActivity = toolCallId ? activityByCallId.get(toolCallId) : undefined;
1538
1436
  const activity = resultActivity || callActivity;
1539
1437
  const mergedMetadata = activity ? { ...metadata, activity } : metadata;
1540
1438
  projected.push({
@@ -1557,23 +1455,28 @@ var buildDesktopRuntimeToolMessagesForUi = ({
1557
1455
  };
1558
1456
  var toolMessageWillPersist = (toolMsg) => {
1559
1457
  const content = toolMsg?.content;
1560
- if (typeof content === "string") return content.trim().length > 0;
1458
+ if (typeof content === "string")
1459
+ return content.trim().length > 0;
1561
1460
  return Array.isArray(content) && content.length > 0;
1562
1461
  };
1563
1462
  var shouldUseDesktopLocalRuntime = (agentConfig, explicitTarget) => {
1564
- if (explicitTarget?.kind === "machine") return false;
1565
- if (!getIsDesktopApp()) return false;
1463
+ if (explicitTarget?.kind === "machine")
1464
+ return false;
1465
+ if (!getIsDesktopApp())
1466
+ return false;
1566
1467
  return agentConfig?.apiSource !== "cli";
1567
1468
  };
1568
1469
  var readCurrentDesktopMachineId = () => {
1569
1470
  const fromProcess = typeof process !== "undefined" ? (process.env?.NOLO_CURRENT_MACHINE_ID || process.env?.NOLO_MACHINE_ID || "").trim() : "";
1570
- if (fromProcess) return fromProcess;
1471
+ if (fromProcess)
1472
+ return fromProcess;
1571
1473
  const w = typeof globalThis !== "undefined" && globalThis.window ? globalThis.window : null;
1572
1474
  const fromWindow = asTrimmedString(w?.__NOLO_CURRENT_MACHINE_ID__) || asTrimmedString(w?.__NOLO_MACHINE_ID__);
1573
1475
  return fromWindow;
1574
1476
  };
1575
1477
  var resolveRemoteBoundMachineId = (machineId) => {
1576
- if (!machineId || !getIsDesktopApp()) return machineId;
1478
+ if (!machineId || !getIsDesktopApp())
1479
+ return machineId;
1577
1480
  const currentMachineId = readCurrentDesktopMachineId();
1578
1481
  return currentMachineId && currentMachineId === machineId ? "" : machineId;
1579
1482
  };
@@ -1606,23 +1509,24 @@ var formatMachineAgentRunError = async (response) => {
1606
1509
  const reason = typeof payload?.reason === "string" ? payload.reason : "";
1607
1510
  if (response.status === 409) {
1608
1511
  if (reason === "bound_machine_unavailable") {
1609
- return "\u7ED1\u5B9A\u7684\u7535\u8111\u4E0D\u5728\u7EBF\u3002\u8BF7\u786E\u8BA4\u8FD9\u53F0\u7535\u8111\u5DF2\u5F00\u673A\u5E76\u91CD\u65B0\u8FD0\u884C\u8FDE\u63A5\u547D\u4EE4\u3002";
1512
+ return "绑定的电脑不在线。请确认这台电脑已开机并重新运行连接命令。";
1610
1513
  }
1611
1514
  if (reason === "bound_machine_owner_mismatch") {
1612
- return "\u8FD9\u53F0\u7535\u8111\u662F\u5728\u7EBF\u7684\uFF0C\u4F46\u5F53\u524D\u8D26\u53F7\u548C Agent \u7ED1\u5B9A\u8D26\u53F7\u4E0D\u4E00\u81F4\u3002\u8BF7\u91CD\u65B0\u7ED1\u5B9A Agent\uFF0C\u6216\u5728\u7ED1\u5B9A\u8D26\u53F7\u4E0B\u91CD\u65B0\u8FDE\u63A5\u8FD9\u53F0\u7535\u8111\u3002";
1515
+ return "这台电脑是在线的,但当前账号和 Agent 绑定账号不一致。请重新绑定 Agent,或在绑定账号下重新连接这台电脑。";
1613
1516
  }
1614
1517
  if (reason === "connector_offline") {
1615
- return "\u7535\u8111\u5728\u7EBF\uFF0C\u4F46\u8FDE\u63A5\u5668\u672A\u8FDE\u63A5\u3002\u8BF7\u5728\u8FD9\u53F0\u7535\u8111\u4E0A\u91CD\u65B0\u8FD0\u884C\u8FDE\u63A5\u547D\u4EE4\u540E\u518D\u8BD5\u3002";
1518
+ return "电脑在线,但连接器未连接。请在这台电脑上重新运行连接命令后再试。";
1616
1519
  }
1617
1520
  if (reason === "missing_capability") {
1618
- return "\u8FD9\u53F0\u7535\u8111\u6CA1\u6709\u5BF9\u5E94\u7684 CLI \u80FD\u529B\u3002\u8BF7\u5B89\u88C5\u5BF9\u5E94 CLI\uFF0C\u6216\u628A Agent \u7ED1\u5B9A\u5230\u53E6\u4E00\u53F0\u7535\u8111\u3002";
1521
+ return "这台电脑没有对应的 CLI 能力。请安装对应 CLI,或把 Agent 绑定到另一台电脑。";
1619
1522
  }
1620
1523
  }
1621
1524
  const message = asOptionalTrimmedString(payload?.message) ?? asOptionalTrimmedString(payload?.error) ?? errorText.trim();
1622
1525
  return message || `Machine agent run failed (${response.status})`;
1623
1526
  };
1624
1527
  var normalizeThreadMetadataPatch = (value) => {
1625
- if (!isRecord(value)) return null;
1528
+ if (!isRecord(value))
1529
+ return null;
1626
1530
  const record = value;
1627
1531
  const changes = {};
1628
1532
  const threadKind = asOptionalTrimmedString(record.threadKind);
@@ -1637,40 +1541,43 @@ var normalizeThreadMetadataPatch = (value) => {
1637
1541
  };
1638
1542
  var patchDialogThreadMetadata = async (dispatch, dialogKey, metadata) => {
1639
1543
  const changes = normalizeThreadMetadataPatch(metadata);
1640
- if (!changes) return;
1641
- await dispatch(
1642
- patch({
1643
- dbKey: dialogKey,
1644
- changes
1645
- })
1646
- ).unwrap?.();
1544
+ if (!changes)
1545
+ return;
1546
+ await dispatch(patch2({
1547
+ dbKey: dialogKey,
1548
+ changes
1549
+ })).unwrap?.();
1647
1550
  };
1648
1551
  var patchDialogActiveAgent = async (dispatch, dialogKey, agentKey) => {
1649
- if (typeof agentKey !== "string" || !agentKey.trim()) return;
1650
- await dispatch(
1651
- patch({
1652
- dbKey: dialogKey,
1653
- changes: {
1654
- primaryAgentKey: agentKey.trim()
1655
- }
1656
- })
1657
- ).unwrap?.();
1552
+ if (typeof agentKey !== "string" || !agentKey.trim())
1553
+ return;
1554
+ await dispatch(patch2({
1555
+ dbKey: dialogKey,
1556
+ changes: {
1557
+ primaryAgentKey: agentKey.trim()
1558
+ }
1559
+ })).unwrap?.();
1658
1560
  };
1659
1561
  function appendCliCapabilityWarnings(content, warnings) {
1660
- if (!warnings.length) return content;
1562
+ if (!warnings.length)
1563
+ return content;
1661
1564
  const warningBlock = `
1662
1565
 
1663
- [CLI \u80FD\u529B\u63D0\u793A]
1664
- ${warnings.map((warning) => `- ${warning}`).join("\n")}`;
1566
+ [CLI 能力提示]
1567
+ ${warnings.map((warning) => `- ${warning}`).join(`
1568
+ `)}`;
1665
1569
  return `${content}${warningBlock}`;
1666
1570
  }
1667
1571
 
1668
1572
  // packages/ai/chat/wireAdapters/resolveChatWire.ts
1669
1573
  function resolveChatWire(agentOrInput) {
1670
- if (!agentOrInput) return "completions";
1574
+ if (!agentOrInput)
1575
+ return "completions";
1671
1576
  const { provider, model, endpointKey, cliProvider, customProviderUrl, endpoint } = agentOrInput;
1672
- if (cliProvider === "codex") return "codex";
1673
- if (cliProvider === "claude") return "anthropic";
1577
+ if (cliProvider === "codex")
1578
+ return "codex";
1579
+ if (cliProvider === "claude")
1580
+ return "anthropic";
1674
1581
  const responsesUrlPattern = /\/responses(?:[/?#]|$)/;
1675
1582
  if (endpointKey === "responses" || endpoint && responsesUrlPattern.test(endpoint) || customProviderUrl && responsesUrlPattern.test(customProviderUrl)) {
1676
1583
  return "responses";
@@ -1684,13 +1591,12 @@ function resolveChatWire(agentOrInput) {
1684
1591
  }
1685
1592
  return "completions";
1686
1593
  }
1687
-
1688
1594
  // packages/ai/llm/isResponseAPIModel.ts
1689
1595
  var isResponseAPIModel = (agentConfig) => resolveChatWire(agentConfig) === "responses";
1690
1596
 
1691
1597
  // packages/ai/agent/streamTurnQuickChat.ts
1692
1598
  var QUICK_CHAT_AGENT_CONFIG_READ_TIMEOUT_MS = 1e4;
1693
- var QUICK_CHAT_DYNAMIC_CONTEXT_TIMEOUT_MS = 5e3;
1599
+ var QUICK_CHAT_DYNAMIC_CONTEXT_TIMEOUT_MS = 5000;
1694
1600
  var EMPTY_DYNAMIC_CONTEXTS = {
1695
1601
  currentInputContext: null,
1696
1602
  historyContext: "",
@@ -1701,7 +1607,8 @@ var EMPTY_DYNAMIC_CONTEXTS = {
1701
1607
  referenceKeys: []
1702
1608
  };
1703
1609
  var logQuickChatPerfStage2 = (startedAt, stage, details = {}) => {
1704
- if (!startedAt) return;
1610
+ if (!startedAt)
1611
+ return;
1705
1612
  const now = typeof performance !== "undefined" ? performance.now() : Date.now();
1706
1613
  console.info("[QuickChatPerf]", {
1707
1614
  stage,
@@ -1711,165 +1618,149 @@ var logQuickChatPerfStage2 = (startedAt, stage, details = {}) => {
1711
1618
  });
1712
1619
  };
1713
1620
  var readAgentConfigForTurn = async (dispatch, agentKey, quickChatPerfStartedAt) => {
1714
- const readPromise = dispatch(read({ dbKey: agentKey })).unwrap();
1715
- if (!quickChatPerfStartedAt) return readPromise;
1621
+ const readPromise = dispatch(read2({ dbKey: agentKey })).unwrap();
1622
+ if (!quickChatPerfStartedAt)
1623
+ return readPromise;
1716
1624
  let timeoutId;
1717
1625
  try {
1718
1626
  return await Promise.race([
1719
1627
  readPromise,
1720
1628
  new Promise((_, reject) => {
1721
1629
  timeoutId = setTimeout(() => {
1722
- logQuickChatPerfStage2(
1723
- quickChatPerfStartedAt,
1724
- "quick-chat-agent-config-read-timeout",
1725
- { agentKey, timeoutMs: QUICK_CHAT_AGENT_CONFIG_READ_TIMEOUT_MS }
1726
- );
1727
- reject(
1728
- new Error("\u8BFB\u53D6 Agent \u914D\u7F6E\u8D85\u65F6\uFF0C\u672A\u80FD\u542F\u52A8\u6A21\u578B\u56DE\u590D\u3002")
1729
- );
1630
+ logQuickChatPerfStage2(quickChatPerfStartedAt, "quick-chat-agent-config-read-timeout", { agentKey, timeoutMs: QUICK_CHAT_AGENT_CONFIG_READ_TIMEOUT_MS });
1631
+ reject(new Error("读取 Agent 配置超时,未能启动模型回复。"));
1730
1632
  }, QUICK_CHAT_AGENT_CONFIG_READ_TIMEOUT_MS);
1731
1633
  })
1732
1634
  ]);
1733
1635
  } finally {
1734
- if (timeoutId) clearTimeout(timeoutId);
1636
+ if (timeoutId)
1637
+ clearTimeout(timeoutId);
1735
1638
  }
1736
1639
  };
1737
1640
  var buildDynamicContextsForTurn = async (state, dispatch, agentConfig, userInput, runtimeOptions, mergedContentCache, dialogKey, quickChatPerfStartedAt, serverBase) => {
1738
1641
  if (!quickChatPerfStartedAt) {
1739
- return buildDynamicContexts(
1740
- state,
1741
- dispatch,
1742
- agentConfig,
1743
- userInput,
1744
- runtimeOptions,
1745
- mergedContentCache,
1746
- dialogKey,
1747
- serverBase
1748
- );
1642
+ return buildDynamicContexts(state, dispatch, agentConfig, userInput, runtimeOptions, mergedContentCache, dialogKey, serverBase);
1749
1643
  }
1750
1644
  let timeoutId;
1751
1645
  try {
1752
1646
  const timeoutPromise = new Promise((resolve) => {
1753
1647
  timeoutId = setTimeout(() => {
1754
- logQuickChatPerfStage2(
1755
- quickChatPerfStartedAt,
1756
- "quick-chat-dynamic-context-timeout",
1757
- { agentKey: agentConfig.dbKey, dialogKey, timeoutMs: QUICK_CHAT_DYNAMIC_CONTEXT_TIMEOUT_MS }
1758
- );
1648
+ logQuickChatPerfStage2(quickChatPerfStartedAt, "quick-chat-dynamic-context-timeout", { agentKey: agentConfig.dbKey, dialogKey, timeoutMs: QUICK_CHAT_DYNAMIC_CONTEXT_TIMEOUT_MS });
1759
1649
  resolve(EMPTY_DYNAMIC_CONTEXTS);
1760
1650
  }, QUICK_CHAT_DYNAMIC_CONTEXT_TIMEOUT_MS);
1761
1651
  });
1762
- logQuickChatPerfStage2(
1763
- quickChatPerfStartedAt,
1764
- "stream-agent-dynamic-context-starting",
1765
- { responseApi: isResponseAPIModel(agentConfig) }
1766
- );
1767
- const contextPromise = buildDynamicContexts(
1768
- state,
1769
- dispatch,
1770
- agentConfig,
1771
- userInput,
1772
- runtimeOptions,
1773
- mergedContentCache,
1774
- dialogKey,
1775
- serverBase
1776
- );
1652
+ logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-dynamic-context-starting", { responseApi: isResponseAPIModel(agentConfig) });
1653
+ const contextPromise = buildDynamicContexts(state, dispatch, agentConfig, userInput, runtimeOptions, mergedContentCache, dialogKey, serverBase);
1777
1654
  return await Promise.race([
1778
1655
  contextPromise,
1779
1656
  timeoutPromise
1780
1657
  ]);
1781
1658
  } finally {
1782
- if (timeoutId) clearTimeout(timeoutId);
1659
+ if (timeoutId)
1660
+ clearTimeout(timeoutId);
1783
1661
  }
1784
1662
  };
1785
1663
  var finalizeQuickChatAgentTurnFailure = async (dispatch, dialogKey, agentKey, error) => {
1786
1664
  const dialogId = extractCustomId(dialogKey);
1787
- const { key: msgKey, messageId } = createDialogMessageKeyAndId(dialogId);
1788
- const reason = error instanceof Error && error.message.trim() ? error.message.trim() : typeof error === "string" && error.trim() ? error.trim() : error && typeof error === "object" && typeof error.message === "string" && error.message.trim() ? error.message.trim() : "\u672A\u80FD\u542F\u52A8\u6A21\u578B\u56DE\u590D\uFF0C\u8BF7\u91CD\u8BD5\u3002";
1789
- await dispatch(
1790
- messageStreamEnd({
1791
- finalContentBuffer: [
1792
- { type: "text", text: `[\u9519\u8BEF: ${reason}]` }
1793
- ],
1794
- totalUsage: null,
1795
- msgKey,
1796
- agentConfig: { dbKey: agentKey },
1797
- dialogId,
1798
- dialogKey,
1799
- messageId,
1800
- reasoningBuffer: ""
1801
- })
1802
- ).unwrap?.();
1665
+ const { key: msgKey, messageId } = createDialogMessageKeyAndId2(dialogId);
1666
+ const reason = error instanceof Error && error.message.trim() ? error.message.trim() : typeof error === "string" && error.trim() ? error.trim() : error && typeof error === "object" && typeof error.message === "string" && error.message.trim() ? error.message.trim() : "未能启动模型回复,请重试。";
1667
+ await dispatch(messageStreamEnd({
1668
+ finalContentBuffer: [
1669
+ { type: "text", text: `[错误: ${reason}]` }
1670
+ ],
1671
+ totalUsage: null,
1672
+ msgKey,
1673
+ agentConfig: { dbKey: agentKey },
1674
+ dialogId,
1675
+ dialogKey,
1676
+ messageId,
1677
+ reasoningBuffer: ""
1678
+ })).unwrap?.();
1803
1679
  };
1804
1680
  var normalizeAgentRunUserInput = (userInput) => {
1805
- if (typeof userInput === "string") return userInput;
1806
- if (!Array.isArray(userInput)) return "";
1681
+ if (typeof userInput === "string")
1682
+ return userInput;
1683
+ if (!Array.isArray(userInput))
1684
+ return "";
1807
1685
  return userInput.flatMap((part) => projectUserPartForModel(part));
1808
1686
  };
1809
1687
  var isSimpleTextInput = (userInput) => {
1810
- if (typeof userInput === "string") return true;
1811
- if (!Array.isArray(userInput)) return false;
1812
- return userInput.every(
1813
- (part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string"
1814
- );
1688
+ if (typeof userInput === "string")
1689
+ return true;
1690
+ if (!Array.isArray(userInput))
1691
+ return false;
1692
+ return userInput.every((part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string");
1815
1693
  };
1816
1694
  var canUseQuickChatEmptyDynamicContexts = (quickChatPerfStartedAt, userInput, runtimeOptions, dialogConfig, agentConfig) => {
1817
- if (!quickChatPerfStartedAt) return false;
1818
- if (runtimeOptions) return false;
1819
- if (agentConfig?.tools?.includes("rememberMemory")) return false;
1820
- if (!isSimpleTextInput(userInput)) return false;
1821
- if (dialogConfig?.referenceKeys?.length) return false;
1695
+ if (!quickChatPerfStartedAt)
1696
+ return false;
1697
+ if (runtimeOptions)
1698
+ return false;
1699
+ if (agentConfig?.tools?.includes("rememberMemory"))
1700
+ return false;
1701
+ if (!isSimpleTextInput(userInput))
1702
+ return false;
1703
+ if (dialogConfig?.referenceKeys?.length)
1704
+ return false;
1822
1705
  return true;
1823
1706
  };
1824
1707
  var QUICK_CHAT_DIRECT_ANSWER_PATTERN = /(只回复|只输出|只回答|直接回复|直接回答|不要解释|无需解释|不用解释|简短回答|一句话)/i;
1825
1708
  var QUICK_CHAT_TOOL_INTENT_PATTERN = /(调用|转交|agent|助手|应用|网页|页面|图表|图片|生成图|画图|删除|清理|空间|商品|链接|https?:\/\/|www\.|@)/i;
1826
1709
  var shouldDisableQuickChatToolsForDirectAnswer = (quickChatPerfStartedAt, userInput, runtimeOptions, dialogConfig) => {
1827
- if (!canUseQuickChatEmptyDynamicContexts(
1828
- quickChatPerfStartedAt,
1829
- userInput,
1830
- runtimeOptions,
1831
- dialogConfig,
1832
- void 0
1833
- )) {
1710
+ if (!canUseQuickChatEmptyDynamicContexts(quickChatPerfStartedAt, userInput, runtimeOptions, dialogConfig, undefined)) {
1834
1711
  return false;
1835
1712
  }
1836
1713
  const text = extractAgentRunUserText(userInput);
1837
- if (!text || text.length > 500) return false;
1838
- if (!QUICK_CHAT_DIRECT_ANSWER_PATTERN.test(text)) return false;
1714
+ if (!text || text.length > 500)
1715
+ return false;
1716
+ if (!QUICK_CHAT_DIRECT_ANSWER_PATTERN.test(text))
1717
+ return false;
1839
1718
  return !QUICK_CHAT_TOOL_INTENT_PATTERN.test(text);
1840
1719
  };
1841
1720
  var classifyQuickChatAccessError = (accessError) => {
1842
- if (accessError.includes("\u83B7\u53D6\u7528\u6237\u4F59\u989D")) return "balance-loading";
1843
- if (accessError.includes("\u4F59\u989D")) return "balance";
1844
- if (accessError.includes("\u767D\u540D\u5355")) return "whitelist";
1845
- if (accessError.includes("\u5B9A\u4EF7")) return "pricing";
1721
+ if (accessError.includes("获取用户余额"))
1722
+ return "balance-loading";
1723
+ if (accessError.includes("余额"))
1724
+ return "balance";
1725
+ if (accessError.includes("白名单"))
1726
+ return "whitelist";
1727
+ if (accessError.includes("定价"))
1728
+ return "pricing";
1846
1729
  return "unknown";
1847
1730
  };
1848
1731
  var isUsableAgentConfig = (value) => !!value && typeof value === "object" && value.__ssrPreviewOnly !== true && typeof value.dbKey === "string" && !!value.dbKey && typeof value.model === "string" && !!value.model && typeof value.provider === "string" && !!value.provider;
1849
1732
  var extractAgentRunUserText = (userInput) => {
1850
- if (typeof userInput === "string") return userInput.trim();
1851
- if (!Array.isArray(userInput)) return "";
1733
+ if (typeof userInput === "string")
1734
+ return userInput.trim();
1735
+ if (!Array.isArray(userInput))
1736
+ return "";
1852
1737
  return userInput.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join("").trim();
1853
1738
  };
1854
1739
  var hasAgentRunUserInputContent = (userInput) => {
1855
- if (typeof userInput === "string") return userInput.trim().length > 0;
1740
+ if (typeof userInput === "string")
1741
+ return userInput.trim().length > 0;
1856
1742
  return Array.isArray(userInput) && userInput.length > 0;
1857
1743
  };
1858
1744
  var isLastMessageMatchingUserInput = (visibleMessages, userInput) => {
1859
- if (visibleMessages.length === 0) return false;
1745
+ if (visibleMessages.length === 0)
1746
+ return false;
1860
1747
  const lastMsg = visibleMessages[visibleMessages.length - 1];
1861
- if (lastMsg.role !== "user") return false;
1748
+ if (lastMsg.role !== "user")
1749
+ return false;
1862
1750
  const content1 = lastMsg.content;
1863
1751
  const content2 = userInput;
1864
1752
  const normalize = (content) => {
1865
- if (typeof content === "string") return content.trim();
1753
+ if (typeof content === "string")
1754
+ return content.trim();
1866
1755
  if (Array.isArray(content)) {
1867
1756
  if (content.length === 1 && content[0]?.type === "text") {
1868
1757
  return (content[0].text || "").trim();
1869
1758
  }
1870
1759
  return content.map((part) => {
1871
- if (part?.type === "text") return { type: "text", text: part.text?.trim() };
1872
- if (part?.type === "image_url") return { type: "image_url", url: part.image_url?.url };
1760
+ if (part?.type === "text")
1761
+ return { type: "text", text: part.text?.trim() };
1762
+ if (part?.type === "image_url")
1763
+ return { type: "image_url", url: part.image_url?.url };
1873
1764
  return part;
1874
1765
  });
1875
1766
  }
@@ -1884,25 +1775,20 @@ var isLastMessageMatchingUserInput = (visibleMessages, userInput) => {
1884
1775
  };
1885
1776
  var setLoopStopReason = (reason) => {
1886
1777
  const w = typeof globalThis !== "undefined" && globalThis.window ? globalThis.window : null;
1887
- if (w) w.__LOOP_STOP_REASON__ = reason;
1778
+ if (w)
1779
+ w.__LOOP_STOP_REASON__ = reason;
1888
1780
  };
1889
1781
  var prewarmPreparedToolsForAgent = (agentConfig) => {
1890
1782
  const tools = agentConfig?.tools;
1891
- if (!Array.isArray(tools) || tools.length === 0) return;
1783
+ if (!Array.isArray(tools) || tools.length === 0)
1784
+ return;
1892
1785
  try {
1893
1786
  prepareTools(tools, { provider: agentConfig.provider });
1894
- } catch {
1895
- }
1787
+ } catch {}
1896
1788
  };
1897
1789
  var buildStaticContextsWithToolsPrewarm = async (state, dispatch, agentConfig, currentDialog, mergedContentCache) => {
1898
1790
  const [staticContexts] = await Promise.all([
1899
- buildStaticContexts(
1900
- state,
1901
- dispatch,
1902
- agentConfig,
1903
- currentDialog ?? void 0,
1904
- mergedContentCache
1905
- ),
1791
+ buildStaticContexts(state, dispatch, agentConfig, currentDialog ?? undefined, mergedContentCache),
1906
1792
  Promise.resolve().then(() => prewarmPreparedToolsForAgent(agentConfig))
1907
1793
  ]);
1908
1794
  return staticContexts;
@@ -1914,39 +1800,41 @@ function hasInlineExecutedToolCalls(result) {
1914
1800
  return Array.isArray(output) && output.some((b) => b?.type === "toolCall" && b?.result != null);
1915
1801
  }
1916
1802
  var COMPACTION_TIMEOUT_PATTERN = /compaction[^\n]{0,40}(timed\s*out|timeout|deadline)|(timed\s*out|timeout|deadline)[^\n]{0,40}compaction|summary[^\n]{0,30}(timed\s*out|timeout)/i;
1917
- var DESKTOP_SSE_NO_EVENT_WATCHDOG_MS = 20 * 60 * 1e3;
1803
+ var DESKTOP_SSE_NO_EVENT_WATCHDOG_MS = 20 * 60 * 1000;
1918
1804
  function classifyLocalTurnStreamError(errorText) {
1919
1805
  const text = typeof errorText === "string" ? errorText : "";
1920
1806
  if (COMPACTION_TIMEOUT_PATTERN.test(text)) {
1921
1807
  return {
1922
1808
  kind: "compaction_timeout",
1923
1809
  retryable: true,
1924
- summary: "\u5386\u53F2\u538B\u7F29\u8D85\u65F6",
1925
- actionHint: "\u5386\u53F2\u538B\u7F29\u672A\u80FD\u5728\u65F6\u9650\u5185\u5B8C\u6210\uFF0C\u672C\u56DE\u5408\u5DF2\u505C\u6B62\u3002\u4F60\u7684\u6D88\u606F\u4E0E\u9644\u4EF6\u5747\u5DF2\u4FDD\u7559\uFF1B\u53EF\u91CD\u8BD5\u3001\u5F00\u542F\u65B0\u5BF9\u8BDD\uFF0C\u6216\u5207\u6362\u5230\u66F4\u5927\u7A97\u53E3\u7684\u6A21\u578B\u3002\uFF08\u8D85\u65F6\u540E\u4E0D\u4F1A\u81EA\u52A8\u91CD\u8BD5\u540C\u4E00\u4ED8\u8D39\u8BF7\u6C42\u3002\uFF09"
1810
+ summary: "历史压缩超时",
1811
+ actionHint: "历史压缩未能在时限内完成,本回合已停止。你的消息与附件均已保留;可重试、开启新对话,或切换到更大窗口的模型。(超时后不会自动重试同一付费请求。)"
1926
1812
  };
1927
1813
  }
1928
1814
  if (isContextOverflowText(text)) {
1929
1815
  return {
1930
1816
  kind: "context_overflow",
1931
1817
  retryable: true,
1932
- summary: "\u4E0A\u4E0B\u6587\u8FC7\u957F",
1933
- actionHint: "\u5F53\u524D\u4E0A\u4E0B\u6587\u8D85\u51FA\u6A21\u578B\u7A97\u53E3\u3002\u53EF\u81EA\u52A8\u538B\u7F29\u5E76\u91CD\u8BD5\u3001\u5F00\u542F\u65B0\u5BF9\u8BDD\uFF0C\u6216\u5207\u6362\u5230\u66F4\u5927\u7A97\u53E3\u7684\u6A21\u578B\u3002"
1818
+ summary: "上下文过长",
1819
+ actionHint: "当前上下文超出模型窗口。可自动压缩并重试、开启新对话,或切换到更大窗口的模型。"
1934
1820
  };
1935
1821
  }
1936
1822
  return { kind: "generic", retryable: true, summary: "", actionHint: "" };
1937
1823
  }
1938
1824
  function createRemoteToolEventHandlers(opts) {
1939
1825
  const { dialogId, dialogKey, dispatch, messageMetadata } = opts;
1940
- const activeToolMessages = /* @__PURE__ */ new Map();
1826
+ const activeToolMessages = new Map;
1941
1827
  const handleToolPayload = (payload) => {
1942
- if (!payload || typeof payload !== "object") return;
1828
+ if (!payload || typeof payload !== "object")
1829
+ return;
1943
1830
  if (payload.type === "assistant_tool_calls") {
1944
1831
  const toolCalls = Array.isArray(payload.tool_calls) ? payload.tool_calls : [];
1945
1832
  for (const tc of toolCalls) {
1946
1833
  const callId = tc?.id;
1947
1834
  const toolName = tc?.function?.name;
1948
- if (!callId || !toolName) continue;
1949
- const { key: toolDbKey, messageId: toolMsgId } = createDialogMessageKeyAndId(dialogId);
1835
+ if (!callId || !toolName)
1836
+ continue;
1837
+ const { key: toolDbKey, messageId: toolMsgId } = createDialogMessageKeyAndId2(dialogId);
1950
1838
  const argsStr = typeof tc.function?.arguments === "string" ? tc.function.arguments : "";
1951
1839
  const toolMsg = {
1952
1840
  id: toolMsgId,
@@ -1973,15 +1861,16 @@ function createRemoteToolEventHandlers(opts) {
1973
1861
  }
1974
1862
  if (payload.type === "tool_result") {
1975
1863
  const callId = payload.toolCallId;
1976
- if (!callId) return;
1864
+ if (!callId)
1865
+ return;
1977
1866
  const existing = activeToolMessages.get(callId);
1978
1867
  const toolName = asOptionalTrimmedString(payload.toolName) || asOptionalTrimmedString(existing?.toolName) || "tool";
1979
- const mergedMeta = isRecord(payload.metadata) ? payload.metadata : void 0;
1868
+ const mergedMeta = isRecord(payload.metadata) ? payload.metadata : undefined;
1980
1869
  const isToolError = !!mergedMeta?.error;
1981
1870
  const projectedContent = projectDesktopToolUiContent({
1982
1871
  toolName,
1983
1872
  content: payload.content,
1984
- metadata: mergedMeta ?? void 0
1873
+ metadata: mergedMeta ?? undefined
1985
1874
  });
1986
1875
  const resultStatus = isToolError ? "failed" : "succeeded";
1987
1876
  if (!isToolError) {
@@ -1993,8 +1882,6 @@ function createRemoteToolEventHandlers(opts) {
1993
1882
  isStreaming: false,
1994
1883
  content: projectedContent,
1995
1884
  toolName,
1996
- // F1: keep server-projected metadata (incl. executionLocation)
1997
- // on the message so tool rows can render the actual host.
1998
1885
  ...mergedMeta ? { metadata: mergedMeta } : {},
1999
1886
  toolPayload: {
2000
1887
  ...existing.toolPayload ?? {},
@@ -2005,7 +1892,7 @@ function createRemoteToolEventHandlers(opts) {
2005
1892
  activeToolMessages.set(callId, updatedMsg);
2006
1893
  dispatch(messageStreaming(updatedMsg));
2007
1894
  } else {
2008
- const { key: toolDbKey, messageId: toolMsgId } = createDialogMessageKeyAndId(dialogId);
1895
+ const { key: toolDbKey, messageId: toolMsgId } = createDialogMessageKeyAndId2(dialogId);
2009
1896
  const toolMsg = {
2010
1897
  id: toolMsgId,
2011
1898
  dialogId,
@@ -2015,8 +1902,6 @@ function createRemoteToolEventHandlers(opts) {
2015
1902
  isStreaming: false,
2016
1903
  toolName,
2017
1904
  toolCallId: callId,
2018
- // F1: surface executionLocation (and any other server metadata)
2019
- // even on the no-prior-call fallback path.
2020
1905
  ...mergedMeta ? { metadata: mergedMeta } : {},
2021
1906
  toolPayload: {
2022
1907
  toolName,
@@ -2053,34 +1938,37 @@ async function persistRemoteToolMessagesAndCleanup(dispatch, activeToolMessages)
2053
1938
  activeToolMessages.clear();
2054
1939
  }
2055
1940
  function safeParseToolArgs(argsStr) {
2056
- if (!argsStr) return {};
1941
+ if (!argsStr)
1942
+ return {};
2057
1943
  try {
2058
1944
  return JSON.parse(argsStr);
2059
1945
  } catch {
2060
1946
  return { raw: argsStr };
2061
1947
  }
2062
1948
  }
2063
- var notifiedOmittedImageUserMessageIds = /* @__PURE__ */ new Set();
1949
+ var notifiedOmittedImageUserMessageIds = new Set;
2064
1950
  function notifyOmittedImagesIfPresent({
2065
1951
  downgraded,
2066
1952
  messagesBeforeStrip,
2067
1953
  targetUserMessageId
2068
1954
  }) {
2069
- if (!downgraded || !targetUserMessageId) return;
2070
- if (notifiedOmittedImageUserMessageIds.has(targetUserMessageId)) return;
1955
+ if (!downgraded || !targetUserMessageId)
1956
+ return;
1957
+ if (notifiedOmittedImageUserMessageIds.has(targetUserMessageId))
1958
+ return;
2071
1959
  const targetMsg = messagesBeforeStrip.find((m) => m.id === targetUserMessageId);
2072
- if (!targetMsg) return;
1960
+ if (!targetMsg)
1961
+ return;
2073
1962
  const currentMessageImageCount = extractImageUrlsFromMessages([targetMsg]).length;
2074
- if (currentMessageImageCount <= 0) return;
1963
+ if (currentMessageImageCount <= 0)
1964
+ return;
2075
1965
  notifiedOmittedImageUserMessageIds.add(targetUserMessageId);
2076
- if (notifiedOmittedImageUserMessageIds.size > 1e3) {
1966
+ if (notifiedOmittedImageUserMessageIds.size > 1000) {
2077
1967
  const first = notifiedOmittedImageUserMessageIds.values().next().value;
2078
- if (first) notifiedOmittedImageUserMessageIds.delete(first);
1968
+ if (first)
1969
+ notifiedOmittedImageUserMessageIds.delete(first);
2079
1970
  }
2080
- toast.info(
2081
- `\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u56FE\u7247\uFF0C\u672C\u6B21\u53D1\u9001\u7684 ${currentMessageImageCount} \u5F20\u56FE\u7247\u5DF2\u7701\u7565\uFF0C\u6587\u5B57\u4ECD\u4F1A\u53D1\u9001\u3002`,
2082
- { id: `image-omitted-${targetUserMessageId}` }
2083
- );
1971
+ toast.info(`当前模型不支持图片,本次发送的 ${currentMessageImageCount} 张图片已省略,文字仍会发送。`, { id: `image-omitted-${targetUserMessageId}` });
2084
1972
  }
2085
1973
  var streamAgentChatTurnHandler = async (args, thunkApi) => {
2086
1974
  const {
@@ -2102,22 +1990,22 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2102
1990
  const serverBase = currentServer;
2103
1991
  const runtimeOptions = requestedRuntimeOptions && Object.freeze({ ...requestedRuntimeOptions });
2104
1992
  const turnThunkApi = { ...thunkApi, accountPolicy, serverBase, runtimeServers };
2105
- const loopController = new AbortController();
1993
+ const loopController = new AbortController;
2106
1994
  const isTurnAborted = (error) => isAbortError(error) || loopController.signal.aborted || thunkApi.signal.aborted;
2107
1995
  const onAbort = () => loopController.abort();
2108
1996
  thunkApi.signal.addEventListener("abort", onAbort);
2109
1997
  let loopKey = null;
2110
1998
  let runtimeDialogKey = explicitDialogKey ?? null;
2111
1999
  let turnPhaseTurnId = null;
2112
- const secretGateTurnId = createDialogMessageKeyAndId("secret-gate").messageId;
2113
- const secretGateAnchors = /* @__PURE__ */ new Set();
2000
+ const secretGateTurnId = createDialogMessageKeyAndId2("secret-gate").messageId;
2001
+ const secretGateAnchors = new Set;
2114
2002
  const receiveActionGate = (gate, target, dialogId) => {
2115
2003
  const secret = gate.kind === "input" && gate.payload?.action === "secret_request";
2116
2004
  if (!secret || target?.kind === "local") {
2117
2005
  pushGate(gate, target);
2118
2006
  return;
2119
2007
  }
2120
- const { messageId, key } = createDialogMessageKeyAndId(dialogId);
2008
+ const { messageId, key } = createDialogMessageKeyAndId2(dialogId);
2121
2009
  secretGateAnchors.add(messageId);
2122
2010
  pushGate(gate, target, { dialogId, turnId: secretGateTurnId, messageId });
2123
2011
  dispatch(messageStreaming({
@@ -2132,19 +2020,21 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2132
2020
  };
2133
2021
  const batchExecution = createUserBatchExecution(loopController.signal, () => !thunkApi.signal.aborted && (!turnPhaseTurnId || !runtimeDialogKey || getDialogRuntimeState(runtimeDialogKey).turnPhaseTurnId === turnPhaseTurnId));
2134
2022
  const workMemoryUserMessageId = (dialogId, activeId) => {
2135
- if (!activeId) return void 0;
2023
+ if (!activeId)
2024
+ return;
2136
2025
  const users = selectAllMsgs(getState(), dialogId).filter((message) => message.role === "user");
2137
2026
  const bound = users.find((message) => message.id === activeId);
2138
- if (!bound || bound.metadata?.queueState === "pending") return void 0;
2027
+ if (!bound || bound.metadata?.queueState === "pending")
2028
+ return;
2139
2029
  const receipt = bound.metadata?.userBatchReceipt;
2140
2030
  if (receipt) {
2141
2031
  const ids = receipt.messageIds;
2142
- return Array.isArray(ids) && ids.length === 1 && ids[0] === activeId ? activeId : void 0;
2032
+ return Array.isArray(ids) && ids.length === 1 && ids[0] === activeId ? activeId : undefined;
2143
2033
  }
2144
2034
  const batchId = bound.metadata?.acceptedUserBatchId;
2145
2035
  if (batchId) {
2146
2036
  const batch = users.filter((message) => message.metadata?.acceptedUserBatchId === batchId);
2147
- return batch.length === 1 && batch[0]?.id === activeId ? activeId : void 0;
2037
+ return batch.length === 1 && batch[0]?.id === activeId ? activeId : undefined;
2148
2038
  }
2149
2039
  return activeId;
2150
2040
  };
@@ -2155,15 +2045,9 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2155
2045
  if (explicitDialogKey) {
2156
2046
  const dialogId = extractCustomId(explicitDialogKey);
2157
2047
  const existingLoopKey = `loop:${dialogId}`;
2158
- const activeControllers = selectActiveControllers(
2159
- getState(),
2160
- explicitDialogKey
2161
- );
2048
+ const activeControllers = selectActiveControllers2(getState(), explicitDialogKey);
2162
2049
  if (activeControllers[existingLoopKey]) {
2163
- console.warn(
2164
- "[streamAgentChatTurn] Rejected concurrent turn for dialog",
2165
- { dialogId, agentKey }
2166
- );
2050
+ console.warn("[streamAgentChatTurn] Rejected concurrent turn for dialog", { dialogId, agentKey });
2167
2051
  return rejectWithValue("Agent is already responding for this dialog");
2168
2052
  }
2169
2053
  }
@@ -2174,10 +2058,7 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2174
2058
  agentKey,
2175
2059
  dialogKey: explicitDialogKey ?? null
2176
2060
  });
2177
- const cachedAgentConfig = selectById(
2178
- getState(),
2179
- agentKey
2180
- );
2061
+ const cachedAgentConfig = selectById2(getState(), agentKey);
2181
2062
  let rawAgentConfig = null;
2182
2063
  let agentConfigSource;
2183
2064
  if (isUsableAgentConfig(providedAgentConfig)) {
@@ -2187,15 +2068,9 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2187
2068
  rawAgentConfig = applyPlatformAgentOverrides(cachedAgentConfig, agentKey);
2188
2069
  agentConfigSource = "cache";
2189
2070
  } else {
2190
- const builtinFallback = resolveBuiltinPlatformAgentRecord(
2191
- agentKey
2192
- );
2071
+ const builtinFallback = resolveBuiltinPlatformAgentRecord(agentKey);
2193
2072
  try {
2194
- const readConfig = await readAgentConfigForTurn(
2195
- dispatch,
2196
- agentKey,
2197
- quickChatPerfStartedAt
2198
- );
2073
+ const readConfig = await readAgentConfigForTurn(dispatch, agentKey, quickChatPerfStartedAt);
2199
2074
  if (isUsableAgentConfig(readConfig)) {
2200
2075
  rawAgentConfig = applyPlatformAgentOverrides(readConfig, agentKey);
2201
2076
  agentConfigSource = "read";
@@ -2204,29 +2079,20 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2204
2079
  agentConfigSource = builtinFallback ? "builtin-unusable-record" : "read";
2205
2080
  }
2206
2081
  } catch (error) {
2207
- if (isTurnAborted(error) || !builtinFallback) throw error;
2208
- console.warn(
2209
- "[streamAgentChatTurn] Agent record unavailable; using builtin platform config",
2210
- { agentKey, error: toErrorMessage(error) }
2211
- );
2082
+ if (isTurnAborted(error) || !builtinFallback)
2083
+ throw error;
2084
+ console.warn("[streamAgentChatTurn] Agent record unavailable; using builtin platform config", { agentKey, error: toErrorMessage(error) });
2212
2085
  rawAgentConfig = builtinFallback;
2213
2086
  agentConfigSource = "builtin-read-failed";
2214
2087
  }
2215
2088
  }
2216
2089
  if (!rawAgentConfig) {
2217
- return rejectWithValue(
2218
- `Agent config not found for ID: ${agentKey}`
2219
- );
2090
+ return rejectWithValue(`Agent config not found for ID: ${agentKey}`);
2220
2091
  }
2221
2092
  if (isLiveAudioOnlyAgent(rawAgentConfig)) {
2222
- return rejectWithValue(
2223
- "\u6B64 Agent \u4EC5\u652F\u6301\u5B9E\u65F6\u8BED\u97F3\u6A21\u5F0F\uFF0C\u8BF7\u4F7F\u7528\u8BED\u97F3\u9762\u677F\u8FDB\u884C\u5BF9\u8BDD\u3002"
2224
- );
2093
+ return rejectWithValue("此 Agent 仅支持实时语音模式,请使用语音面板进行对话。");
2225
2094
  }
2226
- const agentConfig = resolveWebAgentRuntimeToolSurface(
2227
- rawAgentConfig,
2228
- getState()
2229
- );
2095
+ const agentConfig = resolveWebAgentRuntimeToolSurface(rawAgentConfig, getState());
2230
2096
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-config-read", {
2231
2097
  agentKey,
2232
2098
  model: agentConfig.model,
@@ -2246,86 +2112,78 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2246
2112
  if (gptProCheck.blocked) {
2247
2113
  return rejectWithValue(gptProCheck.message);
2248
2114
  }
2249
- const configuredBoundMachineId = asTrimmedString(
2250
- agentConfig.runtimeBinding?.machineId
2251
- );
2252
- const currentDialog = selectDialogConfigByKey(state, explicitDialogKey) ?? selectCurrentDialogConfig(state);
2253
- const explicitTarget = runtimeOptions?.runtimeTarget ?? (currentDialog?.runtimeBinding?.target?.kind === "server" || currentDialog?.runtimeBinding?.target?.kind === "machine" ? currentDialog.runtimeBinding.target : void 0);
2115
+ const configuredBoundMachineId = asTrimmedString(agentConfig.runtimeBinding?.machineId);
2116
+ const currentDialog = selectDialogConfigByKey2(state, explicitDialogKey) ?? selectCurrentDialogConfig2(state);
2117
+ const explicitTarget = runtimeOptions?.runtimeTarget ?? (currentDialog?.runtimeBinding?.target?.kind === "server" || currentDialog?.runtimeBinding?.target?.kind === "machine" ? currentDialog.runtimeBinding.target : undefined);
2254
2118
  const boundMachineId = explicitTarget ? explicitTarget.kind === "machine" ? asTrimmedString(explicitTarget.machineId) : null : resolveRemoteBoundMachineId(configuredBoundMachineId);
2255
2119
  const hasExplicitMachineTarget = explicitTarget?.kind === "machine";
2256
2120
  if (hasExplicitMachineTarget && !boundMachineId) {
2257
- return rejectWithValue("\u663E\u5F0F\u9009\u62E9\u7684\u7535\u8111\u76EE\u6807\u7F3A\u5C11 machineId\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u6267\u884C\u7535\u8111\u3002");
2121
+ return rejectWithValue("显式选择的电脑目标缺少 machineId,请重新选择执行电脑。");
2258
2122
  }
2259
- if (hasExplicitMachineTarget || agentConfig.apiSource === "cli" && !explicitTarget || boundMachineId && !getIsDesktopApp()) {
2260
- console.info("[streamAgentChatTurn] Triggered CLI/machine route. apiSource:", agentConfig.apiSource, "boundMachineId:", boundMachineId, "agentKey:", agentKey);
2123
+ const isCliAgent = resolveAgentProviderMode(agentConfig) === "cli";
2124
+ if (hasExplicitMachineTarget || isCliAgent && !explicitTarget || boundMachineId && !getIsDesktopApp()) {
2125
+ console.info("[streamAgentChatTurn] Triggered CLI/machine route. apiSource:", agentConfig.apiSource, "cliProvider:", agentConfig.cliProvider, "boundMachineId:", boundMachineId, "agentKey:", agentKey);
2261
2126
  const currentState = getState();
2262
- const w2 = typeof globalThis !== "undefined" && globalThis.window ? globalThis.window : null;
2263
- if (w2) w2.__LOOP_STOP_REASON__ = null;
2127
+ const w = typeof globalThis !== "undefined" && globalThis.window ? globalThis.window : null;
2128
+ if (w)
2129
+ w.__LOOP_STOP_REASON__ = null;
2264
2130
  const userText = extractAgentRunUserText(userInput);
2265
- const prompt = buildCliPrompt(
2266
- [agentConfig.prompt, ...contextBlocks ?? []].filter((part) => typeof part === "string" && part.trim().length > 0).join("\n\n"),
2267
- userText
2268
- );
2269
- const dialogConfig = selectDialogConfigByKey(currentState, explicitDialogKey) ?? selectCurrentDialogConfig(currentState);
2131
+ const prompt = buildCliPrompt([agentConfig.prompt, ...contextBlocks ?? []].filter((part) => typeof part === "string" && part.trim().length > 0).join(`
2132
+
2133
+ `), userText);
2134
+ const dialogConfig = selectDialogConfigByKey2(currentState, explicitDialogKey) ?? selectCurrentDialogConfig2(currentState);
2270
2135
  if (!dialogConfig) {
2271
2136
  return rejectWithValue("Dialog config not found");
2272
2137
  }
2273
- const dialogKey2 = explicitDialogKey || dialogConfig.dbKey;
2274
- if (!dialogKey2) {
2275
- return rejectWithValue("\u5F53\u524D\u5BF9\u8BDD\u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F\u3002");
2138
+ const dialogKey = explicitDialogKey || dialogConfig.dbKey;
2139
+ if (!dialogKey) {
2140
+ return rejectWithValue("当前对话不存在,无法发送消息。");
2276
2141
  }
2277
- runtimeDialogKey = dialogKey2;
2278
- const dialogId2 = extractCustomId(dialogKey2);
2279
- loopKey = `loop:${dialogId2}`;
2280
- dispatch(addActiveController({ messageId: loopKey, controller: loopController, dialogKey: dialogKey2 }));
2281
- const { key: msgKey, messageId } = createDialogMessageKeyAndId(dialogId2);
2142
+ runtimeDialogKey = dialogKey;
2143
+ const dialogId = extractCustomId(dialogKey);
2144
+ loopKey = `loop:${dialogId}`;
2145
+ dispatch(addActiveController2({ messageId: loopKey, controller: loopController, dialogKey }));
2146
+ const { key: msgKey, messageId } = createDialogMessageKeyAndId2(dialogId);
2282
2147
  const cliMessageMetadata = buildMessageMetadata(agentConfig);
2283
2148
  if (boundMachineId) {
2284
2149
  const token = selectIdentityToken(currentState);
2285
2150
  const authHeader = token ? `Bearer ${token}` : "";
2286
- const rawMessages = selectAdmittedMessages(selectAllMsgs(currentState, dialogId2));
2287
- const visibleMessages = buildAgentViewMessages(
2288
- rawMessages,
2289
- agentConfig.dbKey
2290
- );
2151
+ const rawMessages = selectAdmittedMessages(selectAllMsgs(currentState, dialogId));
2152
+ const visibleMessages = buildAgentViewMessages(rawMessages, agentConfig.dbKey);
2291
2153
  const cleanedMessages = filterAndCleanMessages(visibleMessages);
2292
2154
  remoteTransientMessageId = messageId;
2293
- let accumulated2 = "";
2294
- let totalTurnUsage2 = void 0;
2155
+ let accumulated = "";
2156
+ let totalTurnUsage = undefined;
2295
2157
  const buildMachineAssistantMessage = () => ({
2296
- dialogId: dialogId2,
2158
+ dialogId,
2297
2159
  id: messageId,
2298
2160
  dbKey: msgKey,
2299
2161
  role: "assistant",
2300
- content: accumulated2,
2162
+ content: accumulated,
2301
2163
  ...cliMessageMetadata,
2302
2164
  userId: selectIdentityUserId(getState())
2303
2165
  });
2304
2166
  const remoteToolHandlers = createRemoteToolEventHandlers({
2305
- dialogKey: dialogKey2,
2306
- dialogId: dialogId2,
2167
+ dialogKey,
2168
+ dialogId,
2307
2169
  dispatch,
2308
2170
  messageMetadata: cliMessageMetadata
2309
2171
  });
2310
2172
  dispatch(messageStreaming({
2311
2173
  id: messageId,
2312
- dialogId: dialogId2,
2174
+ dialogId,
2313
2175
  dbKey: msgKey,
2314
2176
  content: "",
2315
2177
  role: "assistant",
2316
2178
  ...cliMessageMetadata
2317
2179
  }));
2318
2180
  const rejectMachineStream = async (message) => {
2319
- if (accumulated2.length > 0) {
2181
+ if (accumulated.length > 0) {
2320
2182
  await persistMessageWithFixedId(dispatch, buildMachineAssistantMessage());
2321
2183
  } else {
2322
2184
  dispatch(removeTransientMessage(messageId));
2323
2185
  }
2324
- await persistRemoteToolMessagesAndCleanup(
2325
- dispatch,
2326
- remoteToolHandlers.activeToolMessages
2327
- ).catch(() => {
2328
- });
2186
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages).catch(() => {});
2329
2187
  setLoopStopReason("error");
2330
2188
  remoteTransientMessageFinalized = true;
2331
2189
  return rejectWithValue(message);
@@ -2344,7 +2202,7 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2344
2202
  messages: serializeAgentRunMessages(cleanedMessages),
2345
2203
  stream: true,
2346
2204
  persistDialog: true,
2347
- continueDialogId: dialogId2,
2205
+ continueDialogId: dialogId,
2348
2206
  ...explicitTarget ? { runtimeTarget: explicitTarget } : {},
2349
2207
  runtimeContext: {
2350
2208
  surface: "web",
@@ -2359,37 +2217,28 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2359
2217
  signal: loopController.signal
2360
2218
  });
2361
2219
  if (!machineResponse.ok) {
2362
- return await rejectMachineStream(
2363
- await formatMachineAgentRunError(machineResponse)
2364
- );
2220
+ return await rejectMachineStream(await formatMachineAgentRunError(machineResponse));
2365
2221
  }
2366
- const reader2 = machineResponse.body?.getReader();
2367
- if (!reader2) {
2368
- return await rejectMachineStream("\u65E0\u6CD5\u8BFB\u53D6\u7535\u8111\u7AEF Agent \u6D41\u5F0F\u54CD\u5E94");
2222
+ const reader = machineResponse.body?.getReader();
2223
+ if (!reader) {
2224
+ return await rejectMachineStream("无法读取电脑端 Agent 流式响应");
2369
2225
  }
2370
- const decoder2 = new TextDecoder();
2226
+ const decoder = new TextDecoder;
2371
2227
  const parseSSE = createSSEParser();
2372
2228
  const abortMachineStream = async () => {
2373
- if (w2) w2.__LOOP_STOP_REASON__ = "aborted";
2374
- if (accumulated2.length <= 0) {
2375
- await persistRemoteToolMessagesAndCleanup(
2376
- dispatch,
2377
- remoteToolHandlers.activeToolMessages
2378
- ).catch(() => {
2379
- });
2229
+ if (w)
2230
+ w.__LOOP_STOP_REASON__ = "aborted";
2231
+ if (accumulated.length <= 0) {
2232
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages).catch(() => {});
2380
2233
  return;
2381
2234
  }
2382
2235
  await persistMessageWithFixedId(dispatch, buildMachineAssistantMessage());
2383
- await persistRemoteToolMessagesAndCleanup(
2384
- dispatch,
2385
- remoteToolHandlers.activeToolMessages
2386
- ).catch(() => {
2387
- });
2236
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages).catch(() => {});
2388
2237
  };
2389
2238
  try {
2390
2239
  const result = await consumeAgentRunStream({
2391
- reader: reader2,
2392
- decoder: decoder2,
2240
+ reader,
2241
+ decoder,
2393
2242
  parseChunk: (raw) => parseSSE(raw),
2394
2243
  isAborted: () => loopController.signal.aborted || thunkApi.signal.aborted,
2395
2244
  signal: loopController.signal,
@@ -2397,32 +2246,28 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2397
2246
  isDoneEvent: (payload) => payload?.type === "done",
2398
2247
  onPayload: (payload) => {
2399
2248
  if (payload.type === "error") {
2400
- return { reject: payload.message || "\u7535\u8111\u7AEF Agent \u6267\u884C\u5931\u8D25" };
2249
+ return { reject: payload.message || "电脑端 Agent 执行失败" };
2401
2250
  }
2402
2251
  if (payload.type === "action_gate" && payload.gate) {
2403
- receiveActionGate(
2404
- payload.gate,
2405
- targetForRunKind("server-run", {
2406
- server: currentServer,
2407
- token
2408
- }),
2409
- dialogId2
2410
- );
2252
+ receiveActionGate(payload.gate, targetForRunKind("server-run", {
2253
+ server: currentServer,
2254
+ token
2255
+ }), dialogId);
2411
2256
  }
2412
2257
  remoteToolHandlers.handleToolPayload(payload);
2413
2258
  if ((payload.type === "text" || payload.type === "text_replace") && typeof payload.content === "string") {
2414
- accumulated2 = payload.type === "text_replace" ? payload.content : accumulated2 + payload.content;
2259
+ accumulated = payload.type === "text_replace" ? payload.content : accumulated + payload.content;
2415
2260
  dispatch(messageStreaming({
2416
2261
  id: messageId,
2417
- dialogId: dialogId2,
2262
+ dialogId,
2418
2263
  dbKey: msgKey,
2419
- content: accumulated2,
2264
+ content: accumulated,
2420
2265
  role: "assistant",
2421
2266
  ...cliMessageMetadata
2422
2267
  }));
2423
2268
  }
2424
2269
  if (payload.type === "done") {
2425
- totalTurnUsage2 = payload.usage;
2270
+ totalTurnUsage = payload.usage;
2426
2271
  }
2427
2272
  }
2428
2273
  });
@@ -2436,47 +2281,33 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2436
2281
  if (!result.sawDone) {
2437
2282
  dispatch(finalizeTransientMessageOnError({
2438
2283
  id: messageId,
2439
- error: "\u7535\u8111\u7AEF Agent \u6D41\u5F0F\u54CD\u5E94\u88AB\u4E2D\u65AD,\u672A\u6536\u5230\u5B8C\u6210\u4FE1\u53F7"
2284
+ error: "电脑端 Agent 流式响应被中断,未收到完成信号"
2440
2285
  }));
2441
- await persistRemoteToolMessagesAndCleanup(
2442
- dispatch,
2443
- remoteToolHandlers.activeToolMessages
2444
- ).catch(() => {
2445
- });
2286
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages).catch(() => {});
2446
2287
  remoteTransientMessageFinalized = true;
2447
2288
  setLoopStopReason("error");
2448
- return rejectWithValue(
2449
- "\u7535\u8111\u7AEF Agent \u6D41\u5F0F\u54CD\u5E94\u88AB\u4E2D\u65AD,\u672A\u6536\u5230\u5B8C\u6210\u4FE1\u53F7"
2450
- );
2289
+ return rejectWithValue("电脑端 Agent 流式响应被中断,未收到完成信号");
2451
2290
  }
2452
2291
  await persistMessageWithFixedId(dispatch, buildMachineAssistantMessage());
2453
- await persistRemoteToolMessagesAndCleanup(
2454
- dispatch,
2455
- remoteToolHandlers.activeToolMessages
2456
- );
2292
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages);
2457
2293
  remoteTransientMessageFinalized = true;
2458
2294
  }
2459
2295
  } finally {
2460
2296
  try {
2461
- await reader2.cancel();
2462
- } catch {
2463
- }
2297
+ await reader.cancel();
2298
+ } catch {}
2464
2299
  if (remoteToolHandlers.activeToolMessages.size > 0) {
2465
- await persistRemoteToolMessagesAndCleanup(
2466
- dispatch,
2467
- remoteToolHandlers.activeToolMessages
2468
- ).catch(() => {
2469
- });
2300
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages).catch(() => {});
2470
2301
  }
2471
2302
  }
2472
2303
  return {
2473
- usage: totalTurnUsage2 ?? void 0
2304
+ usage: totalTurnUsage ?? undefined
2474
2305
  };
2475
2306
  }
2476
2307
  let cliSessionId = dialogConfig.cliSessionId ?? null;
2477
2308
  dispatch(messageStreaming({
2478
2309
  id: messageId,
2479
- dialogId: dialogId2,
2310
+ dialogId,
2480
2311
  dbKey: msgKey,
2481
2312
  content: "",
2482
2313
  role: "assistant",
@@ -2485,82 +2316,65 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2485
2316
  remoteTransientMessageId = messageId;
2486
2317
  const ensureCliSession = async () => {
2487
2318
  if (cliSessionId) {
2488
- const existing = await getCliChatSession(
2489
- { getState },
2490
- { sessionId: cliSessionId }
2491
- ).catch(() => null);
2319
+ const existing = await getCliChatSession({ getState }, { sessionId: cliSessionId }).catch(() => null);
2492
2320
  if (existing?.ok && existing?.session?.sessionId) {
2493
2321
  return cliSessionId;
2494
2322
  }
2495
2323
  }
2496
- const started = await startCliChatSession(
2497
- { getState },
2498
- {
2499
- cliProvider: agentConfig.cliProvider || "copilot",
2500
- model: agentConfig.model || void 0,
2501
- systemPrompt: agentConfig.prompt || void 0,
2502
- reasoningEffort: agentConfig.reasoning_effort || agentConfig.reasoningEffort || void 0,
2503
- temperature: agentConfig.temperature,
2504
- topP: agentConfig.top_p,
2505
- frequencyPenalty: agentConfig.frequency_penalty,
2506
- presencePenalty: agentConfig.presence_penalty,
2507
- maxTokens: agentConfig.max_tokens,
2508
- enableThinking: agentConfig.enableThinking,
2509
- thinkingBudget: agentConfig.thinkingBudget
2510
- }
2511
- );
2324
+ const started = await startCliChatSession({ getState }, {
2325
+ cliProvider: agentConfig.cliProvider || "copilot",
2326
+ model: agentConfig.model || undefined,
2327
+ systemPrompt: agentConfig.prompt || undefined,
2328
+ reasoningEffort: agentConfig.reasoning_effort || agentConfig.reasoningEffort || undefined,
2329
+ temperature: agentConfig.temperature,
2330
+ topP: agentConfig.top_p,
2331
+ frequencyPenalty: agentConfig.frequency_penalty,
2332
+ presencePenalty: agentConfig.presence_penalty,
2333
+ maxTokens: agentConfig.max_tokens,
2334
+ enableThinking: agentConfig.enableThinking,
2335
+ thinkingBudget: agentConfig.thinkingBudget
2336
+ });
2512
2337
  const newSessionId = typeof started?.sessionId === "string" ? started.sessionId : null;
2513
2338
  if (!newSessionId) {
2514
- throw new Error("\u65E0\u6CD5\u521B\u5EFA CLI session\u3002");
2339
+ throw new Error("无法创建 CLI session。");
2515
2340
  }
2516
2341
  cliSessionId = newSessionId;
2517
- const patchResult = dispatch(
2518
- patch({
2519
- dbKey: dialogKey2,
2520
- changes: {
2521
- cliSessionId: newSessionId
2522
- }
2523
- })
2524
- );
2342
+ const patchResult = dispatch(patch2({
2343
+ dbKey: dialogKey,
2344
+ changes: {
2345
+ cliSessionId: newSessionId
2346
+ }
2347
+ }));
2525
2348
  try {
2526
2349
  if (typeof patchResult?.unwrap === "function") {
2527
2350
  await patchResult.unwrap();
2528
2351
  } else {
2529
2352
  await patchResult;
2530
2353
  }
2531
- } catch {
2532
- }
2354
+ } catch {}
2533
2355
  return newSessionId;
2534
2356
  };
2535
2357
  const initialSessionId = await ensureCliSession();
2536
2358
  console.info("[streamAgentChatTurn] Calling CLI turn stream. Session ID:", initialSessionId);
2537
- let resp = await createCliChatTurnStream(
2538
- {
2539
- getState
2540
- },
2541
- {
2542
- sessionId: initialSessionId,
2543
- prompt,
2544
- model: agentConfig.model || void 0
2545
- },
2546
- loopController.signal
2547
- );
2359
+ let resp = await createCliChatTurnStream({
2360
+ getState
2361
+ }, {
2362
+ sessionId: initialSessionId,
2363
+ prompt,
2364
+ model: agentConfig.model || undefined
2365
+ }, loopController.signal);
2548
2366
  if (!resp.ok && resp.status === 404) {
2549
2367
  console.warn("[streamAgentChatTurn] CLI Session 404. Re-creating session...");
2550
2368
  cliSessionId = null;
2551
2369
  const renewedSessionId = await ensureCliSession();
2552
2370
  console.info("[streamAgentChatTurn] Retrying CLI turn stream. Session ID:", renewedSessionId);
2553
- resp = await createCliChatTurnStream(
2554
- {
2555
- getState
2556
- },
2557
- {
2558
- sessionId: renewedSessionId,
2559
- prompt,
2560
- model: agentConfig.model || void 0
2561
- },
2562
- loopController.signal
2563
- );
2371
+ resp = await createCliChatTurnStream({
2372
+ getState
2373
+ }, {
2374
+ sessionId: renewedSessionId,
2375
+ prompt,
2376
+ model: agentConfig.model || undefined
2377
+ }, loopController.signal);
2564
2378
  }
2565
2379
  if (!resp.ok) {
2566
2380
  const err = await resp.json().catch(() => ({ error: resp.statusText }));
@@ -2568,25 +2382,27 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2568
2382
  dispatch(removeTransientMessage(messageId));
2569
2383
  setLoopStopReason("error");
2570
2384
  remoteTransientMessageFinalized = true;
2571
- return rejectWithValue(err.error || "CLI \u6267\u884C\u5931\u8D25");
2385
+ return rejectWithValue(err.error || "CLI 执行失败");
2572
2386
  }
2573
2387
  const reader = resp.body?.getReader();
2574
2388
  if (!reader) {
2575
2389
  dispatch(removeTransientMessage(messageId));
2576
2390
  setLoopStopReason("error");
2577
2391
  remoteTransientMessageFinalized = true;
2578
- return rejectWithValue("\u65E0\u6CD5\u8BFB\u53D6\u6D41\u5F0F\u54CD\u5E94");
2392
+ return rejectWithValue("无法读取流式响应");
2579
2393
  }
2580
2394
  let accumulated = "";
2395
+ let accumulatedThought = "";
2581
2396
  let cliCapabilityWarnings = [];
2582
2397
  let cliTurnUsage = null;
2583
- const decoder = new TextDecoder();
2398
+ const decoder = new TextDecoder;
2584
2399
  const buildCliAssistantMessage = () => ({
2585
- dialogId: dialogId2,
2400
+ dialogId,
2586
2401
  id: messageId,
2587
2402
  dbKey: msgKey,
2588
- role: "assistant",
2589
2403
  content: accumulated,
2404
+ ...accumulatedThought ? { thinkContent: accumulatedThought } : {},
2405
+ role: "assistant",
2590
2406
  ...cliMessageMetadata,
2591
2407
  userId: selectIdentityUserId(getState())
2592
2408
  });
@@ -2601,7 +2417,8 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2601
2417
  return rejectWithValue(message);
2602
2418
  };
2603
2419
  const abortCliStream = async () => {
2604
- if (w2) w2.__LOOP_STOP_REASON__ = "aborted";
2420
+ if (w)
2421
+ w.__LOOP_STOP_REASON__ = "aborted";
2605
2422
  if (accumulated.length <= 0) {
2606
2423
  return;
2607
2424
  }
@@ -2613,12 +2430,13 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2613
2430
  decoder,
2614
2431
  parseChunk: (raw) => {
2615
2432
  const parsed = [];
2616
- for (const line of raw.split("\n")) {
2617
- if (!line.startsWith("data: ")) continue;
2433
+ for (const line of raw.split(`
2434
+ `)) {
2435
+ if (!line.startsWith("data: "))
2436
+ continue;
2618
2437
  try {
2619
2438
  parsed.push(JSON.parse(line.slice(6)));
2620
- } catch {
2621
- }
2439
+ } catch {}
2622
2440
  }
2623
2441
  return parsed;
2624
2442
  },
@@ -2630,21 +2448,32 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2630
2448
  if (payload.error) {
2631
2449
  return { reject: payload.error };
2632
2450
  }
2451
+ if (typeof payload.thought === "string" && payload.thought.length > 0) {
2452
+ accumulatedThought += payload.thought;
2453
+ dispatch(messageStreaming({
2454
+ id: messageId,
2455
+ dialogId,
2456
+ dbKey: msgKey,
2457
+ content: accumulated,
2458
+ thinkContent: accumulatedThought,
2459
+ role: "assistant",
2460
+ ...cliMessageMetadata
2461
+ }));
2462
+ }
2633
2463
  if (payload.chunk) {
2634
2464
  accumulated += payload.chunk;
2635
2465
  dispatch(messageStreaming({
2636
2466
  id: messageId,
2637
- dialogId: dialogId2,
2467
+ dialogId,
2638
2468
  dbKey: msgKey,
2639
2469
  content: accumulated,
2470
+ ...accumulatedThought ? { thinkContent: accumulatedThought } : {},
2640
2471
  role: "assistant",
2641
2472
  ...cliMessageMetadata
2642
2473
  }));
2643
2474
  }
2644
2475
  if (payload.done && Array.isArray(payload.warnings)) {
2645
- cliCapabilityWarnings = payload.warnings.filter(
2646
- (warning) => typeof warning === "string" && warning.trim().length > 0
2647
- );
2476
+ cliCapabilityWarnings = payload.warnings.filter((warning) => typeof warning === "string" && warning.trim().length > 0);
2648
2477
  }
2649
2478
  if (payload.done && payload.usage) {
2650
2479
  cliTurnUsage = updateTotalUsage(cliTurnUsage, payload.usage);
@@ -2661,17 +2490,17 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2661
2490
  if (!result.sawDone) {
2662
2491
  dispatch(finalizeTransientMessageOnError({
2663
2492
  id: messageId,
2664
- error: "CLI \u6D41\u5F0F\u54CD\u5E94\u88AB\u4E2D\u65AD,\u672A\u6536\u5230\u5B8C\u6210\u4FE1\u53F7"
2493
+ error: "CLI 流式响应被中断,未收到完成信号"
2665
2494
  }));
2666
2495
  remoteTransientMessageFinalized = true;
2667
2496
  setLoopStopReason("error");
2668
- return rejectWithValue("CLI \u6D41\u5F0F\u54CD\u5E94\u88AB\u4E2D\u65AD,\u672A\u6536\u5230\u5B8C\u6210\u4FE1\u53F7");
2497
+ return rejectWithValue("CLI 流式响应被中断,未收到完成信号");
2669
2498
  }
2670
2499
  if (cliCapabilityWarnings.length > 0) {
2671
2500
  accumulated = appendCliCapabilityWarnings(accumulated, cliCapabilityWarnings);
2672
2501
  dispatch(messageStreaming({
2673
2502
  id: messageId,
2674
- dialogId: dialogId2,
2503
+ dialogId,
2675
2504
  dbKey: msgKey,
2676
2505
  content: accumulated,
2677
2506
  role: "assistant",
@@ -2684,11 +2513,11 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2684
2513
  const hasRealUsage = !!cliUsageRaw && (cliUsageRaw.prompt_tokens ?? cliUsageRaw.input_tokens ?? 0) + (cliUsageRaw.completion_tokens ?? cliUsageRaw.output_tokens ?? 0) + (cliUsageRaw.cache_creation_input_tokens ?? 0) + (cliUsageRaw.cache_read_input_tokens ?? 0) > 0;
2685
2514
  const isCliEstimated = !hasRealUsage;
2686
2515
  const cliUsage = hasRealUsage ? cliUsageRaw : estimateMissingUsage({ content: accumulated });
2687
- if (dialogKey2) {
2516
+ if (dialogKey) {
2688
2517
  try {
2689
- await dispatch(updateTokens({
2690
- dialogId: dialogId2,
2691
- dialogKey: dialogKey2,
2518
+ await dispatch(updateTokens2({
2519
+ dialogId,
2520
+ dialogKey,
2692
2521
  usage: cliUsage,
2693
2522
  contextUsageAuthoritative: !isCliEstimated,
2694
2523
  agentConfig: isCliEstimated ? { ...agentConfig, apiSource: "cli" } : agentConfig
@@ -2701,15 +2530,14 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2701
2530
  } finally {
2702
2531
  try {
2703
2532
  await reader.cancel();
2704
- } catch {
2705
- }
2533
+ } catch {}
2706
2534
  }
2707
2535
  return;
2708
2536
  }
2709
2537
  const activeDialogKey = currentDialog?.dbKey;
2710
2538
  const dialogKey = explicitDialogKey || activeDialogKey;
2711
2539
  if (!dialogKey) {
2712
- return rejectWithValue("\u5F53\u524D\u5BF9\u8BDD\u4E0D\u5B58\u5728\uFF0C\u65E0\u6CD5\u53D1\u9001\u6D88\u606F\u3002");
2540
+ return rejectWithValue("当前对话不存在,无法发送消息。");
2713
2541
  }
2714
2542
  runtimeDialogKey = dialogKey;
2715
2543
  const dialogId = extractCustomId(dialogKey);
@@ -2721,14 +2549,15 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2721
2549
  claimDialogTurnPhase({ dialogKey, turnId: turnPhaseTurnId });
2722
2550
  if (shouldUseDesktopLocalRuntime(agentConfig, explicitTarget)) {
2723
2551
  const desktopMessageMetadata = buildMessageMetadata(agentConfig);
2724
- const w2 = typeof globalThis !== "undefined" && globalThis.window ? globalThis.window : null;
2552
+ const w = typeof globalThis !== "undefined" && globalThis.window ? globalThis.window : null;
2725
2553
  loopKey = `loop:${dialogId}`;
2726
- dispatch(addActiveController({ messageId: loopKey, controller: loopController, dialogKey }));
2554
+ dispatch(addActiveController2({ messageId: loopKey, controller: loopController, dialogKey }));
2727
2555
  const ownsDesktopTurn = () => !loopController.signal.aborted && !thunkApi.signal.aborted && getDialogRuntimeState(dialogKey).turnPhaseTurnId === turnPhaseTurnId;
2728
2556
  const admitDesktopBatch = async () => {
2729
- const admission = new AbortController();
2557
+ const admission = new AbortController;
2730
2558
  const checkOwner = () => {
2731
- if (!ownsDesktopTurn()) admission.abort();
2559
+ if (!ownsDesktopTurn())
2560
+ admission.abort();
2732
2561
  };
2733
2562
  const unsubscribe = subscribe(checkOwner);
2734
2563
  loopController.signal.addEventListener("abort", checkOwner);
@@ -2747,7 +2576,8 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2747
2576
  const initialUser = initialMessages.filter((message) => message.role === "user" && sameInput(message.content)).at(-1);
2748
2577
  const isUserTurn = !!initialUser && sameInput(initialUser.content);
2749
2578
  let desktopBatch = isUserTurn && initialUser.metadata?.queueState === "pending" ? await admitDesktopBatch() : isUserTurn ? [...initialMessages.filter((message) => message.role === "user" && message.id !== initialUser.id && message.metadata?.userBatchPhase === "admitted"), initialUser] : [];
2750
- if (!ownsDesktopTurn()) return { aborted: true };
2579
+ if (!ownsDesktopTurn())
2580
+ return { aborted: true };
2751
2581
  while (ownsDesktopTurn()) {
2752
2582
  const desktopRequestUserInput = snapshotUserBatchInput(desktopBatch.length ? desktopBatch : selectAllMsgs(getState(), dialogId));
2753
2583
  const desktopInput = desktopBatch.length ? desktopBatch[desktopBatch.length - 1].content : userInput;
@@ -2757,11 +2587,11 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2757
2587
  let streamResult = null;
2758
2588
  let streamError = null;
2759
2589
  let reasoningBuffer = "";
2760
- const activeToolMessages = /* @__PURE__ */ new Map();
2761
- let desktopToolExecutionLocation = void 0;
2590
+ const activeToolMessages = new Map;
2591
+ let desktopToolExecutionLocation = undefined;
2762
2592
  const ensureAssistantMessageKeys = () => {
2763
2593
  if (!assistantMessageKeys) {
2764
- assistantMessageKeys = createDialogMessageKeyAndId(dialogId);
2594
+ assistantMessageKeys = createDialogMessageKeyAndId2(dialogId);
2765
2595
  assistantSegments.push({
2766
2596
  key: assistantMessageKeys.key,
2767
2597
  messageId: assistantMessageKeys.messageId,
@@ -2774,13 +2604,13 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2774
2604
  return assistantMessageKeys;
2775
2605
  };
2776
2606
  const streamDesktopAssistantUpsert = () => {
2777
- const { key: msgKey2, messageId: messageId2 } = ensureAssistantMessageKeys();
2778
- const segment2 = assistantSegments[assistantSegments.length - 1];
2779
- segment2.content = currentContent;
2607
+ const { key: msgKey, messageId } = ensureAssistantMessageKeys();
2608
+ const segment = assistantSegments[assistantSegments.length - 1];
2609
+ segment.content = currentContent;
2780
2610
  dispatch(messageStreaming({
2781
- id: messageId2,
2611
+ id: messageId,
2782
2612
  dialogId,
2783
- dbKey: msgKey2,
2613
+ dbKey: msgKey,
2784
2614
  content: currentContent,
2785
2615
  role: "assistant",
2786
2616
  isStreaming: true,
@@ -2793,10 +2623,10 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2793
2623
  streamDesktopAssistantUpsert();
2794
2624
  };
2795
2625
  const finalizeCurrentAssistantSegmentForTool = () => {
2796
- const segment2 = assistantSegments[assistantSegments.length - 1];
2797
- if (segment2) {
2798
- segment2.content = currentContent;
2799
- segment2.finalized = true;
2626
+ const segment = assistantSegments[assistantSegments.length - 1];
2627
+ if (segment) {
2628
+ segment.content = currentContent;
2629
+ segment.finalized = true;
2800
2630
  }
2801
2631
  if (assistantMessageKeys && (currentContent.length > 0 || reasoningBuffer.length > 0)) {
2802
2632
  dispatch(updateToolMessage({
@@ -2842,31 +2672,24 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2842
2672
  agentConfigSnapshot: agentConfig,
2843
2673
  dialogMessages: selectAdmittedMessages(selectAllMsgs(getState(), dialogId)),
2844
2674
  signal: loopController.signal,
2845
- // SSE 传输层兜底(review 修复 4):此前本调用方从不传
2846
- // noEventWatchdogMs,watchdog 永远关闭——「已有安全网」只是
2847
- // 错觉,挂起点若在 provider.complete 之外(resolveProvider /
2848
- // adapter 内部,runtime 没有任何 deadline)就会无限静默。
2849
- // 量级必须大于 runtime 自己的 idle 窗(默认 10 分钟无新输出
2850
- // 才放弃,见 localLoop.DEFAULT_LLM_REQUEST_TIMEOUT_MS),
2851
- // 否则一个健康的慢思考轮次会被客户端提前判死,用户拿到的是
2852
- // 未分类的 "stream stalled" 而不是 runtime 的
2853
- // LLM_REQUEST_TIMEOUT 可操作文案。取 2× = 20 分钟:
2854
- // 只兜「runtime 完全没 deadline」的真悬挂。
2855
2675
  noEventWatchdogMs: DESKTOP_SSE_NO_EVENT_WATCHDOG_MS,
2856
2676
  ...desktopTurnAuthToken ? { authToken: desktopTurnAuthToken } : {}
2857
2677
  });
2858
2678
  const first = iterator.next();
2859
2679
  return async function* () {
2860
2680
  const event = await first;
2861
- if (!event.done) yield event.value;
2681
+ if (!event.done)
2682
+ yield event.value;
2862
2683
  yield* iterator;
2863
2684
  }();
2864
2685
  }
2865
2686
  })).unwrap();
2866
- if (!eventStream || !ownsDesktopTurn()) break;
2687
+ if (!eventStream || !ownsDesktopTurn())
2688
+ break;
2867
2689
  for await (const event of eventStream) {
2868
2690
  if (loopController.signal.aborted || thunkApi.signal.aborted) {
2869
- if (w2) w2.__LOOP_STOP_REASON__ = "aborted";
2691
+ if (w)
2692
+ w.__LOOP_STOP_REASON__ = "aborted";
2870
2693
  break;
2871
2694
  }
2872
2695
  if (event.type === "delta") {
@@ -2879,11 +2702,12 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2879
2702
  } else if (event.type === "tool") {
2880
2703
  const toolEvent = event.event;
2881
2704
  const callId = toolEvent.toolCallId;
2882
- if (!callId) continue;
2705
+ if (!callId)
2706
+ continue;
2883
2707
  if (toolEvent.type === "tool-call") {
2884
2708
  attachToolCallIdToSegment(assistantSegments, callId);
2885
2709
  finalizeCurrentAssistantSegmentForTool();
2886
- const { key: dbKey, messageId: toolMsgId } = createDialogMessageKeyAndId(dialogId);
2710
+ const { key: dbKey, messageId: toolMsgId } = createDialogMessageKeyAndId2(dialogId);
2887
2711
  const toolMsg = {
2888
2712
  id: toolMsgId,
2889
2713
  dialogId,
@@ -2893,14 +2717,9 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2893
2717
  isStreaming: true,
2894
2718
  toolName: toolEvent.toolName,
2895
2719
  toolCallId: callId,
2896
- // F2: 实际执行位置(服务端/runtime 投影)挂到 tool
2897
- // 卡片 metadata。优先事件自带 metadata(runtime
2898
- // 投影层直接注入的同名字段),兜底用 turn 级
2899
- // execution_location 帧。缺失/不合法时渲染层
2900
- // projectToolExecutionLocation 收敛为 unknown。
2901
2720
  metadata: {
2902
2721
  ...isRecord(toolEvent.metadata) ? toolEvent.metadata : {},
2903
- ...desktopToolExecutionLocation !== void 0 && !(isRecord(toolEvent.metadata) && toolEvent.metadata.executionLocation !== void 0) ? { executionLocation: desktopToolExecutionLocation } : {},
2722
+ ...desktopToolExecutionLocation !== undefined && !(isRecord(toolEvent.metadata) && toolEvent.metadata.executionLocation !== undefined) ? { executionLocation: desktopToolExecutionLocation } : {},
2904
2723
  ...toolEvent.argumentsPreview ? { argumentsPreview: toolEvent.argumentsPreview } : {}
2905
2724
  },
2906
2725
  ...toolEvent.argumentsPreview ? {
@@ -2926,12 +2745,7 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2926
2745
  ...existingMeta,
2927
2746
  ...toolEvent.metadata,
2928
2747
  ...isError ? { error: true, message: toolEvent.message } : {},
2929
- // 服务端/runtime 已在事件 metadata 带
2930
- // executionLocation 时尊重之;tool-call 阶段
2931
- // 已写入的值由 existingMeta 保留;仅当两边都
2932
- // 没有且 turn 级 execution_location 帧存在时
2933
- // 兜底补上,绝不覆盖已有值。
2934
- ...existingMeta.executionLocation === void 0 && (!isRecord(toolEvent.metadata) || toolEvent.metadata.executionLocation === void 0) && desktopToolExecutionLocation !== void 0 ? { executionLocation: desktopToolExecutionLocation } : {}
2748
+ ...existingMeta.executionLocation === undefined && (!isRecord(toolEvent.metadata) || toolEvent.metadata.executionLocation === undefined) && desktopToolExecutionLocation !== undefined ? { executionLocation: desktopToolExecutionLocation } : {}
2935
2749
  };
2936
2750
  const toolResultMsg = {
2937
2751
  ...existing,
@@ -2942,7 +2756,7 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2942
2756
  summary: toolEvent.summary,
2943
2757
  message: toolEvent.message,
2944
2758
  metadata: mergedMeta,
2945
- argumentsPreview: asOptionalTrimmedString(mergedMeta.argumentsPreview) || asOptionalTrimmedString(existingInput.command) || asOptionalTrimmedString(existingInput.cmd) || void 0
2759
+ argumentsPreview: asOptionalTrimmedString(mergedMeta.argumentsPreview) || asOptionalTrimmedString(existingInput.command) || asOptionalTrimmedString(existingInput.cmd) || undefined
2946
2760
  }),
2947
2761
  metadata: mergedMeta
2948
2762
  };
@@ -2956,15 +2770,11 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2956
2770
  }
2957
2771
  } else if (event.type === "status") {
2958
2772
  const phase = event.phase === "validating-context" ? "validating" : event.phase;
2959
- setDialogTurnPhase({ phase, dialogKey, turnId: turnPhaseTurnId ?? void 0 });
2773
+ setDialogTurnPhase({ phase, dialogKey, turnId: turnPhaseTurnId ?? undefined });
2960
2774
  } else if (event.type === "execution_location") {
2961
2775
  desktopToolExecutionLocation = event.location;
2962
2776
  } else if (event.type === "action_gate") {
2963
- receiveActionGate(
2964
- event.gate,
2965
- targetForRunKind("desktop-local"),
2966
- dialogId
2967
- );
2777
+ receiveActionGate(event.gate, targetForRunKind("desktop-local"), dialogId);
2968
2778
  } else if (event.type === "done") {
2969
2779
  streamResult = event.result;
2970
2780
  } else if (event.type === "error") {
@@ -2973,13 +2783,15 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2973
2783
  }
2974
2784
  } catch (err) {
2975
2785
  if (isAbortError(err) || loopController.signal.aborted || thunkApi.signal.aborted) {
2976
- if (w2) w2.__LOOP_STOP_REASON__ = "aborted";
2786
+ if (w)
2787
+ w.__LOOP_STOP_REASON__ = "aborted";
2977
2788
  } else {
2978
2789
  streamError = err?.message || "Local turn read stream error";
2979
2790
  }
2980
2791
  }
2981
2792
  if (loopController.signal.aborted || thunkApi.signal.aborted || typeof streamError === "string" && /operation was aborted/i.test(streamError)) {
2982
- if (w2) w2.__LOOP_STOP_REASON__ = "aborted";
2793
+ if (w)
2794
+ w.__LOOP_STOP_REASON__ = "aborted";
2983
2795
  const stopKeys = assistantMessageKeys;
2984
2796
  if (stopKeys) {
2985
2797
  const last = assistantSegments[assistantSegments.length - 1];
@@ -2987,35 +2799,30 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
2987
2799
  last.content = currentContent;
2988
2800
  }
2989
2801
  }
2990
- const stopToolNameById = /* @__PURE__ */ new Map();
2802
+ const stopToolNameById = new Map;
2991
2803
  for (const [callId, toolMsg] of activeToolMessages) {
2992
- if (!toolMessageWillPersist(toolMsg)) continue;
2804
+ if (!toolMessageWillPersist(toolMsg))
2805
+ continue;
2993
2806
  const toolName = toolMsg?.toolName;
2994
- stopToolNameById.set(
2995
- callId,
2996
- typeof toolName === "string" && toolName ? toolName : "tool"
2997
- );
2807
+ stopToolNameById.set(callId, typeof toolName === "string" && toolName ? toolName : "tool");
2998
2808
  }
2999
- for (const segment2 of assistantSegments) {
3000
- const hasContent = segment2.content.trim().length > 0;
3001
- const hasToolCalls = segment2.toolCallIds && segment2.toolCallIds.length > 0;
2809
+ for (const segment of assistantSegments) {
2810
+ const hasContent = segment.content.trim().length > 0;
2811
+ const hasToolCalls = segment.toolCallIds && segment.toolCallIds.length > 0;
3002
2812
  if (hasContent || hasToolCalls) {
3003
- const stopToolCalls = buildMinimalToolCallsFromIds(
3004
- segment2.toolCallIds,
3005
- stopToolNameById
3006
- );
2813
+ const stopToolCalls = buildMinimalToolCallsFromIds(segment.toolCallIds, stopToolNameById);
3007
2814
  await persistMessageWithFixedId(dispatch, {
3008
2815
  dialogId,
3009
- id: segment2.messageId,
3010
- dbKey: segment2.key,
2816
+ id: segment.messageId,
2817
+ dbKey: segment.key,
3011
2818
  role: "assistant",
3012
- content: segment2.content,
2819
+ content: segment.content,
3013
2820
  ...stopToolCalls.length > 0 ? { tool_calls: stopToolCalls } : {},
3014
2821
  ...desktopMessageMetadata,
3015
2822
  userId: selectIdentityUserId(getState())
3016
2823
  });
3017
2824
  } else {
3018
- dispatch(removeTransientMessage(segment2.messageId));
2825
+ dispatch(removeTransientMessage(segment.messageId));
3019
2826
  }
3020
2827
  }
3021
2828
  const durableTools = [];
@@ -3038,42 +2845,37 @@ var streamAgentChatTurnHandler = async (args, thunkApi) => {
3038
2845
  return { aborted: true };
3039
2846
  }
3040
2847
  const finalizeDesktopTurnOnError = async (errorText) => {
3041
- const errorToolNameById = /* @__PURE__ */ new Map();
2848
+ const errorToolNameById = new Map;
3042
2849
  for (const [callId, toolMsg] of activeToolMessages) {
3043
- if (!toolMessageWillPersist(toolMsg)) continue;
2850
+ if (!toolMessageWillPersist(toolMsg))
2851
+ continue;
3044
2852
  const toolName = toolMsg?.toolName;
3045
- errorToolNameById.set(
3046
- callId,
3047
- typeof toolName === "string" && toolName ? toolName : "tool"
3048
- );
2853
+ errorToolNameById.set(callId, typeof toolName === "string" && toolName ? toolName : "tool");
3049
2854
  }
3050
- for (const segment2 of assistantSegments) {
3051
- const hasContent = segment2.content.trim().length > 0;
3052
- const hasToolCalls = segment2.toolCallIds && segment2.toolCallIds.length > 0;
2855
+ for (const segment of assistantSegments) {
2856
+ const hasContent = segment.content.trim().length > 0;
2857
+ const hasToolCalls = segment.toolCallIds && segment.toolCallIds.length > 0;
3053
2858
  if (hasContent || hasToolCalls) {
3054
- const errorToolCalls = buildMinimalToolCallsFromIds(
3055
- segment2.toolCallIds,
3056
- errorToolNameById
3057
- );
2859
+ const errorToolCalls = buildMinimalToolCallsFromIds(segment.toolCallIds, errorToolNameById);
3058
2860
  await persistMessageWithFixedId(dispatch, {
3059
2861
  dialogId,
3060
- id: segment2.messageId,
3061
- dbKey: segment2.key,
2862
+ id: segment.messageId,
2863
+ dbKey: segment.key,
3062
2864
  role: "assistant",
3063
- content: segment2.content,
2865
+ content: segment.content,
3064
2866
  ...errorToolCalls.length > 0 ? { tool_calls: errorToolCalls } : {},
3065
2867
  ...desktopMessageMetadata,
3066
2868
  userId: selectIdentityUserId(getState())
3067
2869
  });
3068
2870
  if (hasContent) {
3069
2871
  dispatch(finalizeTransientMessageOnError({
3070
- id: segment2.messageId,
2872
+ id: segment.messageId,
3071
2873
  error: errorText
3072
2874
  }));
3073
2875
  }
3074
2876
  } else {
3075
2877
  dispatch(finalizeTransientMessageOnError({
3076
- id: segment2.messageId,
2878
+ id: segment.messageId,
3077
2879
  error: errorText
3078
2880
  }));
3079
2881
  }
@@ -3111,13 +2913,9 @@ ${info.actionHint}` : streamError;
3111
2913
  return rejectWithValue(message);
3112
2914
  }
3113
2915
  const desktopTurnMessages = streamResult.turnMessages || [];
3114
- const hasSegmentWithCallIds = assistantSegments.some(
3115
- (s) => s.toolCallIds.length > 0
3116
- );
2916
+ const hasSegmentWithCallIds = assistantSegments.some((s) => s.toolCallIds.length > 0);
3117
2917
  if (!hasSegmentWithCallIds) {
3118
- const doneOnlyAssistantCalls = desktopTurnMessages.filter(
3119
- (m) => m?.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0
3120
- ).flatMap((m) => m.tool_calls.map((tc) => tc?.id)).filter((id) => typeof id === "string");
2918
+ const doneOnlyAssistantCalls = desktopTurnMessages.filter((m) => m?.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0).flatMap((m) => m.tool_calls.map((tc) => tc?.id)).filter((id) => typeof id === "string");
3121
2919
  if (doneOnlyAssistantCalls.length > 0) {
3122
2920
  ensureAssistantMessageKeys();
3123
2921
  for (const callId of doneOnlyAssistantCalls) {
@@ -3134,36 +2932,26 @@ ${info.actionHint}` : streamError;
3134
2932
  turnMessages: desktopTurnMessages
3135
2933
  })) {
3136
2934
  dispatch(messageStreaming(toolMessage));
3137
- activeToolMessages.set(
3138
- asTrimmedString(toolMessage.toolCallId) || toolMessage.id,
3139
- toolMessage
3140
- );
2935
+ activeToolMessages.set(asTrimmedString(toolMessage.toolCallId) || toolMessage.id, toolMessage);
3141
2936
  }
3142
2937
  }
3143
- await persistToolMessages(
3144
- dispatch,
3145
- activeToolMessages.values(),
3146
- { isStreaming: false, soft: true }
3147
- );
2938
+ await persistToolMessages(dispatch, activeToolMessages.values(), { isStreaming: false, soft: true });
3148
2939
  const earlierFinalizedSegments = selectPersistableFinalizedSegments(assistantSegments);
3149
- for (const segment2 of earlierFinalizedSegments) {
3150
- const segmentToolCalls = resolveSegmentToolCalls(
3151
- segment2.toolCallIds,
3152
- desktopTurnMessages
3153
- );
3154
- dispatch(write({
2940
+ for (const segment of earlierFinalizedSegments) {
2941
+ const segmentToolCalls = resolveSegmentToolCalls(segment.toolCallIds, desktopTurnMessages);
2942
+ dispatch(write2({
3155
2943
  data: {
3156
- id: segment2.messageId,
3157
- dbKey: segment2.key,
2944
+ id: segment.messageId,
2945
+ dbKey: segment.key,
3158
2946
  dialogId,
3159
- content: segment2.content,
2947
+ content: segment.content,
3160
2948
  role: "assistant",
3161
2949
  isStreaming: false,
3162
2950
  type: "msg" /* MSG */,
3163
2951
  ...segmentToolCalls.length > 0 ? { tool_calls: segmentToolCalls } : {},
3164
2952
  ...desktopMessageMetadata
3165
2953
  },
3166
- customKey: segment2.key
2954
+ customKey: segment.key
3167
2955
  }));
3168
2956
  }
3169
2957
  const { key: msgKey, messageId } = ensureAssistantMessageKeys();
@@ -3187,63 +2975,53 @@ ${info.actionHint}` : streamError;
3187
2975
  text: lastSegmentContent
3188
2976
  }
3189
2977
  ],
3190
- totalUsage: streamResult.usage ?? void 0,
2978
+ totalUsage: streamResult.usage ?? undefined,
3191
2979
  billingUsageRecords: streamResult.usageRecords,
3192
2980
  messageId,
3193
2981
  msgKey,
3194
2982
  agentConfig,
3195
2983
  dialogId,
3196
2984
  dialogKey,
3197
- // 优先用本 turn 累计的 thinking SSE;为空时兜底 streamResult.reasoning_content
3198
- // (provider 在 SSE 流内累计返回的 reasoning_content)。
3199
2985
  reasoningBuffer: reasoningBuffer || (typeof streamResult?.reasoning_content === "string" ? streamResult.reasoning_content : ""),
3200
2986
  toolCalls: lastSegmentToolCalls,
3201
- // 把 provider 报告的 finish_reason 透传给 messageStreamEnd,
3202
- // 由 assembleFinalAssistantMessage 决定是否写进最终 Message。
3203
- finishReason: streamResult.finish_reason ?? void 0,
2987
+ finishReason: streamResult.finish_reason ?? undefined,
3204
2988
  messageMetadata: desktopMessageMetadata
3205
2989
  })).unwrap();
3206
2990
  remoteTransientMessageFinalized = true;
3207
2991
  if (!isUserTurn || !ownsDesktopTurn() || streamResult.finish_reason !== "stop" || streamResult.stopReason && streamResult.stopReason !== "done" || streamResult.pendingInteraction || streamResult.hasPendingInteraction || streamResult.error || streamResult.emptyAssistantFallbackReason) {
3208
- return { usage: streamResult.usage ?? void 0 };
2992
+ return { usage: streamResult.usage ?? undefined };
3209
2993
  }
3210
2994
  desktopBatch = await admitDesktopBatch();
3211
- if (!ownsDesktopTurn()) return { aborted: true };
3212
- if (!desktopBatch.length) return { usage: streamResult.usage ?? void 0 };
2995
+ if (!ownsDesktopTurn())
2996
+ return { aborted: true };
2997
+ if (!desktopBatch.length)
2998
+ return { usage: streamResult.usage ?? undefined };
3213
2999
  }
3214
3000
  return { aborted: true };
3215
3001
  }
3216
3002
  const userInputText = extractAgentRunUserText(userInput);
3217
3003
  const explicitServerBase = asOptionalTrimmedString(args.serverBase) ?? null;
3218
3004
  const normalizedRequestedServerBase = explicitServerBase && normalizeServerOrigin(explicitServerBase);
3219
- const normalizedCurrentServer = normalizeServerOrigin(
3220
- currentServer
3221
- );
3222
- const turnDialogConfig = selectDialogConfigByKey(state, explicitDialogKey) ?? selectCurrentDialogConfig(state);
3223
- const turnDialogExtraReferences = Array.isArray(
3224
- turnDialogConfig?.extraReferences
3225
- ) ? turnDialogConfig.extraReferences : [];
3005
+ const normalizedCurrentServer = normalizeServerOrigin(currentServer);
3006
+ const turnDialogConfig = selectDialogConfigByKey2(state, explicitDialogKey) ?? selectCurrentDialogConfig2(state);
3007
+ const turnDialogExtraReferences = Array.isArray(turnDialogConfig?.extraReferences) ? turnDialogConfig.extraReferences : [];
3226
3008
  const canProxyToExplicitServerBase2 = canProxyToExplicitServerBase({
3227
3009
  userInput,
3228
3010
  runtimeOptions,
3229
3011
  dialogExtraReferences: turnDialogExtraReferences
3230
3012
  });
3231
3013
  if (explicitServerBase && canProxyToExplicitServerBase2) {
3232
- if (normalizedRequestedServerBase && normalizedCurrentServer && normalizedRequestedServerBase === normalizedCurrentServer) {
3233
- } else {
3014
+ if (normalizedRequestedServerBase && normalizedCurrentServer && normalizedRequestedServerBase === normalizedCurrentServer) {} else {
3234
3015
  const token = selectIdentityToken(state);
3235
3016
  const authHeader = token ? `Bearer ${token}` : "";
3236
3017
  const rawMessages = selectAdmittedMessages(selectAllMsgs(state, dialogId));
3237
- const visibleMessages = buildAgentViewMessages(
3238
- rawMessages,
3239
- agentConfig.dbKey
3240
- );
3018
+ const visibleMessages = buildAgentViewMessages(rawMessages, agentConfig.dbKey);
3241
3019
  const cleanedMessages = filterAndCleanMessages(visibleMessages);
3242
- const { key: msgKey, messageId } = createDialogMessageKeyAndId(dialogId);
3020
+ const { key: msgKey, messageId } = createDialogMessageKeyAndId2(dialogId);
3243
3021
  remoteTransientMessageId = messageId;
3244
3022
  const remoteMessageMetadata = buildMessageMetadata(agentConfig);
3245
3023
  let accumulated = "";
3246
- let totalTurnUsage2 = void 0;
3024
+ let totalTurnUsage = undefined;
3247
3025
  const buildRemoteAssistantMessage = () => ({
3248
3026
  dialogId,
3249
3027
  id: messageId,
@@ -3260,7 +3038,7 @@ ${info.actionHint}` : streamError;
3260
3038
  messageMetadata: remoteMessageMetadata
3261
3039
  });
3262
3040
  loopKey = `loop:${dialogId}`;
3263
- dispatch(addActiveController({ messageId: loopKey, controller: loopController, dialogKey }));
3041
+ dispatch(addActiveController2({ messageId: loopKey, controller: loopController, dialogKey }));
3264
3042
  dispatch(messageStreaming({
3265
3043
  id: messageId,
3266
3044
  dialogId,
@@ -3275,11 +3053,7 @@ ${info.actionHint}` : streamError;
3275
3053
  } else {
3276
3054
  dispatch(removeTransientMessage(messageId));
3277
3055
  }
3278
- await persistRemoteToolMessagesAndCleanup(
3279
- dispatch,
3280
- remoteToolHandlers.activeToolMessages
3281
- ).catch(() => {
3282
- });
3056
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages).catch(() => {});
3283
3057
  setLoopStopReason("error");
3284
3058
  remoteTransientMessageFinalized = true;
3285
3059
  return rejectWithValue(message);
@@ -3320,39 +3094,26 @@ ${info.actionHint}` : streamError;
3320
3094
  const remoteResponse = await performServerProxyFetchWithRetry({
3321
3095
  execute: () => fetch(remoteRunUrl, remoteRunInit),
3322
3096
  signal: loopController.signal,
3323
- // A keepalive POST may already have reached the server when
3324
- // the connection error surfaces; /api/agent/run stream turns
3325
- // are not idempotent, so never silently re-submit it.
3326
3097
  retryNetworkErrors: remoteRunInit.keepalive !== true,
3327
3098
  logPrefix: "[streamAgentChatTurn.remoteRun]"
3328
3099
  });
3329
3100
  if (!remoteResponse.ok) {
3330
3101
  const errorText = await remoteResponse.text();
3331
- return await rejectRemoteStream(
3332
- errorText || `Remote agent run failed (${remoteResponse.status})`
3333
- );
3102
+ return await rejectRemoteStream(errorText || `Remote agent run failed (${remoteResponse.status})`);
3334
3103
  }
3335
3104
  const reader = remoteResponse.body?.getReader();
3336
3105
  if (!reader) {
3337
- return await rejectRemoteStream("\u65E0\u6CD5\u8BFB\u53D6\u8FDC\u7AEF\u6D41\u5F0F\u54CD\u5E94");
3106
+ return await rejectRemoteStream("无法读取远端流式响应");
3338
3107
  }
3339
- const decoder = new TextDecoder();
3108
+ const decoder = new TextDecoder;
3340
3109
  const parseSSE = createSSEParser();
3341
3110
  const abortRemoteStream = async () => {
3342
3111
  if (accumulated.length <= 0) {
3343
- await persistRemoteToolMessagesAndCleanup(
3344
- dispatch,
3345
- remoteToolHandlers.activeToolMessages
3346
- ).catch(() => {
3347
- });
3112
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages).catch(() => {});
3348
3113
  return;
3349
3114
  }
3350
3115
  await persistMessageWithFixedId(dispatch, buildRemoteAssistantMessage());
3351
- await persistRemoteToolMessagesAndCleanup(
3352
- dispatch,
3353
- remoteToolHandlers.activeToolMessages
3354
- ).catch(() => {
3355
- });
3116
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages).catch(() => {});
3356
3117
  };
3357
3118
  try {
3358
3119
  const result = await consumeAgentRunStream({
@@ -3365,29 +3126,17 @@ ${info.actionHint}` : streamError;
3365
3126
  isDoneEvent: (payload) => payload?.type === "done",
3366
3127
  onPayload: async (payload) => {
3367
3128
  if (payload.type === "error") {
3368
- return { reject: payload.message || "\u8FDC\u7AEF Agent \u6267\u884C\u5931\u8D25" };
3129
+ return { reject: payload.message || "远端 Agent 执行失败" };
3369
3130
  }
3370
3131
  if (payload.type === "action_gate" && payload.gate) {
3371
- receiveActionGate(
3372
- payload.gate,
3373
- targetForRunKind("server-run", {
3374
- server: explicitServerBase,
3375
- token
3376
- }),
3377
- dialogId
3378
- );
3132
+ receiveActionGate(payload.gate, targetForRunKind("server-run", {
3133
+ server: explicitServerBase,
3134
+ token
3135
+ }), dialogId);
3379
3136
  }
3380
3137
  if (payload.type === "agent_handoff") {
3381
- await patchDialogThreadMetadata(
3382
- dispatch,
3383
- dialogKey,
3384
- payload.threadMetadata
3385
- );
3386
- await patchDialogActiveAgent(
3387
- dispatch,
3388
- dialogKey,
3389
- payload.agentKey
3390
- );
3138
+ await patchDialogThreadMetadata(dispatch, dialogKey, payload.threadMetadata);
3139
+ await patchDialogActiveAgent(dispatch, dialogKey, payload.agentKey);
3391
3140
  }
3392
3141
  remoteToolHandlers.handleToolPayload(payload);
3393
3142
  if ((payload.type === "text" || payload.type === "text_replace") && typeof payload.content === "string") {
@@ -3402,7 +3151,7 @@ ${info.actionHint}` : streamError;
3402
3151
  }));
3403
3152
  }
3404
3153
  if (payload.type === "done") {
3405
- totalTurnUsage2 = payload.usage;
3154
+ totalTurnUsage = payload.usage;
3406
3155
  }
3407
3156
  }
3408
3157
  });
@@ -3416,45 +3165,31 @@ ${info.actionHint}` : streamError;
3416
3165
  if (!result.sawDone) {
3417
3166
  dispatch(finalizeTransientMessageOnError({
3418
3167
  id: messageId,
3419
- error: "\u8FDC\u7AEF Agent \u6D41\u5F0F\u54CD\u5E94\u88AB\u4E2D\u65AD,\u672A\u6536\u5230\u5B8C\u6210\u4FE1\u53F7"
3168
+ error: "远端 Agent 流式响应被中断,未收到完成信号"
3420
3169
  }));
3421
- await persistRemoteToolMessagesAndCleanup(
3422
- dispatch,
3423
- remoteToolHandlers.activeToolMessages
3424
- ).catch(() => {
3425
- });
3170
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages).catch(() => {});
3426
3171
  remoteTransientMessageFinalized = true;
3427
3172
  setLoopStopReason("error");
3428
- return rejectWithValue(
3429
- "\u8FDC\u7AEF Agent \u6D41\u5F0F\u54CD\u5E94\u88AB\u4E2D\u65AD,\u672A\u6536\u5230\u5B8C\u6210\u4FE1\u53F7"
3430
- );
3173
+ return rejectWithValue("远端 Agent 流式响应被中断,未收到完成信号");
3431
3174
  }
3432
3175
  await persistMessageWithFixedId(dispatch, buildRemoteAssistantMessage());
3433
- await persistRemoteToolMessagesAndCleanup(
3434
- dispatch,
3435
- remoteToolHandlers.activeToolMessages
3436
- );
3176
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages);
3437
3177
  remoteTransientMessageFinalized = true;
3438
3178
  }
3439
3179
  } finally {
3440
3180
  try {
3441
3181
  await reader.cancel();
3442
- } catch {
3443
- }
3182
+ } catch {}
3444
3183
  if (remoteToolHandlers.activeToolMessages.size > 0) {
3445
- await persistRemoteToolMessagesAndCleanup(
3446
- dispatch,
3447
- remoteToolHandlers.activeToolMessages
3448
- ).catch(() => {
3449
- });
3184
+ await persistRemoteToolMessagesAndCleanup(dispatch, remoteToolHandlers.activeToolMessages).catch(() => {});
3450
3185
  }
3451
3186
  }
3452
3187
  return {
3453
- usage: totalTurnUsage2 ?? void 0
3188
+ usage: totalTurnUsage ?? undefined
3454
3189
  };
3455
3190
  }
3456
3191
  }
3457
- const activeDialogConfig = selectDialogConfigByKey(getState(), dialogKey) ?? selectDialogConfigByKey(getState(), explicitDialogKey) ?? selectCurrentDialogConfig(getState()) ?? currentDialog;
3192
+ const activeDialogConfig = selectDialogConfigByKey2(getState(), dialogKey) ?? selectDialogConfigByKey2(getState(), explicitDialogKey) ?? selectCurrentDialogConfig2(getState()) ?? currentDialog;
3458
3193
  const turnToolContext = await resolveTurnToolContext({
3459
3194
  agentConfig,
3460
3195
  dialogConfig: activeDialogConfig,
@@ -3469,7 +3204,7 @@ ${info.actionHint}` : streamError;
3469
3204
  const referenceTools = turnToolContext.referencedTools ?? [];
3470
3205
  const contextTools = turnToolContext.contextTools ?? [];
3471
3206
  const attachmentTools = turnToolContext.attachmentToolNames ?? [];
3472
- const mergedContentCache = turnToolContext.mergedContentCache ?? /* @__PURE__ */ new Map();
3207
+ const mergedContentCache = turnToolContext.mergedContentCache ?? new Map;
3473
3208
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-references-resolved", {
3474
3209
  referenceCount: normalizedReferences.length,
3475
3210
  referencedToolCount: referenceTools.length
@@ -3486,25 +3221,11 @@ ${info.actionHint}` : streamError;
3486
3221
  const initialRawMsgs = selectAdmittedMessages(selectAllMsgs(state, dialogId));
3487
3222
  const initialHistoryIds = new Set(initialRawMsgs.map((m) => m.id));
3488
3223
  const accountSkillRuntime = agentConfigWithReferences.runtimePromptAlreadyInMessages ? null : await resolveUserSkillRuntime(agentConfigWithReferences, accountPolicy);
3489
- const agentConfigWithTools = resolveWebAgentRuntimeToolSurface(
3490
- mergeAgentToolsWithRuntime(
3491
- agentConfigWithReferences,
3492
- [...contextTools, ...attachmentTools],
3493
- mentionedTools,
3494
- runtimeOptions,
3495
- state,
3496
- accountSkillRuntime,
3497
- accountPolicy.systemBuiltinSkills
3498
- ),
3499
- state
3500
- );
3224
+ const agentConfigWithTools = resolveWebAgentRuntimeToolSurface(mergeAgentToolsWithRuntime(agentConfigWithReferences, [...contextTools, ...attachmentTools], mentionedTools, runtimeOptions, state, accountSkillRuntime, accountPolicy.systemBuiltinSkills), state);
3501
3225
  let effectiveContextBlocks = contextBlocks;
3502
- let agentConfigForCall = applyImageConfigRuntimeOverride(
3503
- agentConfigWithTools,
3504
- runtimeOptions
3505
- );
3226
+ let agentConfigForCall = applyImageConfigRuntimeOverride(agentConfigWithTools, runtimeOptions);
3506
3227
  const currentUserId = selectIdentityUserId(state);
3507
- const dialogAgentMode = activeDialogConfig ? resolveDialogAgentMode(activeDialogConfig) : void 0;
3228
+ const dialogAgentMode = activeDialogConfig ? resolveDialogAgentMode(activeDialogConfig) : undefined;
3508
3229
  if (!isWebMcpTurnAllowed({
3509
3230
  currentUserId,
3510
3231
  agentConfig: agentConfigForCall,
@@ -3521,7 +3242,7 @@ ${info.actionHint}` : streamError;
3521
3242
  const mcpInjection = await resolveWebTurnMcpInjection({
3522
3243
  userId: currentUserId,
3523
3244
  token: selectIdentityToken(state),
3524
- baseUrl: resolveToolBaseUrl(currentServer),
3245
+ baseUrl: resolveToolBaseUrl2(currentServer),
3525
3246
  agentKey,
3526
3247
  agentConfig: agentConfigForCall,
3527
3248
  dialogAgentMode,
@@ -3541,27 +3262,17 @@ ${info.actionHint}` : streamError;
3541
3262
  }
3542
3263
  }
3543
3264
  const effectiveAgentConfig = agentConfigForCall;
3544
- const initialImageGenerationState = resolveImageGenerationStreamingState(
3545
- effectiveAgentConfig
3546
- );
3265
+ const initialImageGenerationState = resolveImageGenerationStreamingState(effectiveAgentConfig);
3547
3266
  const streamingMessageMetadata = {
3548
3267
  ...buildMessageMetadata(agentConfigForCall),
3549
3268
  ...initialImageGenerationState ? { imageGenerationState: initialImageGenerationState } : {}
3550
3269
  };
3551
- const isRespModel = resolveClientWire(
3552
- resolveAgentCallPlan(agentConfigForCall, {})
3553
- ) === "responses";
3270
+ const isRespModel = resolveClientWire(resolveAgentCallPlan(agentConfigForCall, {})) === "responses";
3554
3271
  if (isRespModel) {
3555
- const maxExecutionTime2 = accountPolicy.maxExecutionTime;
3556
- const MAX_TIME_MS2 = maxExecutionTime2 > 0 ? maxExecutionTime2 : 24e4;
3557
- const startTime2 = Date.now();
3558
- const staticContexts2 = await buildStaticContextsWithToolsPrewarm(
3559
- state,
3560
- dispatch,
3561
- agentConfigForCall,
3562
- currentDialog ?? void 0,
3563
- mergedContentCache
3564
- );
3272
+ const maxExecutionTime = accountPolicy.maxExecutionTime;
3273
+ const MAX_TIME_MS = maxExecutionTime > 0 ? maxExecutionTime : 240000;
3274
+ const startTime = Date.now();
3275
+ const staticContexts = await buildStaticContextsWithToolsPrewarm(state, dispatch, agentConfigForCall, currentDialog ?? undefined, mergedContentCache);
3565
3276
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-static-context-ready", {
3566
3277
  model: agentConfigForCall.model,
3567
3278
  responseApi: true
@@ -3569,61 +3280,56 @@ ${info.actionHint}` : streamError;
3569
3280
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-post-static-entered", {
3570
3281
  responseApi: true
3571
3282
  });
3572
- let appendTempUserInput2 = true;
3573
- let activeTurnUserMessageId2 = args.userMessageId;
3574
- let currentParentMessageId2 = parentMessageId ?? void 0;
3283
+ let appendTempUserInput = true;
3284
+ let activeTurnUserMessageId = args.userMessageId;
3285
+ let currentParentMessageId = parentMessageId ?? undefined;
3575
3286
  const storedResponsesState = currentDialog?.responsesState;
3576
- let responsesState = selectResponsesConversationState(
3577
- storedResponsesState,
3578
- agentConfigForCall
3579
- );
3287
+ let responsesState = selectResponsesConversationState(storedResponsesState, agentConfigForCall);
3580
3288
  if (storedResponsesState != null && !responsesState) {
3581
- dispatch(
3582
- patch({
3583
- dbKey: dialogKey,
3584
- changes: { responsesState: null }
3585
- })
3586
- );
3289
+ dispatch(patch2({
3290
+ dbKey: dialogKey,
3291
+ changes: { responsesState: null }
3292
+ }));
3587
3293
  }
3588
- const w2 = typeof globalThis !== "undefined" && globalThis.window ? globalThis.window : null;
3589
- if (w2) w2.__LOOP_STOP_REASON__ = null;
3294
+ const w = typeof globalThis !== "undefined" && globalThis.window ? globalThis.window : null;
3295
+ if (w)
3296
+ w.__LOOP_STOP_REASON__ = null;
3590
3297
  loopKey = `loop:${dialogId}`;
3591
3298
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-active-controller-adding", {
3592
3299
  responseApi: true
3593
3300
  });
3594
- dispatch(addActiveController({ messageId: loopKey, controller: loopController, dialogKey }));
3301
+ dispatch(addActiveController2({ messageId: loopKey, controller: loopController, dialogKey }));
3595
3302
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-active-controller-added", {
3596
3303
  responseApi: true
3597
3304
  });
3598
- for (; ; ) {
3305
+ for (;; ) {
3599
3306
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-loop-entered", {
3600
3307
  responseApi: true
3601
3308
  });
3602
- const requestParentMessageId = currentParentMessageId2;
3309
+ const requestParentMessageId = currentParentMessageId;
3603
3310
  if (loopController.signal.aborted || thunkApi.signal.aborted) {
3604
3311
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-loop-aborted-before-context", {
3605
3312
  loopControllerAborted: loopController.signal.aborted,
3606
3313
  thunkSignalAborted: thunkApi.signal.aborted,
3607
3314
  responseApi: true
3608
3315
  });
3609
- if (w2) w2.__LOOP_STOP_REASON__ = "aborted";
3316
+ if (w)
3317
+ w.__LOOP_STOP_REASON__ = "aborted";
3610
3318
  return { aborted: true };
3611
3319
  }
3612
3320
  const loopState = getState();
3613
3321
  const now = Date.now();
3614
- if (now - startTime2 > MAX_TIME_MS2) {
3322
+ if (now - startTime > MAX_TIME_MS) {
3615
3323
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-loop-timeout-before-context", {
3616
- maxTimeMs: MAX_TIME_MS2,
3617
- elapsedMs: now - startTime2,
3324
+ maxTimeMs: MAX_TIME_MS,
3325
+ elapsedMs: now - startTime,
3618
3326
  responseApi: true
3619
3327
  });
3620
- if (w2) w2.__LOOP_STOP_REASON__ = "timeout";
3328
+ if (w)
3329
+ w.__LOOP_STOP_REASON__ = "timeout";
3621
3330
  break;
3622
3331
  }
3623
- const accessError = validateAccessAndBalance(
3624
- agentConfigForCall,
3625
- loopState
3626
- );
3332
+ const accessError = validateAccessAndBalance(agentConfigForCall, loopState);
3627
3333
  if (accessError) {
3628
3334
  const accessErrorReason = classifyQuickChatAccessError(accessError);
3629
3335
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-access-error-before-context", {
@@ -3636,23 +3342,12 @@ ${info.actionHint}` : streamError;
3636
3342
  reason: accessErrorReason,
3637
3343
  responseApi: true
3638
3344
  });
3639
- await finalizeQuickChatAgentTurnFailure(
3640
- dispatch,
3641
- runtimeDialogKey,
3642
- agentKey,
3643
- new Error(accessError)
3644
- );
3345
+ await finalizeQuickChatAgentTurnFailure(dispatch, runtimeDialogKey, agentKey, new Error(accessError));
3645
3346
  }
3646
3347
  setLoopStopReason("error");
3647
3348
  return rejectWithValue(accessError);
3648
3349
  }
3649
- const willSkipDynamicContext = canUseQuickChatEmptyDynamicContexts(
3650
- quickChatPerfStartedAt,
3651
- userInput,
3652
- runtimeOptions,
3653
- currentDialog,
3654
- agentConfigForCall
3655
- );
3350
+ const willSkipDynamicContext = canUseQuickChatEmptyDynamicContexts(quickChatPerfStartedAt, userInput, runtimeOptions, currentDialog, agentConfigForCall);
3656
3351
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-dynamic-context-decision", {
3657
3352
  hasRuntimeOptions: !!requestedRuntimeOptions,
3658
3353
  isSimpleTextInput: isSimpleTextInput(userInput),
@@ -3660,37 +3355,17 @@ ${info.actionHint}` : streamError;
3660
3355
  willSkipDynamicContext,
3661
3356
  responseApi: true
3662
3357
  });
3663
- const dynamicContexts = willSkipDynamicContext ? (logQuickChatPerfStage2(
3664
- quickChatPerfStartedAt,
3665
- "stream-agent-dynamic-context-skipped",
3666
- {
3667
- reason: "simple-quick-chat-first-turn",
3668
- responseApi: true
3669
- }
3670
- ), EMPTY_DYNAMIC_CONTEXTS) : await buildDynamicContextsForTurn(
3671
- loopState,
3672
- dispatch,
3673
- agentConfigForCall,
3674
- userInput,
3675
- runtimeOptions,
3676
- mergedContentCache,
3677
- dialogKey,
3678
- quickChatPerfStartedAt,
3679
- serverBase
3680
- );
3358
+ const dynamicContexts = willSkipDynamicContext ? (logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-dynamic-context-skipped", {
3359
+ reason: "simple-quick-chat-first-turn",
3360
+ responseApi: true
3361
+ }), EMPTY_DYNAMIC_CONTEXTS) : await buildDynamicContextsForTurn(loopState, dispatch, agentConfigForCall, userInput, runtimeOptions, mergedContentCache, dialogKey, quickChatPerfStartedAt, serverBase);
3681
3362
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-dynamic-context-ready", {
3682
3363
  responseApi: true
3683
3364
  });
3684
- const contexts = withRequestContextBlocks(
3685
- mergeContexts(staticContexts2, dynamicContexts),
3686
- effectiveContextBlocks
3687
- );
3365
+ const contexts = withRequestContextBlocks(mergeContexts(staticContexts, dynamicContexts), effectiveContextBlocks);
3688
3366
  const rawMessages = selectAdmittedMessages(selectAllMsgs(loopState, dialogId));
3689
- let visibleMessages = buildAgentViewMessages(
3690
- rawMessages,
3691
- agentConfigForCall.dbKey
3692
- );
3693
- if (appendTempUserInput2 && hasAgentRunUserInputContent(agentRunUserInput)) {
3367
+ let visibleMessages = buildAgentViewMessages(rawMessages, agentConfigForCall.dbKey);
3368
+ if (appendTempUserInput && hasAgentRunUserInputContent(agentRunUserInput)) {
3694
3369
  if (!isLastMessageMatchingUserInput(visibleMessages, agentRunUserInput)) {
3695
3370
  const tempId = `__tmp_user_${Date.now()}`;
3696
3371
  visibleMessages = [
@@ -3709,16 +3384,13 @@ ${info.actionHint}` : streamError;
3709
3384
  }
3710
3385
  const requestUserInput = snapshotUserBatchInput(selectAllMsgs(loopState, dialogId));
3711
3386
  const cleanedMessages = filterAndCleanMessages(visibleMessages);
3712
- const ctxWindow = resolveAgentContextWindow(agentConfigForCall);
3387
+ const ctxWindow = resolveAgentContextWindow3(agentConfigForCall);
3713
3388
  const messagesBeforeStrip = compressOldToolResults(cleanedMessages);
3714
- const preprocessedResult = await stripImagePartsForTextOnlyAgent(
3715
- messagesBeforeStrip,
3716
- agentConfigForCall
3717
- );
3389
+ const preprocessedResult = await stripImagePartsForTextOnlyAgent(messagesBeforeStrip, agentConfigForCall);
3718
3390
  notifyOmittedImagesIfPresent({
3719
3391
  downgraded: preprocessedResult.downgraded,
3720
3392
  messagesBeforeStrip,
3721
- targetUserMessageId: activeTurnUserMessageId2
3393
+ targetUserMessageId: activeTurnUserMessageId
3722
3394
  });
3723
3395
  const { bodyData, fallbackBodyData, dynamicMessages, stableMessages } = await admitWebRequest({
3724
3396
  contextWindow: ctxWindow,
@@ -3732,32 +3404,31 @@ ${info.actionHint}` : streamError;
3732
3404
  preserveLatestUserByProjection: true
3733
3405
  }, { ...turnThunkApi, signal: loopController.signal }),
3734
3406
  build: async () => {
3735
- const summaryConfig = selectById(getState(), dialogKey);
3407
+ const summaryConfig = selectById2(getState(), dialogKey);
3736
3408
  const refreshedContexts = { ...contexts, dialogSummary: summaryConfig?.summary || null };
3737
3409
  const processedMessages = projectSummaryHistory(preprocessedResult.messages, summaryConfig?.summary, summaryConfig?.summarizedBeforeId);
3738
- let firstDynamicIdx = processedMessages.findIndex(
3739
- (m) => m.id && !initialHistoryIds.has(m.id)
3740
- );
3741
- if (firstDynamicIdx === -1) firstDynamicIdx = processedMessages.length;
3742
- let stableMessages2 = processedMessages.slice(0, firstDynamicIdx);
3743
- let dynamicMessages2 = processedMessages.slice(firstDynamicIdx);
3744
- const bodyData2 = generateRequestBody({
3410
+ let firstDynamicIdx = processedMessages.findIndex((m) => m.id && !initialHistoryIds.has(m.id));
3411
+ if (firstDynamicIdx === -1)
3412
+ firstDynamicIdx = processedMessages.length;
3413
+ let stableMessages = processedMessages.slice(0, firstDynamicIdx);
3414
+ let dynamicMessages = processedMessages.slice(firstDynamicIdx);
3415
+ const bodyData = generateRequestBody({
3745
3416
  agentConfig: effectiveAgentConfig,
3746
- messages: dynamicMessages2,
3747
- stableMessages: stableMessages2,
3417
+ messages: dynamicMessages,
3418
+ stableMessages,
3748
3419
  userInput: userInputText,
3749
3420
  contexts: refreshedContexts,
3750
3421
  responsesState
3751
3422
  });
3752
- const fallbackBodyData2 = responsesState ? generateRequestBody({
3423
+ const fallbackBodyData = responsesState ? generateRequestBody({
3753
3424
  agentConfig: effectiveAgentConfig,
3754
- messages: dynamicMessages2,
3755
- stableMessages: stableMessages2,
3425
+ messages: dynamicMessages,
3426
+ stableMessages,
3756
3427
  userInput: userInputText,
3757
3428
  contexts: refreshedContexts,
3758
3429
  responsesState: null
3759
- }) : void 0;
3760
- return { value: { bodyData: bodyData2, fallbackBodyData: fallbackBodyData2, dynamicMessages: dynamicMessages2, stableMessages: stableMessages2 }, wireBodies: [buildResponsesRequestBodyWithTools(bodyData2, agentConfigForCall), ...fallbackBodyData2 ? [buildResponsesRequestBodyWithTools(fallbackBodyData2, agentConfigForCall)] : []] };
3430
+ }) : undefined;
3431
+ return { value: { bodyData, fallbackBodyData, dynamicMessages, stableMessages }, wireBodies: [buildResponsesRequestBodyWithTools(bodyData, agentConfigForCall), ...fallbackBodyData ? [buildResponsesRequestBodyWithTools(fallbackBodyData, agentConfigForCall)] : []] };
3761
3432
  }
3762
3433
  });
3763
3434
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-model-request-starting", {
@@ -3777,69 +3448,64 @@ ${info.actionHint}` : streamError;
3777
3448
  agentConfig: agentConfigForCall,
3778
3449
  thunkApi: turnThunkApi,
3779
3450
  dialogKey,
3780
- parentMessageId: currentParentMessageId2,
3451
+ parentMessageId: currentParentMessageId,
3781
3452
  messageMetadata: streamingMessageMetadata,
3782
3453
  quickChatPerfStartedAt,
3783
3454
  fallbackBodyData,
3784
3455
  ...agentConfigForCall.dbKey === PUBLIC_GPT_IMAGE_2_GENERATOR_AGENT_KEY ? {
3785
3456
  currentReferenceImageUrls: extractImageUrlsFromMessages([{
3786
3457
  role: "user",
3787
- content: activeTurnUserMessageId2 ? rawMessages.find((message) => message.role === "user" && message.id === activeTurnUserMessageId2)?.content : appendTempUserInput2 ? agentRunUserInput : void 0
3458
+ content: activeTurnUserMessageId ? rawMessages.find((message) => message.role === "user" && message.id === activeTurnUserMessageId)?.content : appendTempUserInput ? agentRunUserInput : undefined
3788
3459
  }])
3789
3460
  } : {},
3790
- userMessageId: workMemoryUserMessageId(dialogId, activeTurnUserMessageId2)
3461
+ userMessageId: workMemoryUserMessageId(dialogId, activeTurnUserMessageId)
3791
3462
  });
3792
3463
  }
3793
3464
  })).unwrap();
3794
- if (isTurnAborted()) return { aborted: true };
3795
- if (!meta) throw new Error("Model request returned no result; reply did not complete");
3465
+ if (isTurnAborted())
3466
+ return { aborted: true };
3467
+ if (!meta)
3468
+ throw new Error("Model request returned no result; reply did not complete");
3796
3469
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-model-request-finished", {
3797
3470
  responseApi: true,
3798
3471
  hasToolCalls: meta.hasToolCalls,
3799
3472
  hasHandedOff: meta.hasHandedOff,
3800
3473
  hasPendingInteraction: meta.hasPendingInteraction
3801
3474
  });
3802
- appendTempUserInput2 = false;
3803
- currentParentMessageId2 = void 0;
3475
+ appendTempUserInput = false;
3476
+ currentParentMessageId = undefined;
3804
3477
  if (meta.responseId) {
3805
- responsesState = updateResponsesConversationState(
3806
- agentConfigForCall,
3807
- meta.responseId
3808
- );
3478
+ responsesState = updateResponsesConversationState(agentConfigForCall, meta.responseId);
3809
3479
  if (responsesState) {
3810
- dispatch(
3811
- patch({
3812
- dbKey: dialogKey,
3813
- changes: { responsesState }
3814
- })
3815
- );
3480
+ dispatch(patch2({
3481
+ dbKey: dialogKey,
3482
+ changes: { responsesState }
3483
+ }));
3816
3484
  } else if (meta.responsesStateFallback) {
3817
- dispatch(
3818
- patch({
3819
- dbKey: dialogKey,
3820
- changes: { responsesState: null }
3821
- })
3822
- );
3485
+ dispatch(patch2({
3486
+ dbKey: dialogKey,
3487
+ changes: { responsesState: null }
3488
+ }));
3823
3489
  }
3824
3490
  } else if (meta.responsesStateFallback) {
3825
3491
  responsesState = null;
3826
- dispatch(
3827
- patch({
3828
- dbKey: dialogKey,
3829
- changes: { responsesState: null }
3830
- })
3831
- );
3492
+ dispatch(patch2({
3493
+ dbKey: dialogKey,
3494
+ changes: { responsesState: null }
3495
+ }));
3832
3496
  }
3833
3497
  totalTurnUsage = updateTotalUsage(totalTurnUsage, meta.usage);
3834
3498
  if (meta.hasHandedOff) {
3835
3499
  if (!requestParentMessageId && meta.messageId) {
3836
3500
  dispatch(removeTransientMessage(meta.messageId));
3837
3501
  }
3838
- if (w2) w2.__LOOP_STOP_REASON__ = "handoff";
3502
+ if (w)
3503
+ w.__LOOP_STOP_REASON__ = "handoff";
3839
3504
  break;
3840
3505
  }
3841
3506
  if (meta.hasPendingInteraction) {
3842
- if (w2) w2.__LOOP_STOP_REASON__ = "pending";
3507
+ if (w)
3508
+ w.__LOOP_STOP_REASON__ = "pending";
3843
3509
  break;
3844
3510
  }
3845
3511
  if (!loopController.signal.aborted && !thunkApi.signal.aborted) {
@@ -3847,50 +3513,44 @@ ${info.actionHint}` : streamError;
3847
3513
  dialogKey,
3848
3514
  signal: loopController.signal
3849
3515
  })).unwrap();
3850
- if (loopController.signal.aborted || thunkApi.signal.aborted) break;
3516
+ if (loopController.signal.aborted || thunkApi.signal.aborted)
3517
+ break;
3851
3518
  if (admitted.length) {
3852
- activeTurnUserMessageId2 = admitted[admitted.length - 1].id;
3519
+ activeTurnUserMessageId = admitted[admitted.length - 1].id;
3853
3520
  continue;
3854
3521
  }
3855
3522
  }
3856
3523
  const afterTurnState = getState();
3857
- const queuedMessages = selectPendingUserInputQueue(afterTurnState, dialogKey);
3524
+ const queuedMessages = selectPendingUserInputQueue2(afterTurnState, dialogKey);
3858
3525
  if (queuedMessages.length > 0) {
3859
3526
  const queuedText = queuedMessages[0];
3860
- const currentDialogConfig = selectDialogConfigByKey(afterTurnState, dialogKey) ?? selectCurrentDialogConfig(afterTurnState);
3527
+ const currentDialogConfig = selectDialogConfigByKey2(afterTurnState, dialogKey) ?? selectCurrentDialogConfig2(afterTurnState);
3861
3528
  if (!currentDialogConfig) {
3862
- dispatch(clearPendingUserInputQueue({ dialogKey }));
3529
+ dispatch(clearPendingUserInputQueue2({ dialogKey }));
3863
3530
  break;
3864
3531
  }
3865
- const persisted = await dispatch(
3866
- prepareAndPersistUserMessage({
3867
- userInput: queuedText,
3868
- dialogConfig: currentDialogConfig
3869
- })
3870
- ).unwrap();
3871
- dispatch(dequeueUserInput({ dialogKey }));
3872
- activeTurnUserMessageId2 = persisted?.id;
3532
+ const persisted = await dispatch(prepareAndPersistUserMessage({
3533
+ userInput: queuedText,
3534
+ dialogConfig: currentDialogConfig
3535
+ })).unwrap();
3536
+ dispatch(dequeueUserInput2({ dialogKey }));
3537
+ activeTurnUserMessageId = persisted?.id;
3873
3538
  continue;
3874
3539
  }
3875
3540
  if (!meta.hasToolCalls) {
3876
- if (w2) w2.__LOOP_STOP_REASON__ = "done";
3541
+ if (w)
3542
+ w.__LOOP_STOP_REASON__ = "done";
3877
3543
  break;
3878
3544
  }
3879
3545
  }
3880
3546
  return {
3881
- usage: totalTurnUsage ?? void 0
3547
+ usage: totalTurnUsage ?? undefined
3882
3548
  };
3883
3549
  }
3884
3550
  const maxExecutionTime = accountPolicy.maxExecutionTime;
3885
- const MAX_TIME_MS = maxExecutionTime > 0 ? maxExecutionTime : 24e4;
3551
+ const MAX_TIME_MS = maxExecutionTime > 0 ? maxExecutionTime : 240000;
3886
3552
  const startTime = Date.now();
3887
- const staticContexts = await buildStaticContextsWithToolsPrewarm(
3888
- state,
3889
- dispatch,
3890
- agentConfigForCall,
3891
- currentDialog ?? void 0,
3892
- mergedContentCache
3893
- );
3553
+ const staticContexts = await buildStaticContextsWithToolsPrewarm(state, dispatch, agentConfigForCall, currentDialog ?? undefined, mergedContentCache);
3894
3554
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-static-context-ready", {
3895
3555
  model: agentConfigForCall.model,
3896
3556
  responseApi: false
@@ -3900,20 +3560,21 @@ ${info.actionHint}` : streamError;
3900
3560
  });
3901
3561
  let appendTempUserInput = true;
3902
3562
  let activeTurnUserMessageId = args.userMessageId;
3903
- let currentParentMessageId = parentMessageId ?? void 0;
3563
+ let currentParentMessageId = parentMessageId ?? undefined;
3904
3564
  const w = typeof globalThis !== "undefined" && globalThis.window ? globalThis.window : null;
3905
- if (w) w.__LOOP_STOP_REASON__ = null;
3565
+ if (w)
3566
+ w.__LOOP_STOP_REASON__ = null;
3906
3567
  if (!isRespModel) {
3907
3568
  loopKey = `loop:${dialogId}`;
3908
3569
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-active-controller-adding", {
3909
3570
  responseApi: false
3910
3571
  });
3911
- dispatch(addActiveController({ messageId: loopKey, controller: loopController, dialogKey }));
3572
+ dispatch(addActiveController2({ messageId: loopKey, controller: loopController, dialogKey }));
3912
3573
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-active-controller-added", {
3913
3574
  responseApi: false
3914
3575
  });
3915
3576
  }
3916
- for (; ; ) {
3577
+ for (;; ) {
3917
3578
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-loop-entered", {
3918
3579
  responseApi: false
3919
3580
  });
@@ -3924,7 +3585,8 @@ ${info.actionHint}` : streamError;
3924
3585
  thunkSignalAborted: thunkApi.signal.aborted,
3925
3586
  responseApi: false
3926
3587
  });
3927
- if (w) w.__LOOP_STOP_REASON__ = "aborted";
3588
+ if (w)
3589
+ w.__LOOP_STOP_REASON__ = "aborted";
3928
3590
  return { aborted: true };
3929
3591
  }
3930
3592
  const loopState = getState();
@@ -3935,13 +3597,11 @@ ${info.actionHint}` : streamError;
3935
3597
  elapsedMs: now - startTime,
3936
3598
  responseApi: false
3937
3599
  });
3938
- if (w) w.__LOOP_STOP_REASON__ = "timeout";
3600
+ if (w)
3601
+ w.__LOOP_STOP_REASON__ = "timeout";
3939
3602
  break;
3940
3603
  }
3941
- const accessError = validateAccessAndBalance(
3942
- agentConfigForCall,
3943
- loopState
3944
- );
3604
+ const accessError = validateAccessAndBalance(agentConfigForCall, loopState);
3945
3605
  if (accessError) {
3946
3606
  const accessErrorReason = classifyQuickChatAccessError(accessError);
3947
3607
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-access-error-before-context", {
@@ -3954,23 +3614,12 @@ ${info.actionHint}` : streamError;
3954
3614
  reason: accessErrorReason,
3955
3615
  responseApi: false
3956
3616
  });
3957
- await finalizeQuickChatAgentTurnFailure(
3958
- dispatch,
3959
- runtimeDialogKey,
3960
- agentKey,
3961
- new Error(accessError)
3962
- );
3617
+ await finalizeQuickChatAgentTurnFailure(dispatch, runtimeDialogKey, agentKey, new Error(accessError));
3963
3618
  }
3964
3619
  setLoopStopReason("error");
3965
3620
  return rejectWithValue(accessError);
3966
3621
  }
3967
- const willSkipDynamicContext = canUseQuickChatEmptyDynamicContexts(
3968
- quickChatPerfStartedAt,
3969
- userInput,
3970
- runtimeOptions,
3971
- currentDialog,
3972
- agentConfigForCall
3973
- );
3622
+ const willSkipDynamicContext = canUseQuickChatEmptyDynamicContexts(quickChatPerfStartedAt, userInput, runtimeOptions, currentDialog, agentConfigForCall);
3974
3623
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-dynamic-context-decision", {
3975
3624
  hasRuntimeOptions: !!requestedRuntimeOptions,
3976
3625
  isSimpleTextInput: isSimpleTextInput(userInput),
@@ -3978,36 +3627,16 @@ ${info.actionHint}` : streamError;
3978
3627
  willSkipDynamicContext,
3979
3628
  responseApi: false
3980
3629
  });
3981
- const dynamicContexts = willSkipDynamicContext ? (logQuickChatPerfStage2(
3982
- quickChatPerfStartedAt,
3983
- "stream-agent-dynamic-context-skipped",
3984
- {
3985
- reason: "simple-quick-chat-first-turn",
3986
- responseApi: false
3987
- }
3988
- ), EMPTY_DYNAMIC_CONTEXTS) : await buildDynamicContextsForTurn(
3989
- loopState,
3990
- dispatch,
3991
- agentConfigForCall,
3992
- userInput,
3993
- runtimeOptions,
3994
- mergedContentCache,
3995
- dialogKey,
3996
- quickChatPerfStartedAt,
3997
- serverBase
3998
- );
3630
+ const dynamicContexts = willSkipDynamicContext ? (logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-dynamic-context-skipped", {
3631
+ reason: "simple-quick-chat-first-turn",
3632
+ responseApi: false
3633
+ }), EMPTY_DYNAMIC_CONTEXTS) : await buildDynamicContextsForTurn(loopState, dispatch, agentConfigForCall, userInput, runtimeOptions, mergedContentCache, dialogKey, quickChatPerfStartedAt, serverBase);
3999
3634
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-dynamic-context-ready", {
4000
3635
  responseApi: false
4001
3636
  });
4002
- const contexts = withRequestContextBlocks(
4003
- mergeContexts(staticContexts, dynamicContexts),
4004
- effectiveContextBlocks
4005
- );
3637
+ const contexts = withRequestContextBlocks(mergeContexts(staticContexts, dynamicContexts), effectiveContextBlocks);
4006
3638
  const rawMessages = selectAdmittedMessages(selectAllMsgs(loopState, dialogId));
4007
- let visibleMessages = buildAgentViewMessages(
4008
- rawMessages,
4009
- agentConfigForCall.dbKey
4010
- );
3639
+ let visibleMessages = buildAgentViewMessages(rawMessages, agentConfigForCall.dbKey);
4011
3640
  if (appendTempUserInput && hasAgentRunUserInputContent(agentRunUserInput)) {
4012
3641
  if (!isLastMessageMatchingUserInput(visibleMessages, agentRunUserInput)) {
4013
3642
  const tempId = `__tmp_user_${Date.now()}`;
@@ -4027,12 +3656,9 @@ ${info.actionHint}` : streamError;
4027
3656
  }
4028
3657
  const requestUserInput = snapshotUserBatchInput(selectAllMsgs(loopState, dialogId));
4029
3658
  const cleanedMessages = filterAndCleanMessages(visibleMessages);
4030
- const ctxWindow = resolveAgentContextWindow(agentConfigForCall);
3659
+ const ctxWindow = resolveAgentContextWindow3(agentConfigForCall);
4031
3660
  const messagesBeforeStrip = compressOldToolResults(cleanedMessages);
4032
- const preprocessedResult = await stripImagePartsForTextOnlyAgent(
4033
- messagesBeforeStrip,
4034
- agentConfigForCall
4035
- );
3661
+ const preprocessedResult = await stripImagePartsForTextOnlyAgent(messagesBeforeStrip, agentConfigForCall);
4036
3662
  notifyOmittedImagesIfPresent({
4037
3663
  downgraded: preprocessedResult.downgraded,
4038
3664
  messagesBeforeStrip,
@@ -4050,35 +3676,27 @@ ${info.actionHint}` : streamError;
4050
3676
  preserveLatestUserByProjection: true
4051
3677
  }, { ...turnThunkApi, signal: loopController.signal }),
4052
3678
  build: async () => {
4053
- const summaryConfig = selectById(getState(), dialogKey);
3679
+ const summaryConfig = selectById2(getState(), dialogKey);
4054
3680
  const refreshedContexts = { ...contexts, dialogSummary: summaryConfig?.summary || null };
4055
3681
  const processedMessages = projectSummaryHistory(preprocessedResult.messages, summaryConfig?.summary, summaryConfig?.summarizedBeforeId);
4056
- let firstDynamicIdx = processedMessages.findIndex(
4057
- (m) => m.id && !initialHistoryIds.has(m.id)
4058
- );
4059
- if (firstDynamicIdx === -1) firstDynamicIdx = processedMessages.length;
4060
- let stableMessages2 = processedMessages.slice(0, firstDynamicIdx);
4061
- let dynamicMessages2 = processedMessages.slice(firstDynamicIdx);
4062
- const bodyData2 = generateRequestBody({
3682
+ let firstDynamicIdx = processedMessages.findIndex((m) => m.id && !initialHistoryIds.has(m.id));
3683
+ if (firstDynamicIdx === -1)
3684
+ firstDynamicIdx = processedMessages.length;
3685
+ let stableMessages = processedMessages.slice(0, firstDynamicIdx);
3686
+ let dynamicMessages = processedMessages.slice(firstDynamicIdx);
3687
+ const bodyData = generateRequestBody({
4063
3688
  agentConfig: effectiveAgentConfig,
4064
- messages: dynamicMessages2,
4065
- stableMessages: stableMessages2,
3689
+ messages: dynamicMessages,
3690
+ stableMessages,
4066
3691
  userInput: userInputText,
4067
3692
  contexts: refreshedContexts
4068
3693
  });
4069
- const finalBody = await inlineImageUrlsForCustomProvider(
4070
- buildFinalCompletionsRequestBody(
4071
- bodyData2,
4072
- agentConfigForCall,
4073
- shouldDisableQuickChatToolsForDirectAnswer(quickChatPerfStartedAt, userInput, runtimeOptions, currentDialog)
4074
- ),
4075
- {
4076
- shouldInline: shouldInlineImageUrlsForAgent(agentConfigForCall),
4077
- serverUrl: currentServer,
4078
- signal: loopController.signal
4079
- }
4080
- );
4081
- return { value: { bodyData: finalBody, dynamicMessages: dynamicMessages2, stableMessages: stableMessages2 }, wireBodies: [buildEmptyCompletionRepairBody(finalBody)] };
3694
+ const finalBody = await inlineImageUrlsForCustomProvider(buildFinalCompletionsRequestBody(bodyData, agentConfigForCall, shouldDisableQuickChatToolsForDirectAnswer(quickChatPerfStartedAt, userInput, runtimeOptions, currentDialog)), {
3695
+ shouldInline: shouldInlineImageUrlsForAgent(agentConfigForCall),
3696
+ serverUrl: currentServer,
3697
+ signal: loopController.signal
3698
+ });
3699
+ return { value: { bodyData: finalBody, dynamicMessages, stableMessages }, wireBodies: [buildEmptyCompletionRepairBody(finalBody)] };
4082
3700
  }
4083
3701
  });
4084
3702
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-model-request-starting", {
@@ -4086,21 +3704,12 @@ ${info.actionHint}` : streamError;
4086
3704
  dynamicMessageCount: dynamicMessages.length,
4087
3705
  stableMessageCount: stableMessages.length
4088
3706
  });
4089
- const disableToolsForThisRequest = shouldDisableQuickChatToolsForDirectAnswer(
4090
- quickChatPerfStartedAt,
4091
- userInput,
4092
- runtimeOptions,
4093
- currentDialog
4094
- );
3707
+ const disableToolsForThisRequest = shouldDisableQuickChatToolsForDirectAnswer(quickChatPerfStartedAt, userInput, runtimeOptions, currentDialog);
4095
3708
  if (disableToolsForThisRequest) {
4096
- logQuickChatPerfStage2(
4097
- quickChatPerfStartedAt,
4098
- "stream-agent-tools-disabled-for-direct-answer",
4099
- {
4100
- responseApi: false,
4101
- toolCount: Array.isArray(agentConfigForCall.tools) ? agentConfigForCall.tools.length : 0
4102
- }
4103
- );
3709
+ logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-tools-disabled-for-direct-answer", {
3710
+ responseApi: false,
3711
+ toolCount: Array.isArray(agentConfigForCall.tools) ? agentConfigForCall.tools.length : 0
3712
+ });
4104
3713
  }
4105
3714
  const meta = await dispatch(runPendingUserBatchRequest({
4106
3715
  dialogKey,
@@ -4122,8 +3731,10 @@ ${info.actionHint}` : streamError;
4122
3731
  });
4123
3732
  }
4124
3733
  })).unwrap();
4125
- if (isTurnAborted()) return { aborted: true };
4126
- if (!meta) throw new Error("Model request returned no result; reply did not complete");
3734
+ if (isTurnAborted())
3735
+ return { aborted: true };
3736
+ if (!meta)
3737
+ throw new Error("Model request returned no result; reply did not complete");
4127
3738
  logQuickChatPerfStage2(quickChatPerfStartedAt, "stream-agent-model-request-finished", {
4128
3739
  responseApi: false,
4129
3740
  hasToolCalls: meta.hasToolCalls,
@@ -4131,17 +3742,19 @@ ${info.actionHint}` : streamError;
4131
3742
  hasPendingInteraction: meta.hasPendingInteraction
4132
3743
  });
4133
3744
  appendTempUserInput = false;
4134
- currentParentMessageId = void 0;
3745
+ currentParentMessageId = undefined;
4135
3746
  totalTurnUsage = updateTotalUsage(totalTurnUsage, meta.usage);
4136
3747
  if (meta.hasHandedOff) {
4137
3748
  if (!requestParentMessageId && meta.messageId) {
4138
3749
  dispatch(removeTransientMessage(meta.messageId));
4139
3750
  }
4140
- if (w) w.__LOOP_STOP_REASON__ = "handoff";
3751
+ if (w)
3752
+ w.__LOOP_STOP_REASON__ = "handoff";
4141
3753
  break;
4142
3754
  }
4143
3755
  if (meta.hasPendingInteraction) {
4144
- if (w) w.__LOOP_STOP_REASON__ = "pending";
3756
+ if (w)
3757
+ w.__LOOP_STOP_REASON__ = "pending";
4145
3758
  break;
4146
3759
  }
4147
3760
  if (!loopController.signal.aborted && !thunkApi.signal.aborted) {
@@ -4149,40 +3762,42 @@ ${info.actionHint}` : streamError;
4149
3762
  dialogKey,
4150
3763
  signal: loopController.signal
4151
3764
  })).unwrap();
4152
- if (loopController.signal.aborted || thunkApi.signal.aborted) break;
3765
+ if (loopController.signal.aborted || thunkApi.signal.aborted)
3766
+ break;
4153
3767
  if (admitted.length) {
4154
3768
  activeTurnUserMessageId = admitted[admitted.length - 1].id;
4155
3769
  continue;
4156
3770
  }
4157
3771
  }
4158
3772
  const afterTurnState = getState();
4159
- const queuedMessages = selectPendingUserInputQueue(afterTurnState, dialogKey);
3773
+ const queuedMessages = selectPendingUserInputQueue2(afterTurnState, dialogKey);
4160
3774
  if (queuedMessages.length > 0) {
4161
3775
  const queuedText = queuedMessages[0];
4162
- const currentDialogConfig = selectDialogConfigByKey(afterTurnState, dialogKey) ?? selectCurrentDialogConfig(afterTurnState);
3776
+ const currentDialogConfig = selectDialogConfigByKey2(afterTurnState, dialogKey) ?? selectCurrentDialogConfig2(afterTurnState);
4163
3777
  if (!currentDialogConfig) {
4164
- dispatch(clearPendingUserInputQueue({ dialogKey }));
3778
+ dispatch(clearPendingUserInputQueue2({ dialogKey }));
4165
3779
  break;
4166
3780
  }
4167
- const persisted = await dispatch(
4168
- prepareAndPersistUserMessage({
4169
- userInput: queuedText,
4170
- dialogConfig: currentDialogConfig
4171
- })
4172
- ).unwrap();
4173
- dispatch(dequeueUserInput({ dialogKey }));
3781
+ const persisted = await dispatch(prepareAndPersistUserMessage({
3782
+ userInput: queuedText,
3783
+ dialogConfig: currentDialogConfig
3784
+ })).unwrap();
3785
+ dispatch(dequeueUserInput2({ dialogKey }));
4174
3786
  activeTurnUserMessageId = persisted?.id;
4175
3787
  continue;
4176
3788
  }
4177
3789
  if (!meta.hasToolCalls) {
4178
- if (w) w.__LOOP_STOP_REASON__ = "done";
3790
+ if (w)
3791
+ w.__LOOP_STOP_REASON__ = "done";
4179
3792
  break;
4180
3793
  }
4181
3794
  }
4182
- if (isTurnAborted()) return { aborted: true };
4183
- if (!modelRequestStarted) throw new Error("Model request did not start; reply did not complete");
3795
+ if (isTurnAborted())
3796
+ return { aborted: true };
3797
+ if (!modelRequestStarted)
3798
+ throw new Error("Model request did not start; reply did not complete");
4184
3799
  return {
4185
- usage: totalTurnUsage ?? void 0
3800
+ usage: totalTurnUsage ?? undefined
4186
3801
  };
4187
3802
  } catch (error) {
4188
3803
  if (isTurnAborted(error)) {
@@ -4192,13 +3807,11 @@ ${info.actionHint}` : streamError;
4192
3807
  remoteTransientMessageFinalized = true;
4193
3808
  }
4194
3809
  const w = typeof globalThis !== "undefined" && globalThis.window ? globalThis.window : null;
4195
- if (w) w.__LOOP_STOP_REASON__ = "aborted";
3810
+ if (w)
3811
+ w.__LOOP_STOP_REASON__ = "aborted";
4196
3812
  return { aborted: true };
4197
3813
  }
4198
- console.error(
4199
- `Error in streamAgentChatTurn for [${agentKey}]:`,
4200
- error
4201
- );
3814
+ console.error(`Error in streamAgentChatTurn for [${agentKey}]:`, error);
4202
3815
  if (remoteTransientMessageId && !remoteTransientMessageFinalized) {
4203
3816
  dispatch(finalizeTransientMessageOnError({
4204
3817
  id: remoteTransientMessageId,
@@ -4208,12 +3821,7 @@ ${info.actionHint}` : streamError;
4208
3821
  setLoopStopReason("error");
4209
3822
  }
4210
3823
  if (quickChatPerfStartedAt && runtimeDialogKey && !modelRequestStarted && !remoteTransientMessageId) {
4211
- await finalizeQuickChatAgentTurnFailure(
4212
- dispatch,
4213
- runtimeDialogKey,
4214
- agentKey,
4215
- error
4216
- );
3824
+ await finalizeQuickChatAgentTurnFailure(dispatch, runtimeDialogKey, agentKey, error);
4217
3825
  } else if (!isTurnAborted(error)) {
4218
3826
  setLoopStopReason("error");
4219
3827
  }
@@ -4224,21 +3832,20 @@ ${info.actionHint}` : streamError;
4224
3832
  message: error.message
4225
3833
  });
4226
3834
  }
4227
- return rejectWithValue(
4228
- error?.message || "An unexpected error occurred in streamAgentChatTurn."
4229
- );
3835
+ return rejectWithValue(error?.message || "An unexpected error occurred in streamAgentChatTurn.");
4230
3836
  } finally {
4231
3837
  batchExecution.dispose();
4232
3838
  clearGateTurn(secretGateTurnId);
4233
- for (const id of secretGateAnchors) dispatch(removeTransientMessage(id));
4234
- clearDialogTurnPhase({ dialogKey: runtimeDialogKey ?? void 0, turnId: turnPhaseTurnId ?? void 0 });
3839
+ for (const id of secretGateAnchors)
3840
+ dispatch(removeTransientMessage(id));
3841
+ clearDialogTurnPhase({ dialogKey: runtimeDialogKey ?? undefined, turnId: turnPhaseTurnId ?? undefined });
4235
3842
  if (loopKey && runtimeDialogKey) {
4236
- dispatch(removeActiveController({ messageId: loopKey, dialogKey: runtimeDialogKey }));
3843
+ dispatch(removeActiveController2({ messageId: loopKey, dialogKey: runtimeDialogKey }));
4237
3844
  } else if (loopKey) {
4238
- dispatch(removeActiveController(loopKey));
3845
+ dispatch(removeActiveController2(loopKey));
4239
3846
  }
4240
3847
  if (turnAborted) {
4241
- dispatch(clearPendingUserInputQueue(runtimeDialogKey ? { dialogKey: runtimeDialogKey } : void 0));
3848
+ dispatch(clearPendingUserInputQueue2(runtimeDialogKey ? { dialogKey: runtimeDialogKey } : undefined));
4242
3849
  }
4243
3850
  if (runtimeDialogKey) {
4244
3851
  dispatch(runChatQueueTurnEnd({
@@ -4251,8 +3858,5 @@ ${info.actionHint}` : streamError;
4251
3858
  }
4252
3859
  };
4253
3860
  export {
4254
- classifyLocalTurnStreamError,
4255
- notifiedOmittedImageUserMessageIds,
4256
- notifyOmittedImagesIfPresent,
4257
3861
  streamAgentChatTurnHandler
4258
3862
  };