xkzoom 1.5.4 → 1.5.6

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 (423) hide show
  1. package/README.md +65 -0
  2. package/dist/{chunk-YPKHMAO4.mjs → chunk-22VRM3T3.mjs} +1 -1
  3. package/dist/{chunk-XL3MUGFG.mjs → chunk-2B3A3C2V.mjs} +1 -1
  4. package/dist/{chunk-UQLGVSQH.mjs → chunk-2F65KBU2.mjs} +8 -9
  5. package/dist/chunk-2L4VMCM2.mjs +15 -0
  6. package/dist/{chunk-WQSQXDUL.mjs → chunk-2LN3ODBA.mjs} +1 -1
  7. package/dist/{chunk-OBYPZT2S.mjs → chunk-2YB6BHIB.mjs} +9 -9
  8. package/dist/chunk-35SKU3FL.mjs +279 -0
  9. package/dist/{chunk-PETWGCGB.mjs → chunk-3JHD7MGZ.mjs} +2 -2
  10. package/dist/{chunk-PW3ULDNL.mjs → chunk-3QE7GUJC.mjs} +1 -1
  11. package/dist/{chunk-JI67TW4E.mjs → chunk-4XJFA7V3.mjs} +1 -1
  12. package/dist/{chunk-CQUISJWG.mjs → chunk-5G3UUQ36.mjs} +2 -2
  13. package/dist/{chunk-HYSOWPIC.mjs → chunk-6KCPL45H.mjs} +5 -5
  14. package/dist/{chunk-2IQAT3PE.mjs → chunk-6OY3GOUH.mjs} +6 -6
  15. package/dist/{chunk-LBZCBBHU.mjs → chunk-72IPGTJZ.mjs} +1 -1
  16. package/dist/{chunk-TVH4LII3.mjs → chunk-74S3DUNZ.mjs} +1 -1
  17. package/dist/{chunk-MPGMU75K.mjs → chunk-7C7HREZO.mjs} +12 -12
  18. package/dist/{chunk-BFSOQ5IG.mjs → chunk-7HQEB7IJ.mjs} +3 -3
  19. package/dist/{chunk-3VA3YDYL.mjs → chunk-7TKZKTS5.mjs} +1 -1
  20. package/dist/{chunk-M3ISDSQP.mjs → chunk-A4BZZNPW.mjs} +5 -5
  21. package/dist/{chunk-BJ6YI2DJ.mjs → chunk-AEE3DM6S.mjs} +1 -1
  22. package/dist/{chunk-4JXTPCOE.mjs → chunk-ANGNUW6F.mjs} +5 -5
  23. package/dist/{chunk-GZZ7KO57.mjs → chunk-BJFTC4GW.mjs} +21 -1
  24. package/dist/{chunk-GYZ4IXUD.mjs → chunk-CLN4OVFM.mjs} +3 -6
  25. package/dist/{chunk-3KJHUTOO.mjs → chunk-CLVSQ3FG.mjs} +2 -2
  26. package/dist/{chunk-IKQ7CLX3.mjs → chunk-CSKP6E6Y.mjs} +2 -2
  27. package/dist/{chunk-LWCO2YNI.mjs → chunk-CVWDLRQI.mjs} +1 -1
  28. package/dist/{chunk-FG6QCRVN.mjs → chunk-D4TNMY2O.mjs} +2 -2
  29. package/dist/{chunk-FLVJABFP.mjs → chunk-DODTDJSF.mjs} +10 -8
  30. package/dist/{chunk-MWRQORKQ.mjs → chunk-E36MAP7Y.mjs} +1 -1
  31. package/dist/{chunk-CFZVBILR.mjs → chunk-EHL345OC.mjs} +4 -4
  32. package/dist/chunk-F3Y7WDC6.mjs +108 -0
  33. package/dist/{chunk-Q33JD64H.mjs → chunk-FCK6QFJB.mjs} +1 -1
  34. package/dist/{chunk-3ZH273T7.mjs → chunk-FEEEY457.mjs} +71 -55
  35. package/dist/{chunk-MDZUWIBH.mjs → chunk-G3E2E6DD.mjs} +38 -38
  36. package/dist/{chunk-WXELBVXY.mjs → chunk-GC2H3KNZ.mjs} +1 -1
  37. package/dist/{chunk-5SE4JOKE.mjs → chunk-GHWAAAG6.mjs} +309 -262
  38. package/dist/{chunk-5YEFG7BF.mjs → chunk-GNDVHDPO.mjs} +52 -52
  39. package/dist/chunk-H4NINXMV.mjs +95 -0
  40. package/dist/{chunk-TQBVFKCT.mjs → chunk-H6W42R46.mjs} +194 -154
  41. package/dist/chunk-H7ILBOZU.mjs +48 -0
  42. package/dist/{chunk-7LEEVP5O.mjs → chunk-H7QNACAJ.mjs} +12 -12
  43. package/dist/chunk-HCYIE2PR.mjs +130 -0
  44. package/dist/{chunk-E2TTUY6R.mjs → chunk-HHPHIVCC.mjs} +11 -11
  45. package/dist/{chunk-P262PAGZ.mjs → chunk-HLYVEYML.mjs} +15 -2
  46. package/dist/{chunk-GZJMFCRG.mjs → chunk-HNYI45WM.mjs} +23 -4
  47. package/dist/{chunk-JFFBD5TV.mjs → chunk-HOII5XBJ.mjs} +17 -17
  48. package/dist/{chunk-T23H5D4O.mjs → chunk-HPZG5VVI.mjs} +3 -9
  49. package/dist/chunk-HQHICFPO.mjs +58 -0
  50. package/dist/{chunk-DRY7AJMM.mjs → chunk-HQPA2MV5.mjs} +7 -7
  51. package/dist/{chunk-NJAPWQ4D.mjs → chunk-ICKBF7KF.mjs} +2 -60
  52. package/dist/{chunk-HAI7DJD2.mjs → chunk-IEF2AMNW.mjs} +7 -7
  53. package/dist/{chunk-VIZQURO5.mjs → chunk-IGJFAE72.mjs} +9 -9
  54. package/dist/{chunk-IT2GAHAL.mjs → chunk-IHMPR5HT.mjs} +1 -1
  55. package/dist/{chunk-PJKLQF3K.mjs → chunk-INFZEMQK.mjs} +1 -1
  56. package/dist/{chunk-MKYCBV3H.mjs → chunk-J4FQVXEA.mjs} +7 -7
  57. package/dist/{chunk-27BXVTXH.mjs → chunk-JN5EMEXS.mjs} +1 -1
  58. package/dist/{chunk-4WWT6OC2.mjs → chunk-JTKSYLZE.mjs} +26 -48
  59. package/dist/{chunk-ZTKJR7OC.mjs → chunk-K5IQLMJQ.mjs} +4 -4
  60. package/dist/{chunk-GIAML5K5.mjs → chunk-K5JMXCH5.mjs} +1 -1
  61. package/dist/{chunk-JJKRD5DL.mjs → chunk-KBEY4ZQV.mjs} +4 -4
  62. package/dist/{chunk-EL6TOIFZ.mjs → chunk-KHQPC6I7.mjs} +1 -16
  63. package/dist/{chunk-VNEPNUBZ.mjs → chunk-L3PV2ZNB.mjs} +15 -15
  64. package/dist/{chunk-MQKREMOB.mjs → chunk-L7N2B4LX.mjs} +8 -8
  65. package/dist/{chunk-PS6X3CND.mjs → chunk-LKSRZTSL.mjs} +1 -0
  66. package/dist/{chunk-DCSERRXG.mjs → chunk-LNPOTNGJ.mjs} +1 -1
  67. package/dist/chunk-LOMDPHVQ.mjs +42 -0
  68. package/dist/chunk-LQHI5VK2.mjs +26 -0
  69. package/dist/{chunk-J5AXFEDQ.mjs → chunk-LTTSUVF5.mjs} +52 -52
  70. package/dist/{chunk-LESS4N25.mjs → chunk-LV3CI5A4.mjs} +5 -5
  71. package/dist/{chunk-JG3K4N5B.mjs → chunk-M3E2R3PT.mjs} +1 -1
  72. package/dist/{chunk-WPMJCKI2.mjs → chunk-M7DB4RAC.mjs} +9 -9
  73. package/dist/{chunk-COYZO24J.mjs → chunk-MCD5TOFD.mjs} +1 -1
  74. package/dist/{chunk-AP4WVS6L.mjs → chunk-MCJPAZBQ.mjs} +1 -1
  75. package/dist/{chunk-T6XDJ2QQ.mjs → chunk-MGIGU4G6.mjs} +119 -18
  76. package/dist/{chunk-ZMQ3UOGP.mjs → chunk-MMWLRPKT.mjs} +13 -1
  77. package/dist/{chunk-NIU6GWKB.mjs → chunk-MNLMVNF5.mjs} +5 -5
  78. package/dist/{chunk-W75Z6CZR.mjs → chunk-MXKSS63B.mjs} +2 -2
  79. package/dist/{chunk-TADSGGK2.mjs → chunk-N4X2MAF2.mjs} +14 -28
  80. package/dist/{chunk-E7BFLHLM.mjs → chunk-NDPDPELV.mjs} +1 -16
  81. package/dist/{chunk-24GJWXMG.mjs → chunk-NI2PDCVA.mjs} +3 -3
  82. package/dist/{chunk-BSG6WLML.mjs → chunk-NI4N35JN.mjs} +1 -1
  83. package/dist/{chunk-Z2JNJLJM.mjs → chunk-NLUF66E7.mjs} +1 -1
  84. package/dist/{chunk-RKZ56GST.mjs → chunk-NRPE77A3.mjs} +2 -2
  85. package/dist/{chunk-76TKUYY3.mjs → chunk-NTVWS2MO.mjs} +6 -6
  86. package/dist/{chunk-YYDDQEY4.mjs → chunk-NV7SYEH7.mjs} +2 -2
  87. package/dist/{chunk-6W4W5JLG.mjs → chunk-NXVXMXL5.mjs} +3 -3
  88. package/dist/{chunk-PINXXWFJ.mjs → chunk-OGT25PYJ.mjs} +1 -1
  89. package/dist/{chunk-3STOFADV.mjs → chunk-OHCBAEML.mjs} +1 -0
  90. package/dist/{chunk-L252ASZW.mjs → chunk-OPTSEYTI.mjs} +1 -1
  91. package/dist/{chunk-B4YKXZ5W.mjs → chunk-OQMIECO2.mjs} +1 -1
  92. package/dist/{chunk-D3N7EHB2.mjs → chunk-PH5QACOX.mjs} +19 -19
  93. package/dist/{chunk-6MOIFLPP.mjs → chunk-PKJLFQRF.mjs} +1 -1
  94. package/dist/{chunk-M5IU6U3O.mjs → chunk-POOU2U4R.mjs} +2 -2
  95. package/dist/{chunk-IGDJGBAI.mjs → chunk-PPMT66BN.mjs} +3 -3
  96. package/dist/{chunk-RZOILUDC.mjs → chunk-PSZPHCUP.mjs} +1 -1
  97. package/dist/{chunk-MXXTDG5V.mjs → chunk-PVSCARHF.mjs} +1 -1
  98. package/dist/chunk-PW6NSDMI.mjs +117 -0
  99. package/dist/{chunk-NHICONJ3.mjs → chunk-PZAMMLMJ.mjs} +3 -3
  100. package/dist/{chunk-IDQ5B572.mjs → chunk-QDN74R5G.mjs} +5 -5
  101. package/dist/{chunk-VWAUDB4X.mjs → chunk-QHIZRYTO.mjs} +2 -2
  102. package/dist/{chunk-2DR5RT3I.mjs → chunk-QITZ7SAD.mjs} +499 -943
  103. package/dist/{chunk-N2CMVW47.mjs → chunk-QRHBGABQ.mjs} +7 -3
  104. package/dist/{chunk-F35EHL5U.mjs → chunk-RM6GZ2SF.mjs} +7 -7
  105. package/dist/{chunk-JXDHNASC.mjs → chunk-RUMRGCYN.mjs} +85 -42
  106. package/dist/{chunk-K7RZQIPZ.mjs → chunk-S54MBJWY.mjs} +6 -4
  107. package/dist/{chunk-MBOWNG3A.mjs → chunk-S573TMN6.mjs} +2 -2
  108. package/dist/{chunk-UFV3WER4.mjs → chunk-SJ5LNKAH.mjs} +1 -1
  109. package/dist/chunk-SJWQGIQU.mjs +99 -0
  110. package/dist/{chunk-KWQEFCOY.mjs → chunk-SMHFMHQ2.mjs} +1 -1
  111. package/dist/{chunk-LGNLS7ZN.mjs → chunk-SPUVJNKO.mjs} +2 -2
  112. package/dist/{chunk-JBKRS62W.mjs → chunk-T3EJW65E.mjs} +6 -6
  113. package/dist/{chunk-6ZVXCJTG.mjs → chunk-TBLUKDLO.mjs} +91 -1
  114. package/dist/{chunk-76MFE24I.mjs → chunk-TKZWE5DB.mjs} +1 -1
  115. package/dist/{chunk-3CPVI6Y2.mjs → chunk-TRSW7QJW.mjs} +1 -1
  116. package/dist/{chunk-UXEZFEB3.mjs → chunk-TSS3NVRA.mjs} +18 -17
  117. package/dist/{chunk-WRZWEAMN.mjs → chunk-TU75ILAE.mjs} +1 -1
  118. package/dist/{chunk-E5LABIPO.mjs → chunk-U2NKGGVL.mjs} +3 -2
  119. package/dist/{chunk-KLQSTA6K.mjs → chunk-U7TPS3MS.mjs} +1 -1
  120. package/dist/chunk-UOCUHKR5.mjs +21 -0
  121. package/dist/{chunk-VA7SUI2L.mjs → chunk-VD4DIRCW.mjs} +1 -1
  122. package/dist/chunk-VHQ5WHXF.mjs +17 -0
  123. package/dist/{chunk-MRTQWCNC.mjs → chunk-VMRVJ2VF.mjs} +9 -9
  124. package/dist/{chunk-MJDJIPB4.mjs → chunk-VRG32WNZ.mjs} +1 -1
  125. package/dist/chunk-W5XO4T4J.mjs +63 -0
  126. package/dist/{chunk-5ZMY6RTR.mjs → chunk-WASHQYUB.mjs} +2 -2
  127. package/dist/{chunk-XNQJRIGR.mjs → chunk-WHP2GNEC.mjs} +66 -15
  128. package/dist/chunk-WI7PS7YW.mjs +79 -0
  129. package/dist/{chunk-GIC2RBVM.mjs → chunk-WMLZDHER.mjs} +51 -33
  130. package/dist/{chunk-4POYX4AW.mjs → chunk-WVTJXJY4.mjs} +1 -1
  131. package/dist/{chunk-KPDVZFJY.mjs → chunk-WYCMXDZT.mjs} +1 -1
  132. package/dist/{chunk-LFZAVCVW.mjs → chunk-XD5XGGQA.mjs} +1 -1
  133. package/dist/{chunk-NEDXMES6.mjs → chunk-YAGU7I25.mjs} +2 -2
  134. package/dist/{chunk-TRMEHTAT.mjs → chunk-YSI3ZONB.mjs} +1 -1
  135. package/dist/chunk-YTBKWX7J.mjs +102 -0
  136. package/dist/chunk-YYUB3HQR.mjs +119 -0
  137. package/dist/{chunk-CTKIQWTE.mjs → chunk-ZOJEC5RT.mjs} +1 -1
  138. package/dist/{chunk-2VSERWT6.mjs → chunk-ZXJY3JIP.mjs} +2 -2
  139. package/dist/index.js +7773 -6876
  140. package/dist/index.mjs +271 -256
  141. package/dist/mobile/action-planner.js +492 -389
  142. package/dist/mobile/action-planner.mjs +155 -155
  143. package/dist/mobile/agent-capabilities.js +492 -389
  144. package/dist/mobile/agent-capabilities.mjs +155 -155
  145. package/dist/mobile/agent-shop/handlers.mjs +5 -5
  146. package/dist/mobile/agents-watch.js +346 -0
  147. package/dist/mobile/agents-watch.mjs +13 -0
  148. package/dist/mobile/anthropic-incremental-deliver.mjs +4 -4
  149. package/dist/mobile/anthropic-messages-turn-runner.js +1160 -887
  150. package/dist/mobile/anthropic-messages-turn-runner.mjs +172 -170
  151. package/dist/mobile/anthropic-owned-tool-executor.js +542 -435
  152. package/dist/mobile/anthropic-owned-tool-executor.mjs +169 -169
  153. package/dist/mobile/anthropic-provider-adapter.js +23 -18
  154. package/dist/mobile/anthropic-provider-adapter.mjs +3 -2
  155. package/dist/mobile/api.js +236 -147
  156. package/dist/mobile/api.mjs +84 -83
  157. package/dist/mobile/auth.mjs +1 -1
  158. package/dist/mobile/bucket-events/emit-bucket-frame.js +327 -0
  159. package/dist/mobile/bucket-events/emit-bucket-frame.mjs +8 -3
  160. package/dist/mobile/bucket-events/register-bucket-gateway-bridge.js +320 -3
  161. package/dist/mobile/bucket-events/register-bucket-gateway-bridge.mjs +9 -4
  162. package/dist/mobile/channel.mjs +2 -2
  163. package/dist/mobile/chinese-monologue-deliver-partition.js +21 -1
  164. package/dist/mobile/chinese-monologue-deliver-partition.mjs +1 -1
  165. package/dist/mobile/context-compact/compact-artifact-enrich.mjs +18 -18
  166. package/dist/mobile/context-compact/compact-artifact-writer.mjs +3 -3
  167. package/dist/mobile/context-compact/compact-engine-artifacts.mjs +5 -5
  168. package/dist/mobile/context-compact/compact-memory-distill-job.mjs +3 -3
  169. package/dist/mobile/context-compact/compact-message-collector.mjs +2 -2
  170. package/dist/mobile/context-compact/compact-orchestrator.js +8 -22
  171. package/dist/mobile/context-compact/compact-orchestrator.mjs +41 -41
  172. package/dist/mobile/context-compact/compact-resume-prefetch.mjs +3 -3
  173. package/dist/mobile/context-compact/compact-summarizer-engine-artifact.mjs +20 -20
  174. package/dist/mobile/context-compact/compact-summarizer-llm-request.js +2 -1
  175. package/dist/mobile/context-compact/compact-summarizer-llm-request.mjs +11 -11
  176. package/dist/mobile/context-compact/compact-summarizer-llm.js +5 -19
  177. package/dist/mobile/context-compact/compact-summarizer-llm.mjs +12 -12
  178. package/dist/mobile/context-compact/compact-summarizer.js +5 -19
  179. package/dist/mobile/context-compact/compact-summarizer.mjs +17 -17
  180. package/dist/mobile/context-compact/compact-visible-tool-chain.mjs +2 -2
  181. package/dist/mobile/context-compact/compact-write-verifier.mjs +2 -2
  182. package/dist/mobile/context-compact/context-budget-gate.js +111 -84
  183. package/dist/mobile/context-compact/context-budget-gate.mjs +5 -5
  184. package/dist/mobile/context-compact/native-transcript-budget.js +151 -79
  185. package/dist/mobile/context-compact/native-transcript-budget.mjs +7 -3
  186. package/dist/mobile/context-compact/runtime-compact-hook.js +592 -468
  187. package/dist/mobile/context-compact/runtime-compact-hook.mjs +158 -158
  188. package/dist/mobile/dispatch/compact-resume-contract.js +567 -0
  189. package/dist/mobile/dispatch/compact-resume-contract.mjs +39 -0
  190. package/dist/mobile/dispatch/dispatch-context-assembly.js +588 -0
  191. package/dist/mobile/dispatch/dispatch-context-assembly.mjs +20 -0
  192. package/dist/mobile/dispatch/dispatch-route.js +547 -0
  193. package/dist/mobile/dispatch/dispatch-route.mjs +23 -0
  194. package/dist/mobile/dispatch/dispatch-streaming.js +51 -0
  195. package/dist/mobile/dispatch/dispatch-streaming.mjs +9 -0
  196. package/dist/mobile/dispatch/finalize-contract.js +147 -0
  197. package/dist/mobile/dispatch/finalize-contract.mjs +38 -0
  198. package/dist/mobile/dispatch/inbound-prep.js +671 -0
  199. package/dist/mobile/dispatch/inbound-prep.mjs +31 -0
  200. package/dist/mobile/dispatch/interrupted-snapshot.js +190 -0
  201. package/dist/mobile/dispatch/interrupted-snapshot.mjs +11 -0
  202. package/dist/mobile/dispatch/mobile-dispatch-error.js +41 -0
  203. package/dist/mobile/dispatch/mobile-dispatch-error.mjs +7 -0
  204. package/dist/mobile/dispatch/native-turn-executor.js +42662 -0
  205. package/dist/mobile/dispatch/native-turn-executor.mjs +320 -0
  206. package/dist/mobile/dispatch/native-turn-route.js +1465 -0
  207. package/dist/mobile/dispatch/native-turn-route.mjs +34 -0
  208. package/dist/mobile/dispatch/native-turn-transcript.js +1134 -0
  209. package/dist/mobile/dispatch/native-turn-transcript.mjs +29 -0
  210. package/dist/mobile/group/conductor-llm.js +5 -19
  211. package/dist/mobile/group/conductor-llm.mjs +15 -15
  212. package/dist/mobile/group/conductor-plan-llm.js +5 -19
  213. package/dist/mobile/group/conductor-plan-llm.mjs +22 -22
  214. package/dist/mobile/group/delivery-verification.js +61 -13
  215. package/dist/mobile/group/delivery-verification.mjs +4 -4
  216. package/dist/mobile/group/direct-chat-group-context.mjs +6 -6
  217. package/dist/mobile/group/execution-plan.js +61 -13
  218. package/dist/mobile/group/execution-plan.mjs +5 -5
  219. package/dist/mobile/group/floor-scheduler.mjs +9 -9
  220. package/dist/mobile/group/floor-state-store.mjs +6 -6
  221. package/dist/mobile/group/group-api-handlers.js +3 -0
  222. package/dist/mobile/group/group-api-handlers.mjs +61 -60
  223. package/dist/mobile/group/group-peer-private-context.mjs +5 -5
  224. package/dist/mobile/group/group-session.mjs +25 -25
  225. package/dist/mobile/group/index.js +63 -17
  226. package/dist/mobile/group/index.mjs +51 -50
  227. package/dist/mobile/group/memory-supplement.mjs +9 -9
  228. package/dist/mobile/group/mention.mjs +3 -3
  229. package/dist/mobile/group/normal-group-router.mjs +2 -2
  230. package/dist/mobile/group/orchestrator.js +62 -17
  231. package/dist/mobile/group/orchestrator.mjs +44 -44
  232. package/dist/mobile/group/pipeline-ceo-dept-mention-parse.mjs +3 -3
  233. package/dist/mobile/group/pipeline-handoff-verification.js +4 -10
  234. package/dist/mobile/group/pipeline-handoff-verification.mjs +3 -3
  235. package/dist/mobile/group/pipeline-turn-outcome.js +5 -14
  236. package/dist/mobile/group/pipeline-turn-outcome.mjs +2 -2
  237. package/dist/mobile/group/plan-runtime.js +61 -13
  238. package/dist/mobile/group/plan-runtime.mjs +26 -26
  239. package/dist/mobile/group/relation-distill.mjs +10 -10
  240. package/dist/mobile/group/remarks.mjs +4 -4
  241. package/dist/mobile/group/runtime-integration.js +65 -17
  242. package/dist/mobile/group/runtime-integration.mjs +59 -58
  243. package/dist/mobile/group/team-memory-runtime.mjs +3 -3
  244. package/dist/mobile/group/transcript-projection.js +1 -0
  245. package/dist/mobile/group/transcript-projection.mjs +4 -3
  246. package/dist/mobile/index.js +8046 -7126
  247. package/dist/mobile/index.mjs +256 -241
  248. package/dist/mobile/memory-contract-r1-prefetch.mjs +10 -10
  249. package/dist/mobile/memory-contract-r1.js +1 -1
  250. package/dist/mobile/memory-contract-r1.mjs +1 -1
  251. package/dist/mobile/memory-contract-r5-empty-result.mjs +11 -11
  252. package/dist/mobile/memory-runtime-v2/checkpoint-policy.js +1 -61
  253. package/dist/mobile/memory-runtime-v2/checkpoint-policy.mjs +2 -2
  254. package/dist/mobile/memory-runtime-v2/context-pack.js +16 -2
  255. package/dist/mobile/memory-runtime-v2/context-pack.mjs +2 -2
  256. package/dist/mobile/memory-runtime-v2/eval-runner.js +231 -145
  257. package/dist/mobile/memory-runtime-v2/eval-runner.mjs +20 -14
  258. package/dist/mobile/memory-runtime-v2/evidence-plan.js +233 -147
  259. package/dist/mobile/memory-runtime-v2/evidence-plan.mjs +22 -16
  260. package/dist/mobile/memory-runtime-v2/index.js +242 -147
  261. package/dist/mobile/memory-runtime-v2/index.mjs +58 -46
  262. package/dist/mobile/memory-runtime-v2/local-source-import.mjs +3 -3
  263. package/dist/mobile/memory-runtime-v2/long-run-guard.js +1 -119
  264. package/dist/mobile/memory-runtime-v2/long-run-guard.mjs +3 -3
  265. package/dist/mobile/memory-runtime-v2/memory-control-plane.js +233 -147
  266. package/dist/mobile/memory-runtime-v2/memory-control-plane.mjs +22 -16
  267. package/dist/mobile/memory-runtime-v2/memory-evidence-graph.mjs +2 -2
  268. package/dist/mobile/memory-runtime-v2/memory-readiness.js +232 -146
  269. package/dist/mobile/memory-runtime-v2/memory-readiness.mjs +22 -16
  270. package/dist/mobile/memory-runtime-v2/orchestrator.js +17 -3
  271. package/dist/mobile/memory-runtime-v2/orchestrator.mjs +7 -7
  272. package/dist/mobile/memory-runtime-v2/project-tool-event.mjs +2 -2
  273. package/dist/mobile/memory-runtime-v2/public-api.js +233 -147
  274. package/dist/mobile/memory-runtime-v2/public-api.mjs +23 -17
  275. package/dist/mobile/memory-runtime-v2/retrieval.mjs +2 -2
  276. package/dist/mobile/memory-runtime-v2/run-ledger.js +29 -48
  277. package/dist/mobile/memory-runtime-v2/run-ledger.mjs +7 -1
  278. package/dist/mobile/minimax-m3.js +2 -20
  279. package/dist/mobile/minimax-m3.mjs +3 -9
  280. package/dist/mobile/model-context-window-budget.js +19 -4
  281. package/dist/mobile/model-context-window-budget.mjs +7 -3
  282. package/dist/mobile/model-turn-runner.js +61 -2
  283. package/dist/mobile/model-turn-runner.mjs +12 -6
  284. package/dist/mobile/native-anthropic-messages-stream.js +7 -22
  285. package/dist/mobile/native-anthropic-messages-stream.mjs +12 -12
  286. package/dist/mobile/native-openai-text-stream.js +1 -2
  287. package/dist/mobile/native-openai-text-stream.mjs +3 -3
  288. package/dist/mobile/native-provider-api-key.js +2 -2
  289. package/dist/mobile/native-provider-api-key.mjs +1 -1
  290. package/dist/mobile/native-reply-route.js +25 -4
  291. package/dist/mobile/native-reply-route.mjs +13 -11
  292. package/dist/mobile/native-reply-system-prompt-layers.js +497 -392
  293. package/dist/mobile/native-reply-system-prompt-layers.mjs +155 -155
  294. package/dist/mobile/native-reply-system-prompt.js +1 -0
  295. package/dist/mobile/native-reply-system-prompt.mjs +1 -1
  296. package/dist/mobile/native-reply-transcript.js +125 -0
  297. package/dist/mobile/native-reply-transcript.mjs +7 -2
  298. package/dist/mobile/native-request-diagnostics.js +4 -2
  299. package/dist/mobile/native-request-diagnostics.mjs +3 -1
  300. package/dist/mobile/native-stream-block-emit.mjs +3 -3
  301. package/dist/mobile/openai-completions-turn-runner.js +874 -608
  302. package/dist/mobile/openai-completions-turn-runner.mjs +172 -170
  303. package/dist/mobile/reply-dispatch-warmup.mjs +5 -5
  304. package/dist/mobile/runtime.js +8272 -7353
  305. package/dist/mobile/runtime.mjs +253 -238
  306. package/dist/mobile/session-dispatch/mobile-session-agent-event-bridge.mjs +1 -1
  307. package/dist/mobile/store.mjs +3 -3
  308. package/dist/mobile/stream-inbound/mobile-text-stream-pipeline.js +321 -9
  309. package/dist/mobile/stream-inbound/mobile-text-stream-pipeline.mjs +11 -4
  310. package/dist/mobile/system-prompt-snapshot.mjs +4 -4
  311. package/dist/mobile/tool-result-final-summary.js +145 -0
  312. package/dist/mobile/tool-result-final-summary.mjs +11 -0
  313. package/dist/mobile/tool-use-input-normalize.js +492 -389
  314. package/dist/mobile/tool-use-input-normalize.mjs +158 -158
  315. package/dist/mobile/tools/mobile-compact-tool-bridge.js +492 -389
  316. package/dist/mobile/tools/mobile-compact-tool-bridge.mjs +157 -157
  317. package/dist/mobile/types.js +1 -0
  318. package/dist/mobile/types.mjs +1 -1
  319. package/dist/mobile/websocket.js +327 -0
  320. package/dist/mobile/websocket.mjs +7 -2
  321. package/dist/mobile/workspace-startup-pointer.js +1 -1
  322. package/dist/mobile/workspace-startup-pointer.mjs +1 -1
  323. package/dist/org/dept-context.mjs +4 -4
  324. package/dist/org/index.mjs +8 -8
  325. package/dist/owned-tools/agent-tool-config.mjs +2 -2
  326. package/dist/owned-tools/agents-list.mjs +6 -6
  327. package/dist/owned-tools/ceo-confirm-requirements.mjs +15 -15
  328. package/dist/owned-tools/ceo-decision.js +72 -18
  329. package/dist/owned-tools/ceo-decision.mjs +22 -22
  330. package/dist/owned-tools/ceo-ops-brief.mjs +15 -15
  331. package/dist/owned-tools/ceo-redirect.js +3 -0
  332. package/dist/owned-tools/ceo-redirect.mjs +60 -59
  333. package/dist/owned-tools/commit-stack-lesson.mjs +16 -16
  334. package/dist/owned-tools/compact/execute.js +492 -389
  335. package/dist/owned-tools/compact/execute.mjs +155 -155
  336. package/dist/owned-tools/compact/gateway-tool-factory.js +492 -389
  337. package/dist/owned-tools/compact/gateway-tool-factory.mjs +156 -156
  338. package/dist/owned-tools/compact/registry.js +492 -389
  339. package/dist/owned-tools/compact/registry.mjs +154 -154
  340. package/dist/owned-tools/context-compact.js +8 -22
  341. package/dist/owned-tools/context-compact.mjs +69 -63
  342. package/dist/owned-tools/edit.mjs +2 -2
  343. package/dist/owned-tools/exec-primitives.mjs +2 -2
  344. package/dist/owned-tools/exec.js +112 -9
  345. package/dist/owned-tools/exec.mjs +12 -8
  346. package/dist/owned-tools/groups-history.mjs +10 -10
  347. package/dist/owned-tools/handoff.mjs +21 -21
  348. package/dist/owned-tools/internal-tool-names.js +40 -0
  349. package/dist/owned-tools/internal-tool-names.mjs +9 -0
  350. package/dist/owned-tools/media-asset-library.mjs +2 -2
  351. package/dist/owned-tools/memory-control.mjs +24 -18
  352. package/dist/owned-tools/memory-get.js +7 -3
  353. package/dist/owned-tools/memory-get.mjs +1 -1
  354. package/dist/owned-tools/memory-runtime-eval.js +232 -146
  355. package/dist/owned-tools/memory-runtime-eval.mjs +23 -17
  356. package/dist/owned-tools/message.mjs +7 -7
  357. package/dist/owned-tools/models-list.mjs +2 -2
  358. package/dist/owned-tools/owned-reply.mjs +6 -6
  359. package/dist/owned-tools/owned-tool-payload-failure.js +3 -6
  360. package/dist/owned-tools/owned-tool-payload-failure.mjs +1 -1
  361. package/dist/owned-tools/process-registry.mjs +2 -2
  362. package/dist/owned-tools/process.mjs +3 -3
  363. package/dist/owned-tools/providers/minimax-video-generate.mjs +2 -2
  364. package/dist/owned-tools/providers/minimax-voice.mjs +2 -2
  365. package/dist/owned-tools/read.mjs +2 -2
  366. package/dist/owned-tools/register-owned-providers.mjs +12 -12
  367. package/dist/owned-tools/registry.js +497 -389
  368. package/dist/owned-tools/registry.mjs +158 -153
  369. package/dist/owned-tools/router.js +554 -451
  370. package/dist/owned-tools/router.mjs +154 -154
  371. package/dist/owned-tools/runtime-bridge.js +554 -451
  372. package/dist/owned-tools/runtime-bridge.mjs +156 -156
  373. package/dist/owned-tools/runtime-data.mjs +5 -5
  374. package/dist/owned-tools/session-status.mjs +7 -7
  375. package/dist/owned-tools/sessions-history-resolver.mjs +9 -9
  376. package/dist/owned-tools/sessions-history.mjs +8 -8
  377. package/dist/owned-tools/sessions-list.mjs +6 -6
  378. package/dist/owned-tools/sessions-send.mjs +7 -7
  379. package/dist/owned-tools/skills-create.mjs +6 -6
  380. package/dist/owned-tools/subagents.mjs +7 -7
  381. package/dist/owned-tools/tool-contract-prompt.js +497 -392
  382. package/dist/owned-tools/tool-contract-prompt.mjs +154 -154
  383. package/dist/owned-tools/tool-result-envelope.js +526 -405
  384. package/dist/owned-tools/tool-result-envelope.mjs +159 -159
  385. package/dist/owned-tools/tool-usage-guide.js +492 -389
  386. package/dist/owned-tools/tool-usage-guide.mjs +153 -153
  387. package/dist/owned-tools/tool-validation.mjs +2 -2
  388. package/dist/owned-tools/tts.mjs +6 -6
  389. package/dist/owned-tools/web-smoke.mjs +9 -9
  390. package/dist/owned-tools/write.mjs +2 -2
  391. package/dist/project/file-tool-scope-default.mjs +6 -6
  392. package/dist/project/file-tool-scope.js +1 -1
  393. package/dist/project/file-tool-scope.mjs +1 -1
  394. package/dist/project-pipeline/handlers.js +3 -0
  395. package/dist/project-pipeline/handlers.mjs +60 -59
  396. package/dist/project-pipeline/index.js +3 -0
  397. package/dist/project-pipeline/index.mjs +62 -61
  398. package/dist/project-pipeline/pipeline-routing.mjs +2 -2
  399. package/dist/project-pipeline/post-close-skill-evolution.mjs +5 -5
  400. package/dist/project-pipeline/project-store.mjs +5 -5
  401. package/gateway-core/runtime/reply/chinese-monologue-deliver-partition.cjs +27 -6
  402. package/package.json +2 -2
  403. package/dist/chunk-4IWTTXQE.mjs +0 -113
  404. package/dist/chunk-ETD5LGJY.mjs +0 -25
  405. package/gateway-core/README.md +0 -6
  406. package/dist/{chunk-MGWYJD5Q.mjs → chunk-2YNBEBKQ.mjs} +14 -14
  407. package/dist/{chunk-QM7MTC5Q.mjs → chunk-522D52FC.mjs} +3 -3
  408. package/dist/{chunk-QADC4VKT.mjs → chunk-5MXGINNQ.mjs} +4 -4
  409. package/dist/{chunk-BRJJML7A.mjs → chunk-5NFOBSYF.mjs} +3 -3
  410. package/dist/{chunk-NRJWLPTI.mjs → chunk-6AY6OPO5.mjs} +3 -3
  411. package/dist/{chunk-JA65ZG3H.mjs → chunk-BYGWNFCJ.mjs} +4 -4
  412. package/dist/{chunk-I7O5UR24.mjs → chunk-JX3URYQG.mjs} +4 -4
  413. package/dist/{chunk-2QCX6RPN.mjs → chunk-KCZIK3TH.mjs} +3 -3
  414. package/dist/{chunk-WPLDZLAL.mjs → chunk-L7PMYQN5.mjs} +3 -3
  415. package/dist/{chunk-H2UCPL5O.mjs → chunk-LY7M7Z7M.mjs} +3 -3
  416. package/dist/{chunk-UNZ3D3B3.mjs → chunk-MK32KUVI.mjs} +6 -6
  417. package/dist/{chunk-5LUTMHVL.mjs → chunk-NXKHSX4M.mjs} +3 -3
  418. package/dist/{chunk-QVEQRCOD.mjs → chunk-PIDPHIN6.mjs} +4 -4
  419. package/dist/{chunk-UR6LPERL.mjs → chunk-Q7NYATKS.mjs} +3 -3
  420. package/dist/{chunk-TQOUQIVS.mjs → chunk-V3XUPTZQ.mjs} +3 -3
  421. package/dist/{chunk-HWGRW6YP.mjs → chunk-VS2URZFN.mjs} +3 -3
  422. package/dist/{chunk-CVXJ45WI.mjs → chunk-WTOP2LEF.mjs} +5 -5
  423. package/dist/{chunk-FY2QAWA6.mjs → chunk-YI7E3RUY.mjs} +5 -5
@@ -255,8 +255,8 @@ function isSafeAgentId(raw) {
255
255
  }
256
256
  function assertSafeAgentId(raw) {
257
257
  if (!isSafeAgentId(raw)) {
258
- const preview = typeof raw === "string" ? JSON.stringify(raw).slice(0, 64) : String(raw);
259
- throw new Error(`[XKZOOM] Invalid agentId for path resolution: ${preview}`);
258
+ const preview2 = typeof raw === "string" ? JSON.stringify(raw).slice(0, 64) : String(raw);
259
+ throw new Error(`[XKZOOM] Invalid agentId for path resolution: ${preview2}`);
260
260
  }
261
261
  return raw;
262
262
  }
@@ -1813,7 +1813,7 @@ function formatRuntimeContextStateBlock(input) {
1813
1813
  lines.push("fileScopes: project | agent | memory");
1814
1814
  lines.push("defaultFileScope: agent (pipeline group chat or user project/repo intent \u2192 project at runtime)");
1815
1815
  lines.push(
1816
- "workspaceDiscipline: IDENTITY/SOUL/USER/MEMORY/AGENTS.md live ONLY under agentWorkspace \u2014 use scope=agent or scope=memory; never treat projectRoot as your identity directory."
1816
+ "workspaceDiscipline: IDENTITY/SOUL/USER/MEMORY/AGENTS.md live ONLY under agentWorkspace \u2014 use scope=agent (scope=memory only reads MEMORY.md/USER.md/memory/**); never treat projectRoot as your identity directory."
1817
1817
  );
1818
1818
  lines.push(
1819
1819
  "projectRoot is the active task codebase (scope=project only); agentWorkspace is your persona, memory, and user inbound attachments (media/inbound and file/inbound)."
@@ -1971,6 +1971,20 @@ var init_tool_result_compact = __esm({
1971
1971
  }
1972
1972
  });
1973
1973
 
1974
+ // src/owned-tools/internal-tool-names.ts
1975
+ var OWNED_INTERNAL_TOOL_NAMES;
1976
+ var init_internal_tool_names = __esm({
1977
+ "src/owned-tools/internal-tool-names.ts"() {
1978
+ "use strict";
1979
+ OWNED_INTERNAL_TOOL_NAMES = /* @__PURE__ */ new Set([
1980
+ "diary_search",
1981
+ "notes_search",
1982
+ "notes_get",
1983
+ "summarize"
1984
+ ]);
1985
+ }
1986
+ });
1987
+
1974
1988
  // src/mobile/native-reply-transcript.ts
1975
1989
  function assistantTurnTranscriptMessage(blocks) {
1976
1990
  return { role: "assistant", content: blocks };
@@ -1978,7 +1992,7 @@ function assistantTurnTranscriptMessage(blocks) {
1978
1992
  function toolResultsTranscriptMessage(results) {
1979
1993
  return { role: "user", content: results };
1980
1994
  }
1981
- var import_node_fs7, import_node_path9;
1995
+ var import_node_fs7, import_node_path9, IMAGE_BLOCK_BUDGET_BYTES;
1982
1996
  var init_native_reply_transcript = __esm({
1983
1997
  "src/mobile/native-reply-transcript.ts"() {
1984
1998
  "use strict";
@@ -1988,6 +2002,8 @@ var init_native_reply_transcript = __esm({
1988
2002
  init_chat_visible_text();
1989
2003
  init_transcript_media_sanitize();
1990
2004
  init_tool_result_compact();
2005
+ init_internal_tool_names();
2006
+ IMAGE_BLOCK_BUDGET_BYTES = 8 * 1024;
1991
2007
  }
1992
2008
  });
1993
2009
 
@@ -8371,215 +8387,21 @@ var init_memory_consolidate = __esm({
8371
8387
  }
8372
8388
  });
8373
8389
 
8374
- // src/mobile/group/team-memory-runtime.ts
8375
- function normalizeTeamId(teamId) {
8376
- return teamId?.trim() || "";
8377
- }
8378
- function evidenceRef(input) {
8379
- return input.minutesPath?.trim() || `team_minutes:${input.minutes.team_id}:${input.minutes.session_id}:${input.minutes.created_at}`;
8380
- }
8381
- function compactLine(value, max = 360) {
8382
- const normalized = value?.replace(/\s+/gu, " ").trim();
8383
- if (!normalized) return void 0;
8384
- return normalized.length <= max ? normalized : `${normalized.slice(0, max - 3)}...`;
8385
- }
8386
- function buildContent(minutes) {
8387
- const viewpointLines = minutes.viewpoints.map((view) => {
8388
- const summary = compactLine(view.summary, 240);
8389
- return summary ? `- ${view.agent_id}: ${summary}` : void 0;
8390
- }).filter((line) => Boolean(line));
8391
- return [
8392
- `Group convergence memory for team ${minutes.team_id}.`,
8393
- minutes.topic ? `Topic: ${compactLine(minutes.topic, 240)}` : void 0,
8394
- minutes.conclusion ? `Conclusion: ${compactLine(minutes.conclusion, 360)}` : void 0,
8395
- minutes.participants.length ? `Participants: ${minutes.participants.join(", ")}` : void 0,
8396
- viewpointLines.length ? ["Viewpoints:", ...viewpointLines].join("\n") : void 0,
8397
- minutes.disagreements?.length ? ["Disagreements:", ...minutes.disagreements.map((item) => `- ${compactLine(item, 220)}`)].join("\n") : void 0,
8398
- minutes.todos?.length ? ["Todos:", ...minutes.todos.map((todo) => `- ${todo.owner_agent_id}: ${compactLine(todo.item, 180)}`)].join("\n") : void 0,
8399
- minutes.budget_usage ? `Budget: rounds=${minutes.budget_usage.rounds ?? 0}; messages=${minutes.budget_usage.messages ?? 0}` : void 0
8400
- ].filter(Boolean).join("\n");
8401
- }
8402
- async function recordGroupConvergenceTeamMemory(input) {
8403
- const teamId = normalizeTeamId(input.teamId ?? input.minutes.team_id);
8404
- if (!teamId || teamId === "unknown") {
8405
- return { ok: false, imported: false, skippedReason: "missing_team_id" };
8406
- }
8407
- const ref = evidenceRef(input);
8408
- const scope = { type: "team", id: teamId };
8409
- const existing = await readMemoryRecords(scope, 5e3);
8410
- const duplicate = existing.find((record2) => record2.evidenceRefs.includes(ref));
8411
- if (duplicate) {
8412
- return { ok: true, imported: false, skippedReason: "duplicate", record: duplicate, consolidated: false };
8413
- }
8414
- const record = await ingestMemoryEvent({
8415
- scope,
8416
- kind: "episode",
8417
- content: buildContent({ ...input.minutes, team_id: teamId }),
8418
- evidenceRefs: [ref, `session:${input.sessionId}`],
8419
- confidence: 0.82,
8420
- visibility: "team",
8421
- tags: [
8422
- "group-convergence",
8423
- `team:${teamId}`,
8424
- `session:${input.sessionId}`,
8425
- ...input.minutes.topic ? [`topic:${input.minutes.topic}`] : []
8426
- ]
8427
- });
8428
- try {
8429
- await runMemoryConsolidation({
8430
- scope,
8431
- reason: "group-convergence-team-memory",
8432
- budgetClass: "background"
8433
- });
8434
- return { ok: true, imported: true, record, consolidated: true };
8435
- } catch (error) {
8436
- return {
8437
- ok: true,
8438
- imported: true,
8439
- record,
8440
- consolidated: false,
8441
- consolidationError: error instanceof Error ? error.message : String(error)
8442
- };
8443
- }
8444
- }
8445
- var init_team_memory_runtime = __esm({
8446
- "src/mobile/group/team-memory-runtime.ts"() {
8447
- "use strict";
8448
- init_memory_consolidate();
8449
- init_memory_event();
8450
- }
8451
- });
8452
-
8453
- // src/mobile/group/agent-personalization-key.ts
8454
- function catalogIdFromMbti(mbti) {
8455
- return `z-${mbti.trim().toLowerCase()}`;
8456
- }
8457
- function catalogStableKey(catalogId) {
8458
- return `${CATALOG_PERSONALIZATION_PREFIX}${catalogId.trim()}`;
8459
- }
8460
- function mbtiStableKey(mbti) {
8461
- return `${MBTI_PERSONALIZATION_PREFIX}${mbti.trim().toUpperCase()}`;
8462
- }
8463
- function resolveCatalogIdForAgent(agent) {
8464
- const mbti = agent.enrichment?.mbti?.trim().toUpperCase();
8465
- if (!mbti) {
8466
- return null;
8467
- }
8468
- return catalogIdFromMbti(mbti);
8469
- }
8470
- function lookupKeysForAgent(agent) {
8471
- const keys = [];
8472
- const catalogId = resolveCatalogIdForAgent(agent);
8473
- if (catalogId) {
8474
- keys.push(catalogStableKey(catalogId));
8475
- }
8476
- const mbti = agent.enrichment?.mbti?.trim().toUpperCase();
8477
- if (mbti) {
8478
- keys.push(mbtiStableKey(mbti));
8479
- }
8480
- const id = agent.id.trim();
8481
- if (id) {
8482
- keys.push(id);
8483
- }
8484
- return [...new Set(keys)];
8485
- }
8486
- function lookupPersonalizationValue(map, agent) {
8487
- if (!map) {
8488
- return "";
8489
- }
8490
- for (const key of lookupKeysForAgent(agent)) {
8491
- const v = map[key]?.trim();
8492
- if (v) {
8493
- return v;
8494
- }
8495
- }
8496
- return "";
8497
- }
8498
- var CATALOG_PERSONALIZATION_PREFIX, MBTI_PERSONALIZATION_PREFIX;
8499
- var init_agent_personalization_key = __esm({
8500
- "src/mobile/group/agent-personalization-key.ts"() {
8501
- "use strict";
8502
- CATALOG_PERSONALIZATION_PREFIX = "catalog:";
8503
- MBTI_PERSONALIZATION_PREFIX = "mbti:";
8504
- }
8505
- });
8506
-
8507
- // src/mobile/group/remarks.ts
8508
- function agentRefFromId(agentId) {
8509
- const agent = getMobileChatStore().getAgentById(agentId);
8510
- if (!agent) {
8511
- return { id: agentId };
8512
- }
8513
- return {
8514
- id: agent.id,
8515
- enrichment: agent.enrichment?.mbti ? { mbti: agent.enrichment.mbti } : null
8516
- };
8517
- }
8518
- function snapshotRemarkMap() {
8519
- return Object.fromEntries(remarkByAgentId.entries());
8520
- }
8521
- function getAgentRemark(agentId) {
8522
- const id = agentId.trim();
8523
- if (!id) {
8524
- return void 0;
8525
- }
8526
- const direct = remarkByAgentId.get(id);
8527
- if (direct) {
8528
- return direct;
8529
- }
8530
- const viaAlias = lookupPersonalizationValue(snapshotRemarkMap(), agentRefFromId(id));
8531
- return viaAlias || void 0;
8532
- }
8533
- function buildAgentUserRemarkAwarenessBlock(agentId, mode = "direct") {
8534
- const remark = getAgentRemark(agentId);
8535
- if (!remark) {
8536
- return void 0;
8537
- }
8538
- if (mode === "group") {
8539
- return [
8540
- `\u8001\u677F\u7ED9\u4F60\u8D77\u7684\u5907\u6CE8\u662F\u300C${remark}\u300D\u2014\u2014\u8FD9\u662F\u7528\u6237\u79F0\u547C\u4F60\u7684\u540D\u5B57\uFF0C\u4E0D\u662F\u7528\u6237\u7684\u540D\u5B57\u3002`,
8541
- `\u7FA4\u91CC\u6709\u4EBA\u8FD9\u6837\u558A\u5C31\u662F\u5728\u53EB\u4F60\uFF1B\u4E0D\u8981\u7528\u300C\u4F60\u597D ${remark}\u300D\u5411\u7528\u6237\u6253\u62DB\u547C\u3002`,
8542
- `\u88AB\u95EE\u53CA\u300C\u4F60\u7684\u5907\u6CE8/\u804C\u4F4D\u300D\u65F6\uFF0C\u76F4\u63A5\u56DE\u7B54\u300C${remark}\u300D\uFF0C\u4E0D\u8981\u6539\u7B54 MBTI \u7C7B\u578B\u540D\u6216\u5546\u5E97\u5C55\u793A\u540D\u3002`
8543
- ].join(" ");
8544
- }
8545
- return [
8546
- `\u7528\u6237\uFF08\u8001\u677F\uFF09\u7ED9\u4F60\u8D77\u7684\u5907\u6CE8\u662F\u300C${remark}\u300D\u3002`,
8547
- "\u8FD9\u662F\u7528\u6237\u79F0\u547C\u4F60\u7684\u540D\u5B57\uFF08\u4F60\u7684\u4E13\u5C5E\u53EB\u6CD5\uFF09\uFF0C\u4E0D\u662F\u7528\u6237\u7684\u540D\u5B57\u3002",
8548
- `\u81EA\u6211\u4ECB\u7ECD\u6216\u88AB\u95EE\u53CA\u79F0\u547C\u65F6\uFF0C\u53EF\u8BF4\u300C\u6211\u662F ${remark}\u300D\u6216\u300C\u4F60\u53EF\u4EE5\u53EB\u6211 ${remark}\u300D\uFF1B\u4E0D\u8981\u7528\u300C\u4F60\u597D ${remark}\u300D\u5411\u7528\u6237\u6253\u62DB\u547C\u3002`,
8549
- "\u5982\u4F55\u79F0\u547C\u7528\u6237\u89C1 USER.md\uFF08file scope=memory\uFF09\u3002"
8550
- ].join(" ");
8551
- }
8552
- function createRemarkResolver() {
8553
- return (agentId) => getAgentRemark(agentId);
8554
- }
8555
- var remarkByAgentId;
8556
- var init_remarks = __esm({
8557
- "src/mobile/group/remarks.ts"() {
8558
- "use strict";
8559
- init_store();
8560
- init_agent_personalization_key();
8561
- remarkByAgentId = /* @__PURE__ */ new Map();
8562
- }
8563
- });
8564
-
8565
8390
  // src/owned-tools/owned-tool-payload-failure.ts
8566
8391
  function ownedToolPayloadIndicatesFailure(payload) {
8567
8392
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
8568
8393
  return false;
8569
8394
  }
8570
8395
  const record = payload;
8396
+ if (record.is_error === true) {
8397
+ return true;
8398
+ }
8571
8399
  if (record.ok === false) {
8572
8400
  return true;
8573
8401
  }
8574
8402
  if (record.ok === true) {
8575
8403
  return false;
8576
8404
  }
8577
- if (typeof record.exitCode === "number" && record.exitCode !== 0) {
8578
- return true;
8579
- }
8580
- if (typeof record.error === "string" && record.error.trim()) {
8581
- return true;
8582
- }
8583
8405
  return false;
8584
8406
  }
8585
8407
  var init_owned_tool_payload_failure = __esm({
@@ -8606,15 +8428,12 @@ function assessSingleHandoffToolCall(tc) {
8606
8428
  }
8607
8429
  const envelope = parseHandoffPayload(tc.result ?? tc.partialResult);
8608
8430
  if (!envelope) {
8609
- return tc.status === "success" ? { kind: "succeeded" } : { kind: "none" };
8431
+ return { kind: "none" };
8610
8432
  }
8611
8433
  if (ownedToolPayloadIndicatesFailure(envelope)) {
8612
8434
  return { kind: "failed" };
8613
8435
  }
8614
8436
  const data = envelope.data && typeof envelope.data === "object" && !Array.isArray(envelope.data) ? envelope.data : envelope;
8615
- if (data.ok === false) {
8616
- return { kind: "failed" };
8617
- }
8618
8437
  const phase = typeof data.phase === "string" ? data.phase : void 0;
8619
8438
  return { kind: "succeeded", phase };
8620
8439
  }
@@ -8641,15 +8460,12 @@ function assessSingleCeoDecisionToolCall(tc) {
8641
8460
  }
8642
8461
  const envelope = parseHandoffPayload(tc.result ?? tc.partialResult);
8643
8462
  if (!envelope) {
8644
- return tc.status === "success" ? { kind: "succeeded" } : { kind: "none" };
8463
+ return { kind: "none" };
8645
8464
  }
8646
8465
  if (ownedToolPayloadIndicatesFailure(envelope)) {
8647
8466
  return { kind: "failed" };
8648
8467
  }
8649
8468
  const data = envelope.data && typeof envelope.data === "object" && !Array.isArray(envelope.data) ? envelope.data : envelope;
8650
- if (data.ok === false) {
8651
- return { kind: "failed" };
8652
- }
8653
8469
  const phase = typeof data.phase === "string" ? data.phase : void 0;
8654
8470
  return { kind: "succeeded", phase };
8655
8471
  }
@@ -8751,13 +8567,67 @@ var init_pipeline_handoff_verification = __esm({
8751
8567
  });
8752
8568
 
8753
8569
  // src/mobile/group/delivery-verification.ts
8570
+ function parseToolResult(raw) {
8571
+ const trimmed = raw?.trim();
8572
+ if (!trimmed) {
8573
+ return void 0;
8574
+ }
8575
+ try {
8576
+ return JSON.parse(trimmed);
8577
+ } catch {
8578
+ return trimmed;
8579
+ }
8580
+ }
8581
+ function hasNonEmptyString(value) {
8582
+ return typeof value === "string" && value.trim().length > 0;
8583
+ }
8584
+ function recordHasEvidenceField(value, depth = 0) {
8585
+ if (!value || typeof value !== "object" || depth > 4) {
8586
+ return false;
8587
+ }
8588
+ if (Array.isArray(value)) {
8589
+ return value.some((entry) => recordHasEvidenceField(entry, depth + 1));
8590
+ }
8591
+ const record = value;
8592
+ for (const [key, fieldValue] of Object.entries(record)) {
8593
+ const normalizedKey = key.toLowerCase();
8594
+ const keyLooksLikeEvidence = normalizedKey === "path" || normalizedKey === "abspath" || normalizedKey === "filepath" || normalizedKey === "targetpath" || normalizedKey === "resolvedpath" || normalizedKey === "hash" || normalizedKey === "sha256" || normalizedKey === "digest" || normalizedKey === "checksum" || normalizedKey === "exitcode" || normalizedKey === "stdout" || normalizedKey === "stderr" || normalizedKey === "byteswritten" || normalizedKey === "sizebytes" || normalizedKey === "url" || normalizedKey === "mediaurl";
8595
+ if (keyLooksLikeEvidence && (hasNonEmptyString(fieldValue) || typeof fieldValue === "number" && Number.isFinite(fieldValue))) {
8596
+ return true;
8597
+ }
8598
+ if (recordHasEvidenceField(fieldValue, depth + 1)) {
8599
+ return true;
8600
+ }
8601
+ }
8602
+ return false;
8603
+ }
8604
+ function toolCallHasCompletionEvidence(tc) {
8605
+ if (tc.status !== "success" || tc.isError) {
8606
+ return false;
8607
+ }
8608
+ const result = parseToolResult(tc.result ?? tc.partialResult);
8609
+ const args = tc.args ?? {};
8610
+ const resultHasEvidence = recordHasEvidenceField(result);
8611
+ const argsHaveEvidence = recordHasEvidenceField(args);
8612
+ const tool = tc.name.trim().toLowerCase();
8613
+ if (tool === "exec") {
8614
+ return argsHaveEvidence || resultHasEvidence || hasNonEmptyString(args.command);
8615
+ }
8616
+ if (tool === "write" || tool === "edit" || tool === "read" || tool === "pdf") {
8617
+ return argsHaveEvidence || resultHasEvidence;
8618
+ }
8619
+ if (tool === "image_generate" || tool === "video_generate" || tool === "music_generate") {
8620
+ return argsHaveEvidence || resultHasEvidence;
8621
+ }
8622
+ return resultHasEvidence;
8623
+ }
8754
8624
  function assessGenericCompletionVerification(text, toolCalls) {
8755
8625
  const trimmed = text.trim();
8756
8626
  if (!trimmed || !COMPLETION_CLAIM_PATTERN.test(trimmed)) {
8757
8627
  return void 0;
8758
8628
  }
8759
- const hasSuccessTool = (toolCalls ?? []).some((tc) => tc.status === "success");
8760
- return hasSuccessTool ? "verified" : "unverified";
8629
+ const hasEvidenceBackedTool = (toolCalls ?? []).some((tc) => toolCallHasCompletionEvidence(tc));
8630
+ return hasEvidenceBackedTool ? "verified" : "unverified";
8761
8631
  }
8762
8632
  function assessDeliveryVerification(text, toolCalls) {
8763
8633
  const handoffClaim = assessPipelineHandoffClaimVerification(text, toolCalls);
@@ -8771,7 +8641,198 @@ var init_delivery_verification = __esm({
8771
8641
  "src/mobile/group/delivery-verification.ts"() {
8772
8642
  "use strict";
8773
8643
  init_pipeline_handoff_verification();
8774
- COMPLETION_CLAIM_PATTERN = /(?:已完成|已经完成|做完了|搞定了|修改成功|写入成功|创建成功|删除成功|已改成|已更新|已保存)/i;
8644
+ COMPLETION_CLAIM_PATTERN = /(?:已完成|已经完成|做完了|搞定了|修改成功|写入成功|创建成功|删除成功|已改成|已更新|已保存|已修改|已写入|已创建|已删除|已检查|已验证|跑完了|\d+\s*(?:个|件)?\s*(?:文件|目录|路径))/i;
8645
+ }
8646
+ });
8647
+
8648
+ // src/mobile/group/team-memory-runtime.ts
8649
+ function normalizeTeamId(teamId) {
8650
+ return teamId?.trim() || "";
8651
+ }
8652
+ function evidenceRef(input) {
8653
+ return input.minutesPath?.trim() || `team_minutes:${input.minutes.team_id}:${input.minutes.session_id}:${input.minutes.created_at}`;
8654
+ }
8655
+ function compactLine(value, max = 360) {
8656
+ const normalized = value?.replace(/\s+/gu, " ").trim();
8657
+ if (!normalized) return void 0;
8658
+ return normalized.length <= max ? normalized : `${normalized.slice(0, max - 3)}...`;
8659
+ }
8660
+ function buildContent(minutes) {
8661
+ const viewpointLines = minutes.viewpoints.map((view) => {
8662
+ const summary = compactLine(view.summary, 240);
8663
+ return summary ? `- ${view.agent_id}: ${summary}` : void 0;
8664
+ }).filter((line) => Boolean(line));
8665
+ return [
8666
+ `Group convergence memory for team ${minutes.team_id}.`,
8667
+ minutes.topic ? `Topic: ${compactLine(minutes.topic, 240)}` : void 0,
8668
+ minutes.conclusion ? `Conclusion: ${compactLine(minutes.conclusion, 360)}` : void 0,
8669
+ minutes.participants.length ? `Participants: ${minutes.participants.join(", ")}` : void 0,
8670
+ viewpointLines.length ? ["Viewpoints:", ...viewpointLines].join("\n") : void 0,
8671
+ minutes.disagreements?.length ? ["Disagreements:", ...minutes.disagreements.map((item) => `- ${compactLine(item, 220)}`)].join("\n") : void 0,
8672
+ minutes.todos?.length ? ["Todos:", ...minutes.todos.map((todo) => `- ${todo.owner_agent_id}: ${compactLine(todo.item, 180)}`)].join("\n") : void 0,
8673
+ minutes.budget_usage ? `Budget: rounds=${minutes.budget_usage.rounds ?? 0}; messages=${minutes.budget_usage.messages ?? 0}` : void 0
8674
+ ].filter(Boolean).join("\n");
8675
+ }
8676
+ async function recordGroupConvergenceTeamMemory(input) {
8677
+ const teamId = normalizeTeamId(input.teamId ?? input.minutes.team_id);
8678
+ if (!teamId || teamId === "unknown") {
8679
+ return { ok: false, imported: false, skippedReason: "missing_team_id" };
8680
+ }
8681
+ const ref = evidenceRef(input);
8682
+ const scope = { type: "team", id: teamId };
8683
+ const existing = await readMemoryRecords(scope, 5e3);
8684
+ const duplicate = existing.find((record2) => record2.evidenceRefs.includes(ref));
8685
+ if (duplicate) {
8686
+ return { ok: true, imported: false, skippedReason: "duplicate", record: duplicate, consolidated: false };
8687
+ }
8688
+ const record = await ingestMemoryEvent({
8689
+ scope,
8690
+ kind: "episode",
8691
+ content: buildContent({ ...input.minutes, team_id: teamId }),
8692
+ evidenceRefs: [ref, `session:${input.sessionId}`],
8693
+ confidence: 0.82,
8694
+ visibility: "team",
8695
+ tags: [
8696
+ "group-convergence",
8697
+ `team:${teamId}`,
8698
+ `session:${input.sessionId}`,
8699
+ ...input.minutes.topic ? [`topic:${input.minutes.topic}`] : []
8700
+ ]
8701
+ });
8702
+ try {
8703
+ await runMemoryConsolidation({
8704
+ scope,
8705
+ reason: "group-convergence-team-memory",
8706
+ budgetClass: "background"
8707
+ });
8708
+ return { ok: true, imported: true, record, consolidated: true };
8709
+ } catch (error) {
8710
+ return {
8711
+ ok: true,
8712
+ imported: true,
8713
+ record,
8714
+ consolidated: false,
8715
+ consolidationError: error instanceof Error ? error.message : String(error)
8716
+ };
8717
+ }
8718
+ }
8719
+ var init_team_memory_runtime = __esm({
8720
+ "src/mobile/group/team-memory-runtime.ts"() {
8721
+ "use strict";
8722
+ init_memory_consolidate();
8723
+ init_memory_event();
8724
+ }
8725
+ });
8726
+
8727
+ // src/mobile/group/agent-personalization-key.ts
8728
+ function catalogIdFromMbti(mbti) {
8729
+ return `z-${mbti.trim().toLowerCase()}`;
8730
+ }
8731
+ function catalogStableKey(catalogId) {
8732
+ return `${CATALOG_PERSONALIZATION_PREFIX}${catalogId.trim()}`;
8733
+ }
8734
+ function mbtiStableKey(mbti) {
8735
+ return `${MBTI_PERSONALIZATION_PREFIX}${mbti.trim().toUpperCase()}`;
8736
+ }
8737
+ function resolveCatalogIdForAgent(agent) {
8738
+ const mbti = agent.enrichment?.mbti?.trim().toUpperCase();
8739
+ if (!mbti) {
8740
+ return null;
8741
+ }
8742
+ return catalogIdFromMbti(mbti);
8743
+ }
8744
+ function lookupKeysForAgent(agent) {
8745
+ const keys = [];
8746
+ const catalogId = resolveCatalogIdForAgent(agent);
8747
+ if (catalogId) {
8748
+ keys.push(catalogStableKey(catalogId));
8749
+ }
8750
+ const mbti = agent.enrichment?.mbti?.trim().toUpperCase();
8751
+ if (mbti) {
8752
+ keys.push(mbtiStableKey(mbti));
8753
+ }
8754
+ const id = agent.id.trim();
8755
+ if (id) {
8756
+ keys.push(id);
8757
+ }
8758
+ return [...new Set(keys)];
8759
+ }
8760
+ function lookupPersonalizationValue(map, agent) {
8761
+ if (!map) {
8762
+ return "";
8763
+ }
8764
+ for (const key of lookupKeysForAgent(agent)) {
8765
+ const v = map[key]?.trim();
8766
+ if (v) {
8767
+ return v;
8768
+ }
8769
+ }
8770
+ return "";
8771
+ }
8772
+ var CATALOG_PERSONALIZATION_PREFIX, MBTI_PERSONALIZATION_PREFIX;
8773
+ var init_agent_personalization_key = __esm({
8774
+ "src/mobile/group/agent-personalization-key.ts"() {
8775
+ "use strict";
8776
+ CATALOG_PERSONALIZATION_PREFIX = "catalog:";
8777
+ MBTI_PERSONALIZATION_PREFIX = "mbti:";
8778
+ }
8779
+ });
8780
+
8781
+ // src/mobile/group/remarks.ts
8782
+ function agentRefFromId(agentId) {
8783
+ const agent = getMobileChatStore().getAgentById(agentId);
8784
+ if (!agent) {
8785
+ return { id: agentId };
8786
+ }
8787
+ return {
8788
+ id: agent.id,
8789
+ enrichment: agent.enrichment?.mbti ? { mbti: agent.enrichment.mbti } : null
8790
+ };
8791
+ }
8792
+ function snapshotRemarkMap() {
8793
+ return Object.fromEntries(remarkByAgentId.entries());
8794
+ }
8795
+ function getAgentRemark(agentId) {
8796
+ const id = agentId.trim();
8797
+ if (!id) {
8798
+ return void 0;
8799
+ }
8800
+ const direct = remarkByAgentId.get(id);
8801
+ if (direct) {
8802
+ return direct;
8803
+ }
8804
+ const viaAlias = lookupPersonalizationValue(snapshotRemarkMap(), agentRefFromId(id));
8805
+ return viaAlias || void 0;
8806
+ }
8807
+ function buildAgentUserRemarkAwarenessBlock(agentId, mode = "direct") {
8808
+ const remark = getAgentRemark(agentId);
8809
+ if (!remark) {
8810
+ return void 0;
8811
+ }
8812
+ if (mode === "group") {
8813
+ return [
8814
+ `\u8001\u677F\u7ED9\u4F60\u8D77\u7684\u5907\u6CE8\u662F\u300C${remark}\u300D\u2014\u2014\u8FD9\u662F\u7528\u6237\u79F0\u547C\u4F60\u7684\u540D\u5B57\uFF0C\u4E0D\u662F\u7528\u6237\u7684\u540D\u5B57\u3002`,
8815
+ `\u7FA4\u91CC\u6709\u4EBA\u8FD9\u6837\u558A\u5C31\u662F\u5728\u53EB\u4F60\uFF1B\u4E0D\u8981\u7528\u300C\u4F60\u597D ${remark}\u300D\u5411\u7528\u6237\u6253\u62DB\u547C\u3002`,
8816
+ `\u88AB\u95EE\u53CA\u300C\u4F60\u7684\u5907\u6CE8/\u804C\u4F4D\u300D\u65F6\uFF0C\u76F4\u63A5\u56DE\u7B54\u300C${remark}\u300D\uFF0C\u4E0D\u8981\u6539\u7B54 MBTI \u7C7B\u578B\u540D\u6216\u5546\u5E97\u5C55\u793A\u540D\u3002`
8817
+ ].join(" ");
8818
+ }
8819
+ return [
8820
+ `\u7528\u6237\uFF08\u8001\u677F\uFF09\u7ED9\u4F60\u8D77\u7684\u5907\u6CE8\u662F\u300C${remark}\u300D\u3002`,
8821
+ "\u8FD9\u662F\u7528\u6237\u79F0\u547C\u4F60\u7684\u540D\u5B57\uFF08\u4F60\u7684\u4E13\u5C5E\u53EB\u6CD5\uFF09\uFF0C\u4E0D\u662F\u7528\u6237\u7684\u540D\u5B57\u3002",
8822
+ `\u81EA\u6211\u4ECB\u7ECD\u6216\u88AB\u95EE\u53CA\u79F0\u547C\u65F6\uFF0C\u53EF\u8BF4\u300C\u6211\u662F ${remark}\u300D\u6216\u300C\u4F60\u53EF\u4EE5\u53EB\u6211 ${remark}\u300D\uFF1B\u4E0D\u8981\u7528\u300C\u4F60\u597D ${remark}\u300D\u5411\u7528\u6237\u6253\u62DB\u547C\u3002`,
8823
+ "\u5982\u4F55\u79F0\u547C\u7528\u6237\u89C1 USER.md\uFF08file scope=memory\uFF09\u3002"
8824
+ ].join(" ");
8825
+ }
8826
+ function createRemarkResolver() {
8827
+ return (agentId) => getAgentRemark(agentId);
8828
+ }
8829
+ var remarkByAgentId;
8830
+ var init_remarks = __esm({
8831
+ "src/mobile/group/remarks.ts"() {
8832
+ "use strict";
8833
+ init_store();
8834
+ init_agent_personalization_key();
8835
+ remarkByAgentId = /* @__PURE__ */ new Map();
8775
8836
  }
8776
8837
  });
8777
8838
 
@@ -16581,8 +16642,6 @@ function toolChoicePolicyToMinimaxAnthropicToolChoiceWire(policy) {
16581
16642
 
16582
16643
  // src/mobile/minimax-m3.ts
16583
16644
  var MINIMAX_M3_MODEL_ID = "MiniMax-M3";
16584
- var MINIMAX_M3_DEFAULT_MAX_TOKENS = 131072;
16585
- var MINIMAX_M3_MAX_TOKENS_ENV = "XKZOOM_MINIMAX_M3_MAX_TOKENS";
16586
16645
  function isMinimaxM3Model(modelId) {
16587
16646
  return (modelId ?? "").trim() === MINIMAX_M3_MODEL_ID;
16588
16647
  }
@@ -16594,16 +16653,6 @@ function resolveMinimaxM3AnthropicThinking(params) {
16594
16653
  if (params.reasoningMode === "off") return "disabled";
16595
16654
  return "adaptive";
16596
16655
  }
16597
- function resolveMinimaxM3DefaultMaxTokens(env = process.env) {
16598
- const raw = env[MINIMAX_M3_MAX_TOKENS_ENV];
16599
- if (typeof raw === "string" && raw.trim()) {
16600
- const n = Number.parseInt(raw.trim(), 10);
16601
- if (Number.isFinite(n) && n > 0) {
16602
- return n;
16603
- }
16604
- }
16605
- return MINIMAX_M3_DEFAULT_MAX_TOKENS;
16606
- }
16607
16656
  function normalizeMinimaxM3ThinkingType(value) {
16608
16657
  if (value && typeof value === "object" && !Array.isArray(value)) {
16609
16658
  const raw = typeof value.type === "string" ? value.type.trim().toLowerCase() : "";
@@ -16617,6 +16666,199 @@ function normalizeMinimaxM3ThinkingType(value) {
16617
16666
  }
16618
16667
  }
16619
16668
 
16669
+ // src/mobile/native-request-diagnostics.ts
16670
+ function compactLogValue(value, maxLen = 180) {
16671
+ const text = String(value ?? "").replace(/\s+/g, " ").trim();
16672
+ if (!text) {
16673
+ return "";
16674
+ }
16675
+ return text.length > maxLen ? `${text.slice(0, maxLen)}...` : text;
16676
+ }
16677
+ function readErrorProp(value, key) {
16678
+ return value && typeof value === "object" ? value[key] : void 0;
16679
+ }
16680
+ function positiveInteger(value) {
16681
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
16682
+ return void 0;
16683
+ }
16684
+ return Math.trunc(value);
16685
+ }
16686
+ function formatNativeFetchErrorForLog(error) {
16687
+ const parts = [];
16688
+ let current = error;
16689
+ for (let depth = 0; depth < 4 && current !== null && current !== void 0; depth += 1) {
16690
+ const prefix = depth === 0 ? "error" : `cause${depth}`;
16691
+ const name = compactLogValue(readErrorProp(current, "name"));
16692
+ const message = current instanceof Error ? compactLogValue(current.message) : compactLogValue(readErrorProp(current, "message") ?? current);
16693
+ const code = compactLogValue(readErrorProp(current, "code"));
16694
+ const errno = compactLogValue(readErrorProp(current, "errno"));
16695
+ if (name) parts.push(`${prefix}Name=${name}`);
16696
+ if (message) parts.push(`${prefix}Message=${message}`);
16697
+ if (code) parts.push(`${prefix}Code=${code}`);
16698
+ if (errno) parts.push(`${prefix}Errno=${errno}`);
16699
+ current = readErrorProp(current, "cause");
16700
+ }
16701
+ return parts.join(" ") || "error=unknown";
16702
+ }
16703
+ var PROTOCOL_FALLBACK_MAX_TOKENS = 16384;
16704
+ function applyConfiguredMaxTokens(requestBody, maxTokens) {
16705
+ const configured = positiveInteger(maxTokens);
16706
+ if (configured === void 0) {
16707
+ return;
16708
+ }
16709
+ requestBody.max_tokens = configured;
16710
+ }
16711
+ function stringifyJsonRequestBody(requestBody) {
16712
+ const bodyText = JSON.stringify(requestBody);
16713
+ return {
16714
+ bodyText,
16715
+ bodyBytes: Buffer.byteLength(bodyText, "utf8")
16716
+ };
16717
+ }
16718
+ function formatRequestShape(input) {
16719
+ const messageCount = Array.isArray(input.messages) ? input.messages.length : 0;
16720
+ const toolCount = Array.isArray(input.tools) ? input.tools.length : 0;
16721
+ const maxTokens = positiveInteger(input.maxTokens);
16722
+ return `bodyBytes=${input.bodyBytes} messages=${messageCount} tools=${toolCount} max_tokens=${maxTokens ?? "n/a"}`;
16723
+ }
16724
+ var DEFAULT_PROVIDER_FETCH_MAX_ATTEMPTS = 2;
16725
+ var HARD_PROVIDER_FETCH_MAX_ATTEMPTS = 4;
16726
+ var DEFAULT_PROVIDER_FETCH_RETRY_BASE_MS = 350;
16727
+ var HARD_PROVIDER_FETCH_RETRY_BASE_MS = 5e3;
16728
+ var RETRYABLE_NATIVE_FETCH_RE = new RegExp(
16729
+ [
16730
+ "fetch failed",
16731
+ "UND_ERR_CONNECT_TIMEOUT",
16732
+ "UND_ERR_HEADERS_TIMEOUT",
16733
+ "UND_ERR_SOCKET",
16734
+ "ECONNRESET",
16735
+ "ETIMEDOUT",
16736
+ "ECONNREFUSED",
16737
+ "ENOTFOUND",
16738
+ "EAI_AGAIN",
16739
+ "socket hang up",
16740
+ "network connection lost",
16741
+ "network request failed"
16742
+ ].join("|"),
16743
+ "i"
16744
+ );
16745
+ function readClampedPositiveEnvInt(env, key, fallback, max) {
16746
+ const raw = (env[key] ?? "").trim();
16747
+ const n = Number.parseInt(raw, 10);
16748
+ if (!Number.isFinite(n) || n <= 0) {
16749
+ return fallback;
16750
+ }
16751
+ return Math.min(Math.trunc(n), max);
16752
+ }
16753
+ function readClampedNonNegativeEnvInt(env, key, fallback, max) {
16754
+ const raw = (env[key] ?? "").trim();
16755
+ const n = Number.parseInt(raw, 10);
16756
+ if (!Number.isFinite(n) || n < 0) {
16757
+ return fallback;
16758
+ }
16759
+ return Math.min(Math.trunc(n), max);
16760
+ }
16761
+ function readProviderFetchMaxAttempts(env) {
16762
+ return readClampedPositiveEnvInt(
16763
+ env,
16764
+ "XKZOOM_NATIVE_PROVIDER_FETCH_MAX_ATTEMPTS",
16765
+ DEFAULT_PROVIDER_FETCH_MAX_ATTEMPTS,
16766
+ HARD_PROVIDER_FETCH_MAX_ATTEMPTS
16767
+ );
16768
+ }
16769
+ function readProviderFetchRetryBaseMs(env) {
16770
+ return readClampedNonNegativeEnvInt(
16771
+ env,
16772
+ "XKZOOM_NATIVE_PROVIDER_FETCH_RETRY_BASE_MS",
16773
+ DEFAULT_PROVIDER_FETCH_RETRY_BASE_MS,
16774
+ HARD_PROVIDER_FETCH_RETRY_BASE_MS
16775
+ );
16776
+ }
16777
+ function isAbortLikeFetchError(error) {
16778
+ const name = compactLogValue(readErrorProp(error, "name"));
16779
+ return name === "AbortError";
16780
+ }
16781
+ function collectFetchErrorText(error) {
16782
+ const parts = [];
16783
+ let current = error;
16784
+ for (let depth = 0; depth < 4 && current !== null && current !== void 0; depth += 1) {
16785
+ parts.push(
16786
+ compactLogValue(readErrorProp(current, "name")),
16787
+ current instanceof Error ? compactLogValue(current.message) : compactLogValue(readErrorProp(current, "message") ?? current),
16788
+ compactLogValue(readErrorProp(current, "code")),
16789
+ compactLogValue(readErrorProp(current, "errno"))
16790
+ );
16791
+ current = readErrorProp(current, "cause");
16792
+ }
16793
+ return parts.filter(Boolean).join(" ");
16794
+ }
16795
+ function isRetryableNativeProviderFetchError(error) {
16796
+ return !isAbortLikeFetchError(error) && RETRYABLE_NATIVE_FETCH_RE.test(collectFetchErrorText(error));
16797
+ }
16798
+ function formatProviderRetryContext(context) {
16799
+ const parts = [
16800
+ `provider=${context.providerId}`,
16801
+ `model=${context.model}`,
16802
+ context.adapter ? `adapter=${context.adapter}` : "",
16803
+ typeof context.iteration === "number" ? `iteration=${context.iteration}` : ""
16804
+ ];
16805
+ return parts.filter(Boolean).join(" ");
16806
+ }
16807
+ function asAbortSignal(signal) {
16808
+ if (signal && typeof signal === "object" && "aborted" in signal) {
16809
+ return signal;
16810
+ }
16811
+ return void 0;
16812
+ }
16813
+ async function waitForProviderFetchRetryDelay(delayMs, signal) {
16814
+ if (delayMs <= 0) {
16815
+ return;
16816
+ }
16817
+ if (signal?.aborted) {
16818
+ throw new DOMException("Aborted", "AbortError");
16819
+ }
16820
+ await new Promise((resolve9, reject) => {
16821
+ const timer = setTimeout(() => {
16822
+ signal?.removeEventListener("abort", onAbort);
16823
+ resolve9();
16824
+ }, delayMs);
16825
+ const onAbort = () => {
16826
+ clearTimeout(timer);
16827
+ reject(new DOMException("Aborted", "AbortError"));
16828
+ };
16829
+ signal?.addEventListener("abort", onAbort, { once: true });
16830
+ });
16831
+ }
16832
+ async function fetchNativeProviderWithRetry(url, init, context, env = process.env) {
16833
+ const maxAttempts = readProviderFetchMaxAttempts(env);
16834
+ const retryBaseMs = readProviderFetchRetryBaseMs(env);
16835
+ const signal = asAbortSignal(init.signal);
16836
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
16837
+ try {
16838
+ return await fetch(url, init);
16839
+ } catch (error) {
16840
+ const retry = attempt < maxAttempts && !signal?.aborted && isRetryableNativeProviderFetchError(error);
16841
+ context.log(
16842
+ `[XKZOOM][native-reply][${context.label}] fetch_failed ${url} ${formatProviderRetryContext(context)} attempt=${attempt}/${maxAttempts} retry=${retry ? 1 : 0} ${formatRequestShape({
16843
+ bodyBytes: context.bodyBytes,
16844
+ messages: context.messages,
16845
+ tools: context.tools,
16846
+ maxTokens: context.maxTokens
16847
+ })} ${formatNativeFetchErrorForLog(error)}`
16848
+ );
16849
+ if (!retry) {
16850
+ throw error;
16851
+ }
16852
+ const delayMs = retryBaseMs * attempt;
16853
+ context.log(
16854
+ `[XKZOOM][native-reply][${context.label}] fetch_retry ${url} ${formatProviderRetryContext(context)} nextAttempt=${attempt + 1}/${maxAttempts} delayMs=${delayMs}`
16855
+ );
16856
+ await waitForProviderFetchRetryDelay(delayMs, signal);
16857
+ }
16858
+ }
16859
+ throw new Error(`native provider fetch retry exhausted: ${url}`);
16860
+ }
16861
+
16620
16862
  // src/mobile/anthropic-provider-adapter.ts
16621
16863
  function anthropicToolChoiceObject(policy) {
16622
16864
  switch (policy.kind) {
@@ -16691,7 +16933,7 @@ var genericAnthropicAdapter = {
16691
16933
  return genericThinking(input);
16692
16934
  },
16693
16935
  defaultBodyExtras() {
16694
- return { max_tokens: 16384 };
16936
+ return { max_tokens: PROTOCOL_FALLBACK_MAX_TOKENS };
16695
16937
  },
16696
16938
  forcedToolChoiceSupported() {
16697
16939
  return true;
@@ -16759,11 +17001,8 @@ var minimaxAnthropicAdapter = {
16759
17001
  }
16760
17002
  return void 0;
16761
17003
  },
16762
- defaultBodyExtras(input) {
16763
- if (isMinimaxM3Model(input?.model)) {
16764
- return { max_tokens: resolveMinimaxM3DefaultMaxTokens(input?.env) };
16765
- }
16766
- return { max_tokens: 16384 };
17004
+ defaultBodyExtras() {
17005
+ return { max_tokens: PROTOCOL_FALLBACK_MAX_TOKENS };
16767
17006
  },
16768
17007
  forcedToolChoiceSupported() {
16769
17008
  return true;
@@ -17665,199 +17904,6 @@ var minimaxOpenAiCompletionsAdapter = {
17665
17904
  id: "minimax"
17666
17905
  };
17667
17906
 
17668
- // src/mobile/native-request-diagnostics.ts
17669
- function compactLogValue(value, maxLen = 180) {
17670
- const text = String(value ?? "").replace(/\s+/g, " ").trim();
17671
- if (!text) {
17672
- return "";
17673
- }
17674
- return text.length > maxLen ? `${text.slice(0, maxLen)}...` : text;
17675
- }
17676
- function readErrorProp(value, key) {
17677
- return value && typeof value === "object" ? value[key] : void 0;
17678
- }
17679
- function positiveInteger(value) {
17680
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
17681
- return void 0;
17682
- }
17683
- return Math.trunc(value);
17684
- }
17685
- function formatNativeFetchErrorForLog(error) {
17686
- const parts = [];
17687
- let current = error;
17688
- for (let depth = 0; depth < 4 && current !== null && current !== void 0; depth += 1) {
17689
- const prefix = depth === 0 ? "error" : `cause${depth}`;
17690
- const name = compactLogValue(readErrorProp(current, "name"));
17691
- const message = current instanceof Error ? compactLogValue(current.message) : compactLogValue(readErrorProp(current, "message") ?? current);
17692
- const code = compactLogValue(readErrorProp(current, "code"));
17693
- const errno = compactLogValue(readErrorProp(current, "errno"));
17694
- if (name) parts.push(`${prefix}Name=${name}`);
17695
- if (message) parts.push(`${prefix}Message=${message}`);
17696
- if (code) parts.push(`${prefix}Code=${code}`);
17697
- if (errno) parts.push(`${prefix}Errno=${errno}`);
17698
- current = readErrorProp(current, "cause");
17699
- }
17700
- return parts.join(" ") || "error=unknown";
17701
- }
17702
- function applyConfiguredMaxTokens(requestBody, maxTokens) {
17703
- const configured = positiveInteger(maxTokens);
17704
- if (configured === void 0) {
17705
- return;
17706
- }
17707
- const existing = positiveInteger(requestBody.max_tokens);
17708
- requestBody.max_tokens = existing === void 0 ? configured : Math.min(existing, configured);
17709
- }
17710
- function stringifyJsonRequestBody(requestBody) {
17711
- const bodyText = JSON.stringify(requestBody);
17712
- return {
17713
- bodyText,
17714
- bodyBytes: Buffer.byteLength(bodyText, "utf8")
17715
- };
17716
- }
17717
- function formatRequestShape(input) {
17718
- const messageCount = Array.isArray(input.messages) ? input.messages.length : 0;
17719
- const toolCount = Array.isArray(input.tools) ? input.tools.length : 0;
17720
- const maxTokens = positiveInteger(input.maxTokens);
17721
- return `bodyBytes=${input.bodyBytes} messages=${messageCount} tools=${toolCount} max_tokens=${maxTokens ?? "n/a"}`;
17722
- }
17723
- var DEFAULT_PROVIDER_FETCH_MAX_ATTEMPTS = 2;
17724
- var HARD_PROVIDER_FETCH_MAX_ATTEMPTS = 4;
17725
- var DEFAULT_PROVIDER_FETCH_RETRY_BASE_MS = 350;
17726
- var HARD_PROVIDER_FETCH_RETRY_BASE_MS = 5e3;
17727
- var RETRYABLE_NATIVE_FETCH_RE = new RegExp(
17728
- [
17729
- "fetch failed",
17730
- "UND_ERR_CONNECT_TIMEOUT",
17731
- "UND_ERR_HEADERS_TIMEOUT",
17732
- "UND_ERR_SOCKET",
17733
- "ECONNRESET",
17734
- "ETIMEDOUT",
17735
- "ECONNREFUSED",
17736
- "ENOTFOUND",
17737
- "EAI_AGAIN",
17738
- "socket hang up",
17739
- "network connection lost",
17740
- "network request failed"
17741
- ].join("|"),
17742
- "i"
17743
- );
17744
- function readClampedPositiveEnvInt(env, key, fallback, max) {
17745
- const raw = (env[key] ?? "").trim();
17746
- const n = Number.parseInt(raw, 10);
17747
- if (!Number.isFinite(n) || n <= 0) {
17748
- return fallback;
17749
- }
17750
- return Math.min(Math.trunc(n), max);
17751
- }
17752
- function readClampedNonNegativeEnvInt(env, key, fallback, max) {
17753
- const raw = (env[key] ?? "").trim();
17754
- const n = Number.parseInt(raw, 10);
17755
- if (!Number.isFinite(n) || n < 0) {
17756
- return fallback;
17757
- }
17758
- return Math.min(Math.trunc(n), max);
17759
- }
17760
- function readProviderFetchMaxAttempts(env) {
17761
- return readClampedPositiveEnvInt(
17762
- env,
17763
- "XKZOOM_NATIVE_PROVIDER_FETCH_MAX_ATTEMPTS",
17764
- DEFAULT_PROVIDER_FETCH_MAX_ATTEMPTS,
17765
- HARD_PROVIDER_FETCH_MAX_ATTEMPTS
17766
- );
17767
- }
17768
- function readProviderFetchRetryBaseMs(env) {
17769
- return readClampedNonNegativeEnvInt(
17770
- env,
17771
- "XKZOOM_NATIVE_PROVIDER_FETCH_RETRY_BASE_MS",
17772
- DEFAULT_PROVIDER_FETCH_RETRY_BASE_MS,
17773
- HARD_PROVIDER_FETCH_RETRY_BASE_MS
17774
- );
17775
- }
17776
- function isAbortLikeFetchError(error) {
17777
- const name = compactLogValue(readErrorProp(error, "name"));
17778
- return name === "AbortError";
17779
- }
17780
- function collectFetchErrorText(error) {
17781
- const parts = [];
17782
- let current = error;
17783
- for (let depth = 0; depth < 4 && current !== null && current !== void 0; depth += 1) {
17784
- parts.push(
17785
- compactLogValue(readErrorProp(current, "name")),
17786
- current instanceof Error ? compactLogValue(current.message) : compactLogValue(readErrorProp(current, "message") ?? current),
17787
- compactLogValue(readErrorProp(current, "code")),
17788
- compactLogValue(readErrorProp(current, "errno"))
17789
- );
17790
- current = readErrorProp(current, "cause");
17791
- }
17792
- return parts.filter(Boolean).join(" ");
17793
- }
17794
- function isRetryableNativeProviderFetchError(error) {
17795
- return !isAbortLikeFetchError(error) && RETRYABLE_NATIVE_FETCH_RE.test(collectFetchErrorText(error));
17796
- }
17797
- function formatProviderRetryContext(context) {
17798
- const parts = [
17799
- `provider=${context.providerId}`,
17800
- `model=${context.model}`,
17801
- context.adapter ? `adapter=${context.adapter}` : "",
17802
- typeof context.iteration === "number" ? `iteration=${context.iteration}` : ""
17803
- ];
17804
- return parts.filter(Boolean).join(" ");
17805
- }
17806
- function asAbortSignal(signal) {
17807
- if (signal && typeof signal === "object" && "aborted" in signal) {
17808
- return signal;
17809
- }
17810
- return void 0;
17811
- }
17812
- async function waitForProviderFetchRetryDelay(delayMs, signal) {
17813
- if (delayMs <= 0) {
17814
- return;
17815
- }
17816
- if (signal?.aborted) {
17817
- throw new DOMException("Aborted", "AbortError");
17818
- }
17819
- await new Promise((resolve9, reject) => {
17820
- const timer = setTimeout(() => {
17821
- signal?.removeEventListener("abort", onAbort);
17822
- resolve9();
17823
- }, delayMs);
17824
- const onAbort = () => {
17825
- clearTimeout(timer);
17826
- reject(new DOMException("Aborted", "AbortError"));
17827
- };
17828
- signal?.addEventListener("abort", onAbort, { once: true });
17829
- });
17830
- }
17831
- async function fetchNativeProviderWithRetry(url, init, context, env = process.env) {
17832
- const maxAttempts = readProviderFetchMaxAttempts(env);
17833
- const retryBaseMs = readProviderFetchRetryBaseMs(env);
17834
- const signal = asAbortSignal(init.signal);
17835
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
17836
- try {
17837
- return await fetch(url, init);
17838
- } catch (error) {
17839
- const retry = attempt < maxAttempts && !signal?.aborted && isRetryableNativeProviderFetchError(error);
17840
- context.log(
17841
- `[XKZOOM][native-reply][${context.label}] fetch_failed ${url} ${formatProviderRetryContext(context)} attempt=${attempt}/${maxAttempts} retry=${retry ? 1 : 0} ${formatRequestShape({
17842
- bodyBytes: context.bodyBytes,
17843
- messages: context.messages,
17844
- tools: context.tools,
17845
- maxTokens: context.maxTokens
17846
- })} ${formatNativeFetchErrorForLog(error)}`
17847
- );
17848
- if (!retry) {
17849
- throw error;
17850
- }
17851
- const delayMs = retryBaseMs * attempt;
17852
- context.log(
17853
- `[XKZOOM][native-reply][${context.label}] fetch_retry ${url} ${formatProviderRetryContext(context)} nextAttempt=${attempt + 1}/${maxAttempts} delayMs=${delayMs}`
17854
- );
17855
- await waitForProviderFetchRetryDelay(delayMs, signal);
17856
- }
17857
- }
17858
- throw new Error(`native provider fetch retry exhausted: ${url}`);
17859
- }
17860
-
17861
17907
  // src/mobile/native-openai-text-stream.ts
17862
17908
  var isRecord3 = isGatewayConfigRecord;
17863
17909
  function resolveOpenAiCompletionsBodyExtras(provider, baseUrl) {
@@ -19640,7 +19686,7 @@ async function minimaxVoiceDesign(input) {
19640
19686
  throw new Error(`MiniMax voice_design error ${code}: ${payload.base_resp?.status_msg ?? bodyText.slice(0, 200)}`);
19641
19687
  }
19642
19688
  const trialAudioHex = payload.data?.trial_audio ?? payload.trial_audio;
19643
- const preview = input.root && trialAudioHex ? await writeMediaAssetToWorkspace({
19689
+ const preview2 = input.root && trialAudioHex ? await writeMediaAssetToWorkspace({
19644
19690
  root: input.root,
19645
19691
  relPath: buildGeneratedMediaRelPath({
19646
19692
  kind: "audio",
@@ -19657,7 +19703,7 @@ async function minimaxVoiceDesign(input) {
19657
19703
  previewText: input.previewText,
19658
19704
  voiceId: payload.data?.voice_id ?? payload.voice_id,
19659
19705
  provider: "minimax-voice-design",
19660
- ...preview ? { preview } : {}
19706
+ ...preview2 ? { preview: preview2 } : {}
19661
19707
  };
19662
19708
  }
19663
19709
  async function minimaxVoiceClone(input) {
@@ -20013,6 +20059,9 @@ function registerDefaultOwnedProviders() {
20013
20059
  });
20014
20060
  }
20015
20061
 
20062
+ // src/owned-tools/registry.ts
20063
+ init_internal_tool_names();
20064
+
20016
20065
  // src/owned-tools/agents-list.ts
20017
20066
  init_runtime_data();
20018
20067
  init_tool_descriptor();
@@ -23000,7 +23049,7 @@ function resolveAnthropicMessagesBodyExtras(provider) {
23000
23049
  }
23001
23050
  return isGatewayConfigRecord(raw) ? { ...raw } : {};
23002
23051
  }
23003
- return { max_tokens: 16384 };
23052
+ return { max_tokens: PROTOCOL_FALLBACK_MAX_TOKENS };
23004
23053
  }
23005
23054
  function resolveNativeAnthropicMessagesConfigFromGatewayConfig(cfg, options) {
23006
23055
  const slice = resolveProviderSliceFromGatewayConfig(cfg, {
@@ -25161,20 +25210,18 @@ function enqueueCompactMemoryDistill(agentId, artifact, cfg) {
25161
25210
  // src/project/project-context-prompt.ts
25162
25211
  init_current_project_context();
25163
25212
 
25164
- // src/mobile/context-compact/native-transcript-budget.ts
25213
+ // src/mobile/context-compact/context-budget-gate.ts
25165
25214
  init_native_reply_transcript();
25166
- init_transcript_media_sanitize();
25167
- var IMAGE_BLOCK_BUDGET_BYTES = 8 * 1024;
25168
25215
 
25169
25216
  // src/mobile/model-context-window-budget.ts
25170
25217
  var MIN_TRANSCRIPT_BUDGET_BYTES = 64 * 1024;
25171
- var DEFAULT_MAX_NATIVE_TRANSCRIPT_BUDGET_BYTES = 128 * 1024;
25218
+ var DEFAULT_TRANSCRIPT_BUDGET_BYTES = 512 * 1024;
25172
25219
  var HARD_MAX_TRANSCRIPT_BUDGET_BYTES = 4 * 1024 * 1024;
25173
25220
 
25174
25221
  // src/mobile/context-compact/context-budget-gate.ts
25175
25222
  function resolveContextBudgetSignalSource() {
25176
25223
  const raw = (process.env.XKZOOM_CONTEXT_BUDGET_SOURCE ?? "native").trim().toLowerCase();
25177
- if (raw === "legacy" || raw === "legacy" || raw === "jsonl") {
25224
+ if (raw === "legacy" || raw === "jsonl") {
25178
25225
  return "gateway-jsonl";
25179
25226
  }
25180
25227
  return "native-transcript";
@@ -26056,52 +26103,28 @@ function uniqueAppend(existing, incoming, max) {
26056
26103
  function normalizeEvidenceRefs(refs) {
26057
26104
  return uniqueAppend([], refs, 20);
26058
26105
  }
26059
- function hasRepeatedToolWithoutEvidence(events) {
26060
- const recent = events.filter((event) => event.kind === "tool").slice(-3);
26061
- if (recent.length < 3) {
26062
- return false;
26063
- }
26064
- const [first] = recent;
26065
- return recent.every(
26066
- (event) => event.kind === "tool" && event.toolName && event.toolName === first.toolName && event.toolArgsHash && event.toolArgsHash === first.toolArgsHash && event.newEvidence !== true
26067
- );
26068
- }
26069
- function hasRepeatedToolFailure(events) {
26070
- const recentFailures = events.filter((event) => event.kind === "tool" && event.outcome === "failed").slice(-3);
26071
- if (recentFailures.length < 3) {
26072
- return false;
26073
- }
26074
- const first = recentFailures[0];
26075
- return recentFailures.every(
26076
- (event) => event.toolName && event.toolName === first?.toolName && (!first?.toolArgsHash || event.toolArgsHash === first.toolArgsHash)
26077
- );
26078
- }
26079
- function hasRepeatedFailure(events) {
26080
- const recentFailures = events.filter((event) => event.kind === "failure").slice(-3);
26081
- if (recentFailures.length < 3) {
26082
- return false;
26083
- }
26084
- const firstSummary = recentFailures[0]?.summary.trim().toLowerCase();
26085
- return Boolean(firstSummary) && recentFailures.every((event) => event.summary.trim().toLowerCase() === firstSummary);
26086
- }
26087
- function evaluateLoopBreaker(events, at) {
26088
- if (hasRepeatedToolFailure(events)) {
26089
- return { tripped: true, reason: "repeated_tool_failure", at };
26090
- }
26091
- if (hasRepeatedToolWithoutEvidence(events)) {
26092
- return { tripped: true, reason: "repeated_tool_without_new_evidence", at };
26093
- }
26094
- if (hasRepeatedFailure(events)) {
26095
- return { tripped: true, reason: "repeated_failure", at };
26096
- }
26097
- return void 0;
26098
- }
26099
26106
  async function readRunLedger(taskId) {
26100
26107
  return readJsonFile(resolveRunLedgerPath(taskId));
26101
26108
  }
26102
26109
  async function readRunLedgerEvents(taskId, limit) {
26103
26110
  return readJsonLines(resolveRunLedgerEventLogPath(taskId), limit);
26104
26111
  }
26112
+ function readLegacyRunLedgerLoopMarker(ledger) {
26113
+ if (!ledger) return null;
26114
+ const marker = ledger.loopBreaker;
26115
+ if (!marker || typeof marker !== "object") return null;
26116
+ const record = marker;
26117
+ const reason = typeof record.reason === "string" ? record.reason.trim() : "";
26118
+ const at = typeof record.at === "string" ? record.at.trim() : "";
26119
+ return {
26120
+ tripped: record.tripped === true,
26121
+ reason: reason || "legacy_loop_marker",
26122
+ at: at || "unknown"
26123
+ };
26124
+ }
26125
+ function legacyRunLedgerLoopMarkerTripped(ledger) {
26126
+ return readLegacyRunLedgerLoopMarker(ledger)?.tripped === true;
26127
+ }
26105
26128
  async function updateRunLedger(input) {
26106
26129
  if (!input.taskId.trim()) {
26107
26130
  throw new Error("run_ledger.update requires taskId");
@@ -26155,12 +26178,7 @@ async function updateRunLedger(input) {
26155
26178
  openLoops,
26156
26179
  ...input.nextStep ? { nextStep: input.nextStep.trim() } : base.nextStep ? { nextStep: base.nextStep } : {}
26157
26180
  };
26158
- const loopBreaker = evaluateLoopBreaker(events, now);
26159
- if (loopBreaker) {
26160
- next.loopBreaker = loopBreaker;
26161
- } else if (base.loopBreaker?.tripped) {
26162
- next.loopBreaker = base.loopBreaker;
26163
- }
26181
+ delete next.loopBreaker;
26164
26182
  const logEntry = {
26165
26183
  schemaVersion: RUN_LEDGER_EVENT_SCHEMA_VERSION,
26166
26184
  taskId: input.taskId,
@@ -26186,8 +26204,9 @@ function formatRunLedgerBlock(ledger) {
26186
26204
  const failures = ledger.failures.slice(-5).map((failure) => `- ${failure}`);
26187
26205
  const artifacts = ledger.artifactRefs.slice(-6).map((artifact) => `- ${artifact}`);
26188
26206
  const loops = ledger.openLoops.slice(-6).map((loop) => `- ${loop}`);
26189
- const breaker = ledger.loopBreaker?.tripped ? `
26190
- Loop breaker: ${ledger.loopBreaker.reason} at ${ledger.loopBreaker.at}` : "";
26207
+ const legacyLoopMarker = readLegacyRunLedgerLoopMarker(ledger);
26208
+ const breaker = legacyLoopMarker?.tripped ? `
26209
+ Legacy loop marker (not a runtime blocker): ${legacyLoopMarker.reason} at ${legacyLoopMarker.at}` : "";
26191
26210
  return [
26192
26211
  "## Active Task Ledger",
26193
26212
  `Task: ${ledger.taskId}`,
@@ -28992,6 +29011,7 @@ var import_node_path51 = __toESM(require("path"));
28992
29011
  var import_node_crypto21 = require("crypto");
28993
29012
  var import_node_fs52 = require("fs");
28994
29013
  var import_node_path49 = __toESM(require("path"));
29014
+ init_delivery_verification();
28995
29015
  init_team_memory_runtime();
28996
29016
  init_memory_event();
28997
29017
  init_memory_consolidate();
@@ -29024,13 +29044,6 @@ function lastCheckpointAtMs(ledger) {
29024
29044
  }
29025
29045
  return parseIsoMs(ledger.createdAt);
29026
29046
  }
29027
- function hasCheckpointAfter(ledger, at) {
29028
- const atMs = parseIsoMs(at);
29029
- if (atMs === null) {
29030
- return false;
29031
- }
29032
- return ledger.events.some((event) => event.kind === "checkpoint" && (parseIsoMs(event.at) ?? 0) >= atMs);
29033
- }
29034
29047
  function evaluateRunLedgerCheckpoint(ledger, policy = {}, now = /* @__PURE__ */ new Date()) {
29035
29048
  const lastEvent = ledger.events.at(-1);
29036
29049
  const lastIdx = lastCheckpointIndex(ledger.events);
@@ -29042,14 +29055,6 @@ function evaluateRunLedgerCheckpoint(ledger, policy = {}, now = /* @__PURE__ */
29042
29055
  if (lastEvent?.kind === "checkpoint" || eventsSinceLastCheckpoint <= 0) {
29043
29056
  return { shouldCheckpoint: false, eventsSinceLastCheckpoint, msSinceLastCheckpoint };
29044
29057
  }
29045
- if (policy.forceOnLoopBreaker !== false && ledger.loopBreaker?.tripped && !hasCheckpointAfter(ledger, ledger.loopBreaker.at)) {
29046
- return {
29047
- shouldCheckpoint: true,
29048
- reason: "loop_breaker",
29049
- eventsSinceLastCheckpoint,
29050
- msSinceLastCheckpoint
29051
- };
29052
- }
29053
29058
  if (eventsSinceLastCheckpoint >= maxEvents) {
29054
29059
  return {
29055
29060
  shouldCheckpoint: true,
@@ -29116,15 +29121,6 @@ function stableNormalize(value, seen = /* @__PURE__ */ new WeakSet()) {
29116
29121
  function sha256Hex(value) {
29117
29122
  return (0, import_node_crypto19.createHash)("sha256").update(value).digest("hex");
29118
29123
  }
29119
- function lastNonCheckpointEvents(ledger, limit) {
29120
- return ledger.events.filter((event) => event.kind !== "checkpoint").slice(-limit);
29121
- }
29122
- function currentWouldRepeatNoEvidence(ledger, toolName, toolArgsHash) {
29123
- const recent = lastNonCheckpointEvents(ledger, 2);
29124
- return recent.length === 2 && recent.every(
29125
- (event) => event.kind === "tool" && event.toolName === toolName && event.toolArgsHash === toolArgsHash && event.newEvidence !== true
29126
- );
29127
- }
29128
29124
  function hasNewEvidence(outcome, resultContent) {
29129
29125
  return outcome === "ok" && typeof resultContent === "string" && resultContent.trim().length > 0;
29130
29126
  }
@@ -29141,55 +29137,6 @@ function deriveRunLedgerToolArgsHash(toolName, toolArgs) {
29141
29137
  async function assessLongRunToolCall(input) {
29142
29138
  const toolArgsHash = deriveRunLedgerToolArgsHash(input.toolName, input.toolArgs);
29143
29139
  const ledger = await readRunLedger(input.taskId);
29144
- if (ledger?.loopBreaker?.tripped) {
29145
- return {
29146
- allowed: false,
29147
- code: "RUN_LEDGER_LOOP_BREAKER",
29148
- reason: ledger.loopBreaker.reason,
29149
- detail: `RunLedger ${input.taskId} tripped loop breaker at ${ledger.loopBreaker.at}; checkpoint or change strategy before executing more tools.`,
29150
- toolArgsHash,
29151
- ledger,
29152
- checkpointed: false
29153
- };
29154
- }
29155
- if (ledger && currentWouldRepeatNoEvidence(ledger, input.toolName, toolArgsHash)) {
29156
- const updated = await updateRunLedger({
29157
- taskId: input.taskId,
29158
- agentId: input.agentId,
29159
- ...input.sessionId ? { sessionId: input.sessionId } : {},
29160
- ...input.teamId ? { teamId: input.teamId } : {},
29161
- goal: ledger.goal,
29162
- phase: "loop_breaker",
29163
- event: {
29164
- kind: "tool",
29165
- summary: `blocked repeated no-evidence tool call ${input.toolName}`,
29166
- toolName: input.toolName,
29167
- toolArgsHash,
29168
- outcome: "failed",
29169
- newEvidence: false,
29170
- evidenceRefs: input.evidenceRefs
29171
- },
29172
- artifactRefs: ledger.artifactRefs,
29173
- openLoops: [
29174
- ...ledger.openLoops,
29175
- `blocked repeated no-evidence tool call: ${input.toolName} args=${toolArgsHash}`
29176
- ],
29177
- nextStep: "Stop repeating the same tool arguments; inspect prior evidence, change strategy, or ask for clarification."
29178
- });
29179
- const checkpoint = await maybeCheckpointRunLedger({
29180
- ledger: updated,
29181
- policy: { forceOnLoopBreaker: true }
29182
- });
29183
- return {
29184
- allowed: false,
29185
- code: "RUN_LEDGER_REPEAT_TOOL_NO_EVIDENCE",
29186
- reason: "repeated_tool_without_new_evidence",
29187
- detail: `The previous two non-checkpoint ledger events already used ${input.toolName} with argsHash=${toolArgsHash} and no new evidence.`,
29188
- toolArgsHash,
29189
- ledger: checkpoint.ledger,
29190
- checkpointed: checkpoint.checkpointed
29191
- };
29192
- }
29193
29140
  return { allowed: true, toolArgsHash, ledger };
29194
29141
  }
29195
29142
  async function recordLongRunToolResult(input) {
@@ -29644,7 +29591,7 @@ async function evalProjectDetail(runId) {
29644
29591
  day: 2,
29645
29592
  category: "failure",
29646
29593
  query: "What Day 2 failure reason must be remembered for repeated tools?",
29647
- expected: "Day 2 failure shield: repeated same-tool no-evidence calls must trip RUN_LEDGER_REPEAT_TOOL_NO_EVIDENCE before another execution.",
29594
+ expected: "Day 2 failure shield: repeated same-tool no-evidence calls stay recorded in RunLedger, while maxTurns, prompt guidance, and is_error tool results steer recovery instead of a runtime blocker.",
29648
29595
  evidenceRef: "eval:project:day2:failure"
29649
29596
  },
29650
29597
  {
@@ -29878,6 +29825,53 @@ async function evalEvidenceTrace(runId) {
29878
29825
  }
29879
29826
  );
29880
29827
  }
29828
+ async function evalToolResultCompletionEvidence(_runId) {
29829
+ const verbalCompletionClaim = "\u5DF2\u5B8C\u6210\u4FEE\u6539\uFF0C\u5171\u5904\u7406 8 \u4E2A\u6587\u4EF6";
29830
+ const noToolResultVerification = assessDeliveryVerification(verbalCompletionClaim, []);
29831
+ const unrelatedSuccessToolCalls = [
29832
+ {
29833
+ toolCallId: "eval-agents-list-1",
29834
+ name: "agents_list",
29835
+ status: "success",
29836
+ result: JSON.stringify({ ok: true, data: [{ id: "dev" }] }),
29837
+ startedAt: "2026-01-01T00:00:00.000Z"
29838
+ }
29839
+ ];
29840
+ const unrelatedToolVerification = assessDeliveryVerification(verbalCompletionClaim, unrelatedSuccessToolCalls);
29841
+ const evidenceBackedToolCalls = [
29842
+ {
29843
+ toolCallId: "eval-write-1",
29844
+ name: "write",
29845
+ status: "success",
29846
+ args: { path: "docs/report.md" },
29847
+ result: JSON.stringify({
29848
+ ok: true,
29849
+ tool: "write",
29850
+ data: {
29851
+ path: "docs/report.md",
29852
+ bytesWritten: 128
29853
+ }
29854
+ }),
29855
+ startedAt: "2026-01-01T00:00:01.000Z"
29856
+ }
29857
+ ];
29858
+ const evidenceToolVerification = assessDeliveryVerification(verbalCompletionClaim, evidenceBackedToolCalls);
29859
+ return caseFromCheck(
29860
+ "tool-result-completion-evidence-boundary",
29861
+ "evidence_trace",
29862
+ noToolResultVerification === "unverified" && unrelatedToolVerification === "unverified" && evidenceToolVerification === "verified",
29863
+ "Verbal completion claims fail without matching tool_result evidence and pass only when an evidence-backed tool result is attached.",
29864
+ ["src/mobile/group/delivery-verification.ts", "eval:tool-result-completion-evidence"],
29865
+ {
29866
+ noToolResultVerification,
29867
+ unrelatedToolVerification,
29868
+ evidenceToolVerification,
29869
+ matchingToolResultCount: 0,
29870
+ unrelatedSuccessToolCount: unrelatedSuccessToolCalls.length,
29871
+ evidenceBackedToolCount: evidenceBackedToolCalls.length
29872
+ }
29873
+ );
29874
+ }
29881
29875
  async function evalTeamIsolation(runId, workspaceRoot) {
29882
29876
  const memberAgentIds = [
29883
29877
  `eval-agent-architect-${runId}`,
@@ -30020,7 +30014,7 @@ async function evalLongRun(runId) {
30020
30014
  evidenceRefs: ["eval:long-run:start"],
30021
30015
  newEvidence: true
30022
30016
  },
30023
- openLoops: ["verify checkpoint cadence", "verify idempotent side effects", "verify resume after loop breaker"],
30017
+ openLoops: ["verify checkpoint cadence", "verify idempotent side effects", "verify resume after repeated no-evidence telemetry"],
30024
30018
  nextStep: "Continue bounded multi-tool execution with durable ledger checkpoints."
30025
30019
  });
30026
30020
  for (let step = 0; step < totalSteps; step += 1) {
@@ -30031,7 +30025,7 @@ async function evalLongRun(runId) {
30031
30025
  shard: `shard-${step % 11}`,
30032
30026
  query: `memory-runtime-v2-long-run-${runId}-${step}`
30033
30027
  };
30034
- const guard = await assessLongRunToolCall({
30028
+ const guard2 = await assessLongRunToolCall({
30035
30029
  taskId,
30036
30030
  agentId,
30037
30031
  sessionId,
@@ -30039,15 +30033,6 @@ async function evalLongRun(runId) {
30039
30033
  toolArgs,
30040
30034
  evidenceRefs: [`eval:long-run:guard:${step}`]
30041
30035
  });
30042
- if (!guard.allowed) {
30043
- return failCase(
30044
- "long-run-7x24-recovery",
30045
- "long_run",
30046
- `Unexpected guard block during varied 7x24 run: ${guard.reason}`,
30047
- ["eval:long-run:unexpected-block"],
30048
- { step, guard }
30049
- );
30050
- }
30051
30036
  const result = await recordLongRunToolResult({
30052
30037
  taskId,
30053
30038
  agentId,
@@ -30109,13 +30094,13 @@ async function evalLongRun(runId) {
30109
30094
  evidenceRefs: [`eval:long-run:no-evidence:${i}`]
30110
30095
  });
30111
30096
  }
30112
- const blocked = await assessLongRunToolCall({
30097
+ const guard = await assessLongRunToolCall({
30113
30098
  taskId,
30114
30099
  agentId,
30115
30100
  sessionId,
30116
30101
  toolName: repeatedToolName,
30117
30102
  toolArgs: repeatedToolArgs,
30118
- evidenceRefs: ["eval:long-run:no-evidence:block"]
30103
+ evidenceRefs: ["eval:long-run:no-evidence:record"]
30119
30104
  });
30120
30105
  const resumedLedger = await readRunLedger(taskId);
30121
30106
  const eventLog = await readRunLedgerEvents(taskId);
@@ -30129,7 +30114,7 @@ async function evalLongRun(runId) {
30129
30114
  taskId,
30130
30115
  project: null,
30131
30116
  agentWorkspaceRoot: workspaceRootForLongRun(runId),
30132
- queryText: "resume after repeated no evidence loop breaker",
30117
+ queryText: "resume after repeated no-evidence telemetry without a runtime blocker",
30133
30118
  recentTurnsBlock: "Runtime resumes after a synthetic 7x24 tool loop without replaying the full event log.",
30134
30119
  budgetClass: "balanced"
30135
30120
  });
@@ -30138,13 +30123,14 @@ async function evalLongRun(runId) {
30138
30123
  const appendOnlyHasStart = eventLog.some((entry) => entry.event.summary.includes("Start synthetic 7x24"));
30139
30124
  const appendOnlyHasFinalStep = eventLog.some((entry) => entry.event.evidenceRefs.includes(`eval:long-run:step:${totalSteps - 1}`));
30140
30125
  const snapshotBounded = (resumedLedger?.events.length ?? Number.POSITIVE_INFINITY) <= 200;
30141
- const resumeContainsBreaker = renderedResume.includes("Loop breaker: repeated_tool_without_new_evidence") && renderedResume.includes("Stop repeating the same tool arguments");
30126
+ const resumeContainsRepeatedNoEvidence = renderedResume.includes("owned tool web_fetch outcome=inconclusive") || renderedResume.includes("same-empty-result");
30127
+ const legacyLoopMarkerTripped = legacyRunLedgerLoopMarkerTripped(resumedLedger);
30142
30128
  return caseFromCheck(
30143
30129
  "long-run-7x24-recovery",
30144
30130
  "long_run",
30145
- !blocked.allowed && blocked.code === "RUN_LEDGER_REPEAT_TOOL_NO_EVIDENCE" && blocked.checkpointed && checkpointCount >= 8 && checkpointEventCount >= checkpointCount && sideEffectExecuteCount === 1 && sideEffectReplayCount === 1 && snapshotBounded && eventLog.length > totalSteps && appendOnlyHasStart && appendOnlyHasFinalStep && recentEvents.at(-1)?.event.kind === "checkpoint" && resumedLedger?.loopBreaker?.reason === "repeated_tool_without_new_evidence" && resumeContainsBreaker,
30146
- "A 7x24 synthetic multi-tool run checkpoints durably, replays idempotent side effects, trips the loop breaker on repeated no-evidence calls, and resumes from bounded ledger state plus append-only event log.",
30147
- ["eval:long-run:start", `ledger:${taskId}`, "eval:long-run:idempotency:complete", "eval:long-run:no-evidence:block"],
30131
+ guard.allowed && checkpointCount >= 8 && checkpointEventCount >= checkpointCount && sideEffectExecuteCount === 1 && sideEffectReplayCount === 1 && snapshotBounded && eventLog.length > totalSteps && appendOnlyHasStart && appendOnlyHasFinalStep && recentEvents.at(-1)?.event.kind === "tool" && !legacyLoopMarkerTripped && resumeContainsRepeatedNoEvidence,
30132
+ "A 7x24 synthetic multi-tool run checkpoints durably, replays idempotent side effects, records repeated no-evidence calls without blocking execution, and resumes from bounded ledger state plus append-only event log.",
30133
+ ["eval:long-run:start", `ledger:${taskId}`, "eval:long-run:idempotency:complete", "eval:long-run:no-evidence:record"],
30148
30134
  {
30149
30135
  simulatedHours,
30150
30136
  totalToolSteps: totalSteps,
@@ -30154,13 +30140,12 @@ async function evalLongRun(runId) {
30154
30140
  checkpointEventCount,
30155
30141
  sideEffectExecuteCount,
30156
30142
  sideEffectReplayCount,
30157
- blockedCode: blocked.allowed ? null : blocked.code,
30158
- blockedReason: blocked.allowed ? null : blocked.reason,
30159
- blockedCheckpointed: blocked.allowed ? false : blocked.checkpointed,
30143
+ guardAllowed: guard.allowed,
30144
+ legacyLoopMarkerTripped,
30160
30145
  appendOnlyHasStart,
30161
30146
  appendOnlyHasFinalStep,
30162
30147
  latestRecentEventKind: recentEvents.at(-1)?.event.kind,
30163
- resumeContainsBreaker
30148
+ resumeContainsRepeatedNoEvidence
30164
30149
  }
30165
30150
  );
30166
30151
  }
@@ -30695,6 +30680,7 @@ async function runMemoryRuntimeV2SelfEval(input = {}) {
30695
30680
  evalContinuity,
30696
30681
  evalProjectDetail,
30697
30682
  evalEvidenceTrace,
30683
+ evalToolResultCompletionEvidence,
30698
30684
  evalTeamIsolation,
30699
30685
  evalLongRun,
30700
30686
  evalSideEffect,
@@ -31785,7 +31771,7 @@ function buildGates(input) {
31785
31771
  category: "long_run",
31786
31772
  title: "7x24 durable tool execution",
31787
31773
  status: casePassed(evalReport, "long_run") && casePassed(evalReport, "side_effect") ? "proven" : evalFailed ? "blocked" : "partial",
31788
- summary: "Long tasks must checkpoint, keep append-only event logs, replay idempotent side effects, and trip loop breakers on repeated no-evidence work.",
31774
+ summary: "Long tasks must checkpoint, keep append-only event logs, replay idempotent side effects, and preserve repeated no-evidence telemetry without blocking tool execution.",
31789
31775
  evidenceRefs: ["src/mobile/memory-runtime-v2/long-run-guard.ts", "src/mobile/memory-runtime-v2/tool-side-effect.ts", ...caseEvidence(evalReport, "long_run"), ...caseEvidence(evalReport, "side_effect")],
31790
31776
  blockers: evalFailed ? ["Latest long-run or side-effect eval did not pass."] : [],
31791
31777
  nextActions: casePassed(evalReport, "long_run") ? ["Add wall-clock soak and process-restart recovery evidence."] : ["Run the 7x24 synthetic long-run eval."]
@@ -33366,6 +33352,105 @@ function appendChainAbortNotice(stderr, command, exitCode) {
33366
33352
 
33367
33353
  ${notice}` : notice;
33368
33354
  }
33355
+ function extractProbeLeadingToken(command) {
33356
+ let cmd = command.trim();
33357
+ const psMatch = /^(?:powershell|pwsh)(?:\.exe)?\b[\s\S]*?\s-(?:c|command)\s+(.+)$/i.exec(cmd);
33358
+ if (psMatch?.[1]) {
33359
+ cmd = psMatch[1].trim().replace(/^["'&{}\s]+/, "");
33360
+ }
33361
+ const first = cmd.split(/[\s;|]+/, 1)[0] ?? "";
33362
+ return first.replace(/^["']+/, "").replace(/\.exe$/i, "").toLowerCase();
33363
+ }
33364
+ var PROBE_COMMAND_TOKENS = /* @__PURE__ */ new Set([
33365
+ "findstr",
33366
+ "find",
33367
+ "where",
33368
+ "grep",
33369
+ "rg",
33370
+ "egrep",
33371
+ "fgrep",
33372
+ "dir",
33373
+ "get-command",
33374
+ "get-childitem",
33375
+ "gci"
33376
+ ]);
33377
+ function execNonzeroIsBenignProbe(record) {
33378
+ if (record.exitCode !== 1) {
33379
+ return false;
33380
+ }
33381
+ if (String(record.stderr ?? "").trim()) {
33382
+ return false;
33383
+ }
33384
+ const token = extractProbeLeadingToken(record.command);
33385
+ if (PROBE_COMMAND_TOKENS.has(token)) {
33386
+ return true;
33387
+ }
33388
+ if (token === "pip" || token === "pip3") {
33389
+ return /\bpip3?\b[\s\S]*\b(show|index)\b/i.test(record.command);
33390
+ }
33391
+ return false;
33392
+ }
33393
+ function execExitZeroLooksInconclusive(record) {
33394
+ const stdout = String(record.stdout ?? "").trim();
33395
+ const stderr = String(record.stderr ?? "").trim();
33396
+ const psShellError = /CommandNotFoundException|无法将|is not recognized as an internal or external command/i.test(stderr);
33397
+ return !stdout && Boolean(stderr) || psShellError;
33398
+ }
33399
+ function classifyOwnedExecResultSemantic(result) {
33400
+ if (result.background === true) {
33401
+ return { isError: false, summary: "exec started (background)" };
33402
+ }
33403
+ const stdout = String(result.stdout ?? "").trim();
33404
+ const stderr = String(result.stderr ?? "").trim();
33405
+ if (result.exitCode === 0) {
33406
+ if (execExitZeroLooksInconclusive(result)) {
33407
+ return {
33408
+ isError: true,
33409
+ code: "EXEC_INCONCLUSIVE",
33410
+ error: "exec exit 0 but output inconclusive (stderr indicates shell failure)",
33411
+ detail: stderr || "empty stdout with stderr errors \u2014 not a verification"
33412
+ };
33413
+ }
33414
+ return {
33415
+ isError: false,
33416
+ summary: stdout ? `exit 0 \u2014 ${stdout.slice(0, 240)}` : "exit 0 (INCONCLUSIVE: empty stdout \u2014 exit 0 alone is not a verification)"
33417
+ };
33418
+ }
33419
+ if (execNonzeroIsBenignProbe(result)) {
33420
+ return {
33421
+ isError: false,
33422
+ summary: stdout ? `exit 1 (probe no match) \u2014 ${stdout.slice(0, 240)}` : "exit 1 (probe returned no match / not found \u2014 this is a valid empty result, not a command error)"
33423
+ };
33424
+ }
33425
+ if (result.exitCode === 124) {
33426
+ return {
33427
+ isError: true,
33428
+ code: "EXEC_TIMEOUT",
33429
+ error: `command timed out (exit ${result.exitCode})`,
33430
+ detail: stderr || stdout || void 0
33431
+ };
33432
+ }
33433
+ if (stderr.includes("[XKZOOM] command chain")) {
33434
+ return {
33435
+ isError: true,
33436
+ code: "EXEC_CHAIN_ABORT",
33437
+ error: `command chain aborted (exit ${result.exitCode})`,
33438
+ detail: stderr || stdout || void 0
33439
+ };
33440
+ }
33441
+ return {
33442
+ isError: true,
33443
+ code: "EXEC_NONZERO_EXIT",
33444
+ error: `command exited with code ${result.exitCode}`,
33445
+ detail: stderr || stdout || void 0
33446
+ };
33447
+ }
33448
+ function withOwnedExecSemantics(result) {
33449
+ return {
33450
+ ...result,
33451
+ semantic: result.semantic ?? classifyOwnedExecResultSemantic(result)
33452
+ };
33453
+ }
33369
33454
  function detectOutOfRootAbsolutePaths(command, root) {
33370
33455
  const rootAbs = path43.resolve(root);
33371
33456
  const out = [];
@@ -33390,7 +33475,7 @@ function readOwnedExecParams(params) {
33390
33475
  async function runOwnedExec(params) {
33391
33476
  const primitive = await runExecPrimitiveAction({ root: params.root, toolParams: params.toolParams });
33392
33477
  if (primitive) {
33393
- return primitive;
33478
+ return withOwnedExecSemantics(primitive);
33394
33479
  }
33395
33480
  const parsed = readOwnedExecParams(params.toolParams);
33396
33481
  if (!parsed.command?.trim()) throw new Error("command is required (or use action=route_smoke|npm_script)");
@@ -33445,7 +33530,7 @@ async function runOwnedExec(params) {
33445
33530
  spawnPty: params.spawnPty,
33446
33531
  now: params.now
33447
33532
  });
33448
- return {
33533
+ return withOwnedExecSemantics({
33449
33534
  command: effectiveCommand,
33450
33535
  cwd,
33451
33536
  activeRoot: rootAbs,
@@ -33456,7 +33541,7 @@ async function runOwnedExec(params) {
33456
33541
  sessionId: started.sessionId,
33457
33542
  ...started.pid !== void 0 ? { pid: started.pid } : {},
33458
33543
  ...warningList ? { warnings: warningList } : {}
33459
- };
33544
+ });
33460
33545
  }
33461
33546
  const timeoutSec = resolveForegroundExecTimeoutSec(effectiveCommand, parsed.timeoutSec);
33462
33547
  const timeoutMs = timeoutSec * 1e3;
@@ -33472,7 +33557,7 @@ async function runOwnedExec(params) {
33472
33557
  windowsHide: true,
33473
33558
  encoding: "utf8"
33474
33559
  });
33475
- return {
33560
+ return withOwnedExecSemantics({
33476
33561
  command: effectiveCommand,
33477
33562
  cwd,
33478
33563
  activeRoot: rootAbs,
@@ -33480,14 +33565,14 @@ async function runOwnedExec(params) {
33480
33565
  stdout: truncateCapture2(String(stdout ?? "")),
33481
33566
  stderr: truncateCapture2(String(stderr ?? "")),
33482
33567
  ...warningList ? { warnings: warningList } : {}
33483
- };
33568
+ });
33484
33569
  } catch (err) {
33485
33570
  const record = err;
33486
33571
  const exitCode = typeof record.code === "number" ? record.code : record.killed ? 124 : 1;
33487
33572
  const stderr = truncateCapture2(
33488
33573
  appendChainAbortNotice(String(record.stderr ?? ""), effectiveCommand, exitCode)
33489
33574
  );
33490
- return {
33575
+ return withOwnedExecSemantics({
33491
33576
  command: effectiveCommand,
33492
33577
  cwd,
33493
33578
  activeRoot: rootAbs,
@@ -33495,7 +33580,7 @@ async function runOwnedExec(params) {
33495
33580
  stdout: truncateCapture2(String(record.stdout ?? "")),
33496
33581
  stderr,
33497
33582
  ...warningList ? { warnings: warningList } : {}
33498
- };
33583
+ });
33499
33584
  }
33500
33585
  }
33501
33586
  var execTool = defineTool({
@@ -35715,8 +35800,12 @@ async function readOwnedMemoryFile(params) {
35715
35800
  const relPath = path45.relative(workspaceDir, absPath).replace(/\\/g, "/");
35716
35801
  const allowedWorkspace = relPath.length > 0 && !relPath.startsWith("..") && !path45.isAbsolute(relPath) && isMemoryPath(relPath);
35717
35802
  const allowedAdditional = allowedWorkspace ? false : await isAllowedAdditionalPath(workspaceDir, absPath, params.extraPaths);
35718
- if (!allowedWorkspace && !allowedAdditional) throw new Error("path required");
35719
- if (!absPath.endsWith(".md")) throw new Error("path required");
35803
+ if (!allowedWorkspace && !allowedAdditional) {
35804
+ throw new Error(
35805
+ "memory_get only reads MEMORY.md or memory/** \u2014 use read(scope=agent) for AGENTS.md/SOUL.md/USER.md."
35806
+ );
35807
+ }
35808
+ if (!absPath.endsWith(".md")) throw new Error("memory_get requires a .md path.");
35720
35809
  const stat4 = await statRegularFile(absPath);
35721
35810
  if (stat4.missing || !stat4.file) {
35722
35811
  return { text: "", path: relPath };
@@ -35743,7 +35832,7 @@ async function readOwnedMemoryFile(params) {
35743
35832
  }
35744
35833
  var memoryGetTool = defineTool({
35745
35834
  name: "memory_get",
35746
- doc: "Read a file from the agent's memory workspace (MEMORY.md, memory/**, USER.md).",
35835
+ doc: "Read a file from the agent's memory workspace (MEMORY.md or memory/**).",
35747
35836
  inputScope: "memory-workspace",
35748
35837
  properties: {
35749
35838
  path: { type: "string", description: "Memory file path, e.g. MEMORY.md or memory/notes/x.md." },
@@ -37227,13 +37316,13 @@ async function readOwnedFile(params) {
37227
37316
  };
37228
37317
  }
37229
37318
  if (offset === void 0 && limit === void 0) {
37230
- const preview = applyReadTextPreview(content, void 0, void 0);
37319
+ const preview2 = applyReadTextPreview(content, void 0, void 0);
37231
37320
  return {
37232
37321
  ...base,
37233
- text: preview.text,
37322
+ text: preview2.text,
37234
37323
  totalLines,
37235
- ...preview.textTruncated ? { textTruncated: true } : {},
37236
- returnedChars: preview.returnedChars
37324
+ ...preview2.textTruncated ? { textTruncated: true } : {},
37325
+ returnedChars: preview2.returnedChars
37237
37326
  };
37238
37327
  }
37239
37328
  const startIndex = offset !== void 0 ? offset - 1 : 0;
@@ -37949,20 +38038,20 @@ function buildOwnedWritePreviewLines(content, opts) {
37949
38038
  }
37950
38039
  function buildOwnedWriteUiSurface(params) {
37951
38040
  const languageHint = inferWriteLanguageId(params.relPath);
37952
- const preview = buildOwnedWritePreviewLines(params.content, {
38041
+ const preview2 = buildOwnedWritePreviewLines(params.content, {
37953
38042
  maxLines: params.previewMaxLines,
37954
38043
  maxChars: params.previewMaxChars
37955
38044
  });
37956
- const highlightInToolCard = preview.lines.length > 0 && languageHint.languageId !== "plaintext";
38045
+ const highlightInToolCard = preview2.lines.length > 0 && languageHint.languageId !== "plaintext";
37957
38046
  return {
37958
38047
  surfaceVersion: OWNED_WRITE_UI_SURFACE_VERSION,
37959
38048
  path: params.relPath.replace(/\\/g, "/"),
37960
38049
  languageHint,
37961
38050
  highlightInToolCard,
37962
38051
  contentLength: params.bytesWritten,
37963
- lineCount: preview.lineCount,
37964
- previewLines: preview.lines,
37965
- previewTruncated: preview.truncated
38052
+ lineCount: preview2.lineCount,
38053
+ previewLines: preview2.lines,
38054
+ previewTruncated: preview2.truncated
37966
38055
  };
37967
38056
  }
37968
38057
 
@@ -38250,6 +38339,19 @@ var OWNED_TURN_TOOL_NAMES = OWNED_TURN_TOOLS.map((tool) => tool.name);
38250
38339
  function resolveOwnedToolNamesByTier(tier) {
38251
38340
  return OWNED_TURN_TOOL_CATALOG.filter((entry) => entry.routerTier === tier).map((entry) => entry.tool.name);
38252
38341
  }
38342
+ (() => {
38343
+ const derived = new Set(OWNED_INTERNAL_TOOL_CATALOG.map((entry) => entry.tool.name));
38344
+ for (const name of derived) {
38345
+ if (!OWNED_INTERNAL_TOOL_NAMES.has(name)) {
38346
+ throw new Error(`OWNED_INTERNAL_TOOL_NAMES missing internal tool: ${name}`);
38347
+ }
38348
+ }
38349
+ for (const name of OWNED_INTERNAL_TOOL_NAMES) {
38350
+ if (!derived.has(name)) {
38351
+ throw new Error(`OWNED_INTERNAL_TOOL_NAMES has stale internal tool: ${name}`);
38352
+ }
38353
+ }
38354
+ })();
38253
38355
  function parseToolNameList(raw) {
38254
38356
  if (!raw) return [];
38255
38357
  return raw.split(",").map((s) => s.trim()).filter(Boolean);
@@ -38387,28 +38489,49 @@ function classifyToolExecutionErrorMessage(message) {
38387
38489
  }
38388
38490
  return "EXEC_FAILED";
38389
38491
  }
38390
- function classifyExecFailureCode(record) {
38391
- const exitCode = typeof record.exitCode === "number" ? record.exitCode : 1;
38392
- const stderr = String(record.stderr ?? "");
38393
- if (exitCode === 124) {
38394
- return "EXEC_TIMEOUT";
38492
+ var OWNED_TOOL_RESULT_CODES = /* @__PURE__ */ new Set([
38493
+ "EMPTY_TOOL_INPUT",
38494
+ "PARTIAL_TOOL_INPUT",
38495
+ "UNPARSEABLE_TOOL_INPUT",
38496
+ "TOOL_NOT_AVAILABLE",
38497
+ "TOOL_CALL_GATE_DENIED",
38498
+ "VALIDATION_ERROR",
38499
+ "SIDE_EFFECT_PENDING",
38500
+ "SIDE_EFFECT_REPLAY_MISSING",
38501
+ "EXEC_FAILED",
38502
+ "EXEC_INCONCLUSIVE",
38503
+ "EXEC_NONZERO_EXIT",
38504
+ "EXEC_TIMEOUT",
38505
+ "EXEC_CHAIN_ABORT"
38506
+ ]);
38507
+ function readToolResultSemantic(record) {
38508
+ const raw = record.semantic;
38509
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
38510
+ return void 0;
38395
38511
  }
38396
- if (stderr.includes("[XKZOOM] command chain")) {
38397
- return "EXEC_CHAIN_ABORT";
38512
+ const semantic = raw;
38513
+ if (typeof semantic.isError !== "boolean") {
38514
+ return void 0;
38398
38515
  }
38399
- return "EXEC_NONZERO_EXIT";
38400
- }
38401
- function execExitZeroLooksInconclusive(record) {
38402
- const stdout = String(record.stdout ?? "").trim();
38403
- const stderr = String(record.stderr ?? "").trim();
38404
- const psShellError = /CommandNotFoundException|无法将|is not recognized as an internal or external command/i.test(stderr);
38405
- return !stdout && Boolean(stderr) || psShellError;
38516
+ const rawCode = typeof semantic.code === "string" ? semantic.code : void 0;
38517
+ const code = rawCode && OWNED_TOOL_RESULT_CODES.has(rawCode) ? rawCode : void 0;
38518
+ return {
38519
+ isError: semantic.isError,
38520
+ ...typeof semantic.summary === "string" && semantic.summary.trim() ? { summary: semantic.summary.trim() } : {},
38521
+ ...code ? { code } : {},
38522
+ ...typeof semantic.error === "string" && semantic.error.trim() ? { error: semantic.error.trim() } : {},
38523
+ ...typeof semantic.detail === "string" && semantic.detail.trim() ? { detail: semantic.detail.trim() } : {}
38524
+ };
38406
38525
  }
38407
38526
  function buildSuccessSummary(tool, data) {
38408
38527
  if (!data || typeof data !== "object" || Array.isArray(data)) {
38409
38528
  return void 0;
38410
38529
  }
38411
38530
  const record = data;
38531
+ const semantic = readToolResultSemantic(record);
38532
+ if (semantic?.summary) {
38533
+ return semantic.summary;
38534
+ }
38412
38535
  if (tool === "exec" && typeof record.exitCode === "number" && record.exitCode === 0) {
38413
38536
  if (record.background === true) {
38414
38537
  return "exec started (background)";
@@ -38431,9 +38554,9 @@ function buildSuccessSummary(tool, data) {
38431
38554
  }
38432
38555
  if (tool === "pdf" && typeof record.path === "string") {
38433
38556
  const text = typeof record.text === "string" ? record.text.trim() : "";
38434
- const preview = text ? text.slice(0, 240) : "";
38557
+ const preview2 = text ? text.slice(0, 240) : "";
38435
38558
  const pages = typeof record.pages === "number" ? `, ${record.pages} pages` : "";
38436
- return preview ? `pdf ${record.path}${pages} \u2014 ${preview}` : `pdf ${record.path}${pages}`;
38559
+ return preview2 ? `pdf ${record.path}${pages} \u2014 ${preview2}` : `pdf ${record.path}${pages}`;
38437
38560
  }
38438
38561
  if (tool === "memory_get" && typeof record.path === "string") {
38439
38562
  const text = typeof record.text === "string" ? record.text.trim() : "";
@@ -38457,29 +38580,26 @@ function normalizeOwnedToolExecuteOutcome(tool, result) {
38457
38580
  });
38458
38581
  return { envelope: envelope2, isError: true };
38459
38582
  }
38460
- if (tool === "exec" && typeof record.exitCode === "number" && record.exitCode === 0) {
38461
- if (execExitZeroLooksInconclusive(record)) {
38462
- const stderr = String(record.stderr ?? "").trim();
38583
+ const semantic = readToolResultSemantic(record);
38584
+ if (semantic) {
38585
+ if (semantic.isError) {
38463
38586
  const envelope2 = buildOwnedToolErrorEnvelope({
38464
38587
  tool,
38465
- code: "EXEC_NONZERO_EXIT",
38466
- error: "exec exit 0 but output inconclusive (stderr indicates shell failure)",
38467
- detail: stderr || "empty stdout with stderr errors \u2014 not a verification",
38588
+ code: semantic.code ?? "EXEC_FAILED",
38589
+ error: semantic.error ?? "tool execution failed",
38590
+ detail: semantic.detail,
38468
38591
  data: sanitized
38469
38592
  });
38470
38593
  return { envelope: envelope2, isError: true };
38471
38594
  }
38595
+ return { envelope: buildOwnedToolSuccessEnvelope(tool, sanitized), isError: false };
38472
38596
  }
38473
- if (typeof record.exitCode === "number" && record.exitCode !== 0) {
38474
- const stderr = String(record.stderr ?? "").trim();
38475
- const stdout = String(record.stdout ?? "").trim();
38476
- const code = tool === "exec" ? classifyExecFailureCode(record) : "EXEC_NONZERO_EXIT";
38477
- const error = code === "EXEC_TIMEOUT" ? `command timed out (exit ${record.exitCode})` : code === "EXEC_CHAIN_ABORT" ? `command chain aborted (exit ${record.exitCode})` : `command exited with code ${record.exitCode}`;
38597
+ if (tool === "exec" && typeof record.exitCode === "number") {
38478
38598
  const envelope2 = buildOwnedToolErrorEnvelope({
38479
38599
  tool,
38480
- code,
38481
- error,
38482
- detail: stderr || stdout || void 0,
38600
+ code: "EXEC_FAILED",
38601
+ error: "exec result missing semantic classification",
38602
+ detail: "exec.ts must attach semantic.isError before envelope normalization",
38483
38603
  data: sanitized
38484
38604
  });
38485
38605
  return { envelope: envelope2, isError: true };
@@ -39036,20 +39156,6 @@ async function safeAssessLongRunToolCall(input) {
39036
39156
  toolArgs: input.rawInput,
39037
39157
  evidenceRefs: [`tool_use:${input.toolUseId}`, `session:${input.deps.inboundSessionId}`]
39038
39158
  });
39039
- if (!decision.allowed) {
39040
- return {
39041
- toolArgsHash: decision.toolArgsHash,
39042
- blocked: ownedToolErrorResult(
39043
- input.toolUseId,
39044
- buildOwnedToolErrorEnvelope({
39045
- tool: input.toolName,
39046
- code: decision.code,
39047
- error: decision.reason,
39048
- detail: decision.detail
39049
- })
39050
- )
39051
- };
39052
- }
39053
39159
  return { toolArgsHash: decision.toolArgsHash };
39054
39160
  } catch {
39055
39161
  return {
@@ -39285,9 +39391,6 @@ async function executeAnthropicToolUse(params) {
39285
39391
  agentId,
39286
39392
  deps
39287
39393
  });
39288
- if (longRunGuard.blocked) {
39289
- return longRunGuard.blocked;
39290
- }
39291
39394
  let activeSideEffect = null;
39292
39395
  let resolvedToolContext = null;
39293
39396
  try {
@@ -39417,7 +39520,10 @@ async function executeAnthropicToolUse(params) {
39417
39520
  resultContent: String(errorBlock.content ?? ""),
39418
39521
  artifactRefs
39419
39522
  });
39420
- return errorBlock;
39523
+ return {
39524
+ ...errorBlock,
39525
+ content: String(errorBlock.content ?? "")
39526
+ };
39421
39527
  }
39422
39528
  }
39423
39529
  function buildMvpAnthropicToolSchemas() {
@@ -39577,6 +39683,135 @@ var ToolArgsTextDeltaExtractor = class {
39577
39683
  }
39578
39684
  };
39579
39685
 
39686
+ // src/mobile/tool-result-final-summary.ts
39687
+ var MAX_DETAIL_CHARS = 160;
39688
+ function collapseWhitespace(text) {
39689
+ return text.replace(/\s+/g, " ").trim();
39690
+ }
39691
+ function preview(text, maxChars = MAX_DETAIL_CHARS) {
39692
+ const cleaned = collapseWhitespace(text);
39693
+ if (cleaned.length <= maxChars) {
39694
+ return cleaned;
39695
+ }
39696
+ return `${cleaned.slice(0, maxChars - 1)}...`;
39697
+ }
39698
+ function stringValue2(value) {
39699
+ return typeof value === "string" ? value.trim() : "";
39700
+ }
39701
+ function isRecord7(value) {
39702
+ return typeof value === "object" && value !== null && !Array.isArray(value);
39703
+ }
39704
+ function toolResultContentToString(content) {
39705
+ if (typeof content === "string") {
39706
+ return content;
39707
+ }
39708
+ return content.map((c) => c.text).join("");
39709
+ }
39710
+ function pickFirstString(obj, keys) {
39711
+ for (const key of keys) {
39712
+ const value = stringValue2(obj[key]);
39713
+ if (value) {
39714
+ return value;
39715
+ }
39716
+ }
39717
+ return "";
39718
+ }
39719
+ function extractDetailFromParsedToolResult(parsed) {
39720
+ if (!isRecord7(parsed)) {
39721
+ return "";
39722
+ }
39723
+ const direct = pickFirstString(parsed, ["summary", "message", "text", "content", "error", "reason"]);
39724
+ if (direct) {
39725
+ return preview(direct);
39726
+ }
39727
+ const path52 = pickFirstString(parsed, ["path", "filePath", "targetPath", "outputPath", "deliverable_path"]);
39728
+ if (path52) {
39729
+ return `\u8DEF\u5F84 ${preview(path52, 120)}`;
39730
+ }
39731
+ const data = parsed.data;
39732
+ if (isRecord7(data)) {
39733
+ const dataMessage = pickFirstString(data, ["summary", "message", "text", "content", "error", "reason"]);
39734
+ if (dataMessage) {
39735
+ return preview(dataMessage);
39736
+ }
39737
+ const dataPath = pickFirstString(data, ["path", "filePath", "targetPath", "outputPath", "deliverable_path"]);
39738
+ if (dataPath) {
39739
+ return `\u8DEF\u5F84 ${preview(dataPath, 120)}`;
39740
+ }
39741
+ const stdout = stringValue2(data.stdout);
39742
+ if (stdout) {
39743
+ return `\u8F93\u51FA ${preview(stdout)}`;
39744
+ }
39745
+ const stderr = stringValue2(data.stderr);
39746
+ if (stderr) {
39747
+ return `\u9519\u8BEF\u8F93\u51FA ${preview(stderr)}`;
39748
+ }
39749
+ }
39750
+ if (parsed.ok === true || parsed.success === true) {
39751
+ return "\u5DE5\u5177\u8FD4\u56DE\u6210\u529F\u3002";
39752
+ }
39753
+ if (parsed.ok === false || parsed.success === false) {
39754
+ return "\u5DE5\u5177\u8FD4\u56DE\u5931\u8D25\u3002";
39755
+ }
39756
+ return "";
39757
+ }
39758
+ function extractToolResultDetail(raw) {
39759
+ const text = raw.trim();
39760
+ if (!text) {
39761
+ return "";
39762
+ }
39763
+ try {
39764
+ const parsed = JSON.parse(text);
39765
+ const detail = extractDetailFromParsedToolResult(parsed);
39766
+ if (detail) {
39767
+ return detail;
39768
+ }
39769
+ } catch {
39770
+ }
39771
+ return preview(text);
39772
+ }
39773
+ function synthesizeFinalTextFromToolResult(params) {
39774
+ const toolName = params.toolName?.trim() || "\u5DE5\u5177";
39775
+ const isError = params.result?.is_error === true;
39776
+ const resultText = params.result ? toolResultContentToString(params.result.content) : "";
39777
+ const detail = extractToolResultDetail(resultText);
39778
+ const status = isError ? "\u6267\u884C\u5931\u8D25" : "\u5DF2\u5B8C\u6210";
39779
+ const prefix = params.toolCalls > 1 ? `\u5DF2\u5B8C\u6210 ${params.toolCalls} \u6B21\u5DE5\u5177\u8C03\u7528\uFF0C\u6700\u540E\u4E00\u6B65 ${toolName} ${status}` : `\u5DE5\u5177 ${toolName} ${status}`;
39780
+ return detail ? `${prefix}\uFF1A${detail}` : `${prefix}\u3002`;
39781
+ }
39782
+
39783
+ // src/mobile/model-turn-runner.ts
39784
+ async function runModelTurnLoop(params) {
39785
+ const maxIterations = Math.max(0, Math.floor(params.maxIterations));
39786
+ let iterations = 0;
39787
+ let lastFollowUpReason;
39788
+ for (let iteration = 0; iteration < maxIterations; iteration += 1) {
39789
+ iterations = iteration + 1;
39790
+ const decision = await params.runIteration({ iteration });
39791
+ if (decision.kind === "follow_up") {
39792
+ lastFollowUpReason = decision.reason;
39793
+ continue;
39794
+ }
39795
+ return { kind: "final", iterations, value: decision.value };
39796
+ }
39797
+ return {
39798
+ kind: "exhausted",
39799
+ iterations,
39800
+ ...lastFollowUpReason ? { lastFollowUpReason } : {}
39801
+ };
39802
+ }
39803
+ function modelTurnNeedsFollowUp(toolUseCount) {
39804
+ return Number.isFinite(toolUseCount) && toolUseCount > 0;
39805
+ }
39806
+ function formatModelTurnLoopGuardDetails(params) {
39807
+ return [
39808
+ `maxIterations=${Math.max(0, Math.floor(params.maxIterations))} reached`,
39809
+ `iterations=${Math.max(0, Math.floor(params.iterations))}`,
39810
+ params.lastFollowUpReason ? `lastFollowUp=${params.lastFollowUpReason}` : "",
39811
+ params.lastToolName ? `lastToolName=${params.lastToolName}` : ""
39812
+ ].filter(Boolean).join(" ");
39813
+ }
39814
+
39580
39815
  // src/mobile/anthropic-messages-turn-runner.ts
39581
39816
  var DEFAULT_MAX_ITERATIONS = 48;
39582
39817
  var HARD_MAX_ITERATIONS = 128;
@@ -39599,11 +39834,9 @@ function resolveMaxIterations(explicit, env = process.env) {
39599
39834
  }
39600
39835
  return cap;
39601
39836
  }
39602
- function toolResultContentToString(content) {
39603
- if (typeof content === "string") {
39604
- return content;
39605
- }
39606
- return content.map((c) => c.text).join("");
39837
+ function isNativeToolTurnSpeculativeLiveDeliverEnabled(env = process.env) {
39838
+ const raw = (env.XKZOOM_NATIVE_TOOL_TURN_SPECULATIVE_LIVE_DELIVER ?? "").trim().toLowerCase();
39839
+ return raw === "1" || raw === "true" || raw === "yes";
39607
39840
  }
39608
39841
  function trackEarlyToolUseStart(params) {
39609
39842
  const effect = interpretAnthropicStreamEvent(params.event);
@@ -39758,278 +39991,304 @@ async function runAnthropicMessagesTurn(params) {
39758
39991
  let firstSseEventAtMs = null;
39759
39992
  let finalStreamIdleTimeout = false;
39760
39993
  let lastToolName = "";
39994
+ let lastToolResult = null;
39761
39995
  const maxIterations = resolveMaxIterations(params.maxIterations);
39996
+ const toolsAvailable = params.tools.length > 0;
39997
+ const allowSpeculativeToolTurnLiveDeliver = toolsAvailable && isNativeToolTurnSpeculativeLiveDeliverEnabled();
39762
39998
  let forcedIterationsUsed = 0;
39763
39999
  const basePolicy = params.toolChoicePolicy ?? { kind: "auto" };
39764
40000
  const baseForces = basePolicy.kind === "required" || basePolicy.kind === "tool";
39765
40001
  const canWireForce = params.wireForcedToolChoice !== false;
39766
40002
  const turnEarlyToolStartIds = /* @__PURE__ */ new Set();
39767
- for (let iteration = 0; iteration < maxIterations; iteration += 1) {
39768
- iterations = iteration + 1;
39769
- let iterAnswer = "";
39770
- let iterReasoning = "";
39771
- const iterPolicy = canWireForce && baseForces && iteration === 0 ? basePolicy : { kind: "auto" };
39772
- const thisIterForced = canWireForce && iterPolicy.kind !== "auto";
39773
- const allowLiveDeliver = !thisIterForced;
39774
- const pendingToolUseByIndex = /* @__PURE__ */ new Map();
39775
- let assembler = new AnthropicStreamAssembler();
39776
- let liveDeliver = new AnthropicIncrementalDeliverer(params.dispatcher, reasoningOn, params.log);
39777
- let streamIdleTimeout = false;
39778
- let toolUses = [];
39779
- let finalized = assembler.finalize();
39780
- for (let streamAttempt = 0; streamAttempt < 2; streamAttempt += 1) {
39781
- iterAnswer = "";
39782
- iterReasoning = "";
39783
- assembler = new AnthropicStreamAssembler();
39784
- liveDeliver = new AnthropicIncrementalDeliverer(params.dispatcher, reasoningOn, params.log);
39785
- streamIdleTimeout = false;
39786
- let streamSseEvents = 0;
39787
- const bufferedStreamEvents = [];
39788
- const argsDeltaExtractor = streamAttempt === 0 && params.onToolEvent ? new ToolArgsTextDeltaExtractor() : null;
39789
- const stream = params.streamFn(
39790
- {
39791
- systemPrompt: params.systemPrompt,
39792
- messages,
39793
- tools: params.tools,
39794
- reasoningMode: params.reasoningMode,
39795
- iteration,
39796
- toolChoicePolicy: iterPolicy
39797
- },
39798
- params.signal
39799
- );
39800
- for await (const event of stream) {
39801
- if (firstSseEventAtMs === null && !isAnthropicSseStreamMeta(event)) {
39802
- firstSseEventAtMs = Date.now();
39803
- params.log(
39804
- `[XKZOOM][native-reply][stream-diag] first-sse-event ms=${firstSseEventAtMs - turnStartedAtMs} iteration=${iteration}`
39805
- );
39806
- }
39807
- if (params.signal.aborted) {
39808
- params.log(
39809
- `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} aborted before stream complete`
39810
- );
39811
- throw new DOMException("Aborted", "AbortError");
39812
- }
39813
- if (isAnthropicSseStreamMeta(event)) {
39814
- streamIdleTimeout = event.idleTimeout;
39815
- continue;
39816
- }
39817
- if (argsDeltaExtractor) {
39818
- const argsEffect = interpretAnthropicStreamEvent(event);
39819
- if (argsEffect?.kind === "block-start" && argsEffect.block.type === "tool_use") {
39820
- const earlyId = (argsEffect.block.id ?? "").trim();
39821
- const earlyName = (argsEffect.block.name ?? "").trim();
39822
- argsDeltaExtractor.onToolUseBlockStart(argsEffect.index, earlyId, earlyName);
39823
- if (earlyId && earlyName && STREAMABLE_ARGS_FIELD_BY_TOOL[earlyName] && !turnEarlyToolStartIds.has(earlyId)) {
39824
- turnEarlyToolStartIds.add(earlyId);
39825
- params.onToolEvent?.({ phase: "start", toolCallId: earlyId, name: earlyName });
39826
- }
39827
- } else if (argsEffect?.kind === "input-json-delta") {
39828
- const delta = argsDeltaExtractor.onInputJsonDelta(argsEffect.index, argsEffect.partialJson);
39829
- if (delta) {
39830
- params.onToolEvent?.({
39831
- phase: "update",
39832
- toolCallId: delta.toolCallId,
39833
- argsDelta: { field: delta.field, textDelta: delta.textDelta }
39834
- });
39835
- }
39836
- } else if (argsEffect?.kind === "block-stop") {
39837
- argsDeltaExtractor.onBlockStop(argsEffect.index);
40003
+ const loopResult = await runModelTurnLoop({
40004
+ maxIterations,
40005
+ runIteration: async ({ iteration }) => {
40006
+ iterations = iteration + 1;
40007
+ let iterAnswer = "";
40008
+ let iterReasoning = "";
40009
+ const iterPolicy = canWireForce && baseForces && iteration === 0 ? basePolicy : { kind: "auto" };
40010
+ const thisIterForced = canWireForce && iterPolicy.kind !== "auto";
40011
+ const allowLiveDeliver = !thisIterForced && (!toolsAvailable || allowSpeculativeToolTurnLiveDeliver);
40012
+ const pendingToolUseByIndex = /* @__PURE__ */ new Map();
40013
+ let assembler = new AnthropicStreamAssembler();
40014
+ let liveDeliver = new AnthropicIncrementalDeliverer(params.dispatcher, reasoningOn, params.log);
40015
+ let streamIdleTimeout = false;
40016
+ let toolUses = [];
40017
+ let finalized = assembler.finalize();
40018
+ for (let streamAttempt = 0; streamAttempt < 2; streamAttempt += 1) {
40019
+ iterAnswer = "";
40020
+ iterReasoning = "";
40021
+ assembler = new AnthropicStreamAssembler();
40022
+ liveDeliver = new AnthropicIncrementalDeliverer(params.dispatcher, reasoningOn, params.log);
40023
+ streamIdleTimeout = false;
40024
+ let streamSseEvents = 0;
40025
+ const bufferedStreamEvents = [];
40026
+ const argsDeltaExtractor = streamAttempt === 0 && params.onToolEvent ? new ToolArgsTextDeltaExtractor() : null;
40027
+ const stream = params.streamFn(
40028
+ {
40029
+ systemPrompt: params.systemPrompt,
40030
+ messages,
40031
+ tools: params.tools,
40032
+ reasoningMode: params.reasoningMode,
40033
+ iteration,
40034
+ toolChoicePolicy: iterPolicy
40035
+ },
40036
+ params.signal
40037
+ );
40038
+ for await (const event of stream) {
40039
+ if (firstSseEventAtMs === null && !isAnthropicSseStreamMeta(event)) {
40040
+ firstSseEventAtMs = Date.now();
40041
+ params.log(
40042
+ `[XKZOOM][native-reply][stream-diag] first-sse-event ms=${firstSseEventAtMs - turnStartedAtMs} iteration=${iteration}`
40043
+ );
39838
40044
  }
39839
- }
39840
- const { error } = assembler.handle(event, (delta) => {
39841
- if (delta.thinkingDelta && reasoningOn) {
39842
- iterReasoning += delta.thinkingDelta;
40045
+ if (params.signal.aborted) {
40046
+ params.log(
40047
+ `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} aborted before stream complete`
40048
+ );
40049
+ throw new DOMException("Aborted", "AbortError");
40050
+ }
40051
+ if (isAnthropicSseStreamMeta(event)) {
40052
+ streamIdleTimeout = event.idleTimeout;
40053
+ continue;
39843
40054
  }
39844
- if (delta.textDelta) {
39845
- iterAnswer += delta.textDelta;
40055
+ if (argsDeltaExtractor) {
40056
+ const argsEffect = interpretAnthropicStreamEvent(event);
40057
+ if (argsEffect?.kind === "block-start" && argsEffect.block.type === "tool_use") {
40058
+ const earlyId = (argsEffect.block.id ?? "").trim();
40059
+ const earlyName = (argsEffect.block.name ?? "").trim();
40060
+ argsDeltaExtractor.onToolUseBlockStart(argsEffect.index, earlyId, earlyName);
40061
+ if (earlyId && earlyName && STREAMABLE_ARGS_FIELD_BY_TOOL[earlyName] && !turnEarlyToolStartIds.has(earlyId)) {
40062
+ turnEarlyToolStartIds.add(earlyId);
40063
+ params.onToolEvent?.({ phase: "start", toolCallId: earlyId, name: earlyName });
40064
+ }
40065
+ } else if (argsEffect?.kind === "input-json-delta") {
40066
+ const delta = argsDeltaExtractor.onInputJsonDelta(argsEffect.index, argsEffect.partialJson);
40067
+ if (delta) {
40068
+ params.onToolEvent?.({
40069
+ phase: "update",
40070
+ toolCallId: delta.toolCallId,
40071
+ argsDelta: { field: delta.field, textDelta: delta.textDelta }
40072
+ });
40073
+ }
40074
+ } else if (argsEffect?.kind === "block-stop") {
40075
+ argsDeltaExtractor.onBlockStop(argsEffect.index);
40076
+ }
39846
40077
  }
39847
- if (allowLiveDeliver) {
40078
+ const { error } = assembler.handle(event, (delta) => {
39848
40079
  if (delta.thinkingDelta && reasoningOn) {
39849
- liveDeliver.onThinkingDelta(delta.thinkingDelta);
40080
+ iterReasoning += delta.thinkingDelta;
39850
40081
  }
39851
- if (delta.textDelta && !assembler.hasToolUseBlock) {
39852
- liveDeliver.onTextDelta(delta.textDelta);
40082
+ if (delta.textDelta) {
40083
+ iterAnswer += delta.textDelta;
39853
40084
  }
40085
+ if (allowLiveDeliver) {
40086
+ if (delta.thinkingDelta && reasoningOn) {
40087
+ liveDeliver.onThinkingDelta(delta.thinkingDelta);
40088
+ }
40089
+ if (delta.textDelta && !assembler.hasToolUseBlock) {
40090
+ liveDeliver.onTextDelta(delta.textDelta);
40091
+ }
40092
+ }
40093
+ });
40094
+ if (error) {
40095
+ throw new Error(`native anthropic-turn stream error: ${error}`);
40096
+ }
40097
+ bufferedStreamEvents.push(event);
40098
+ streamSseEvents += 1;
40099
+ if (assembler.hasToolUseBlock && streamSseEvents % 25 === 0) {
40100
+ params.log(
40101
+ `[XKZOOM][native-reply][anthropic-turn] tool_use stream-progress iteration=${iteration} events=${streamSseEvents} answerLen=${iterAnswer.length}`
40102
+ );
39854
40103
  }
39855
- });
39856
- if (error) {
39857
- throw new Error(`native anthropic-turn stream error: ${error}`);
39858
40104
  }
39859
- bufferedStreamEvents.push(event);
39860
- streamSseEvents += 1;
39861
- if (assembler.hasToolUseBlock && streamSseEvents % 25 === 0) {
39862
- params.log(
39863
- `[XKZOOM][native-reply][anthropic-turn] tool_use stream-progress iteration=${iteration} events=${streamSseEvents} answerLen=${iterAnswer.length}`
39864
- );
40105
+ finalized = assembler.finalize();
40106
+ toolUses = resolveToolUsesFromAssembler(assembler);
40107
+ const hasIncomplete = toolUses.length > 0 && toolUses.some((tu) => !isExecutableToolUseInput(tu.name, tu.input));
40108
+ if (!hasIncomplete) {
40109
+ for (const bufferedEvent of bufferedStreamEvents) {
40110
+ trackEarlyToolUseStart({
40111
+ event: bufferedEvent,
40112
+ iteration,
40113
+ turnEmittedStartIds: turnEarlyToolStartIds,
40114
+ pendingByIndex: pendingToolUseByIndex,
40115
+ onToolEvent: params.onToolEvent,
40116
+ log: params.log
40117
+ });
40118
+ }
40119
+ break;
39865
40120
  }
39866
- }
39867
- finalized = assembler.finalize();
39868
- toolUses = resolveToolUsesFromAssembler(assembler);
39869
- const hasIncomplete = toolUses.length > 0 && toolUses.some((tu) => !isExecutableToolUseInput(tu.name, tu.input));
39870
- if (!hasIncomplete) {
39871
- for (const bufferedEvent of bufferedStreamEvents) {
39872
- trackEarlyToolUseStart({
39873
- event: bufferedEvent,
39874
- iteration,
39875
- turnEmittedStartIds: turnEarlyToolStartIds,
39876
- pendingByIndex: pendingToolUseByIndex,
39877
- onToolEvent: params.onToolEvent,
39878
- log: params.log
39879
- });
40121
+ if (streamAttempt === 1) {
40122
+ break;
39880
40123
  }
39881
- break;
40124
+ const incompleteSummary = toolUses.filter((tu) => !isExecutableToolUseInput(tu.name, tu.input)).map((tu) => `${tu.name}:${tu.id}`).join(",");
40125
+ params.log(
40126
+ `[XKZOOM][native-reply][anthropic-turn] tool_use batch has incomplete input; retrying provider stream once iteration=${iteration} incomplete=${incompleteSummary}`
40127
+ );
39882
40128
  }
39883
- if (streamAttempt === 1) {
39884
- break;
40129
+ stopReason = finalized.stopReason;
40130
+ if (streamIdleTimeout) {
40131
+ finalStreamIdleTimeout = true;
39885
40132
  }
39886
- const incompleteSummary = toolUses.filter((tu) => !isExecutableToolUseInput(tu.name, tu.input)).map((tu) => `${tu.name}:${tu.id}`).join(",");
39887
- params.log(
39888
- `[XKZOOM][native-reply][anthropic-turn] tool_use batch has incomplete input; retrying provider stream once iteration=${iteration} incomplete=${incompleteSummary}`
39889
- );
39890
- }
39891
- stopReason = finalized.stopReason;
39892
- if (streamIdleTimeout) {
39893
- finalStreamIdleTimeout = true;
39894
- }
39895
- const blockStats = assembler.getBlockStats();
39896
- const usage = assembler.getUsageSnapshot();
39897
- params.log(
39898
- `[XKZOOM][native-reply][anthropic-turn] block_stats iteration=${iteration} ${formatBlockStats(blockStats)} usage=${formatUsageSnapshot(usage)}`
39899
- );
39900
- if (!stopReason && toolUses.length > 0) {
39901
- stopReason = "tool_use";
39902
- params.log(
39903
- `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stop_reason_synthesized=tool_use toolCalls=${toolUses.length} idleTimeout=${streamIdleTimeout ? 1 : 0}`
39904
- );
39905
- } else if (!stopReason && iterAnswer.trim().length > 0) {
39906
- stopReason = "end_turn";
39907
- params.log(
39908
- `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stop_reason_synthesized=end_turn answerLen=${iterAnswer.length} idleTimeout=${streamIdleTimeout ? 1 : 0}`
39909
- );
39910
- } else if (streamIdleTimeout && iterAnswer.trim().length > 0 && assembler.hasToolUseBlock && toolUses.length === 0) {
39911
- stopReason = "end_turn";
40133
+ const blockStats = assembler.getBlockStats();
40134
+ const usage = assembler.getUsageSnapshot();
39912
40135
  params.log(
39913
- `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} incomplete_tool_use_dropped answerLen=${iterAnswer.length} idleTimeout=1`
40136
+ `[XKZOOM][native-reply][anthropic-turn] block_stats iteration=${iteration} ${formatBlockStats(blockStats)} usage=${formatUsageSnapshot(usage)}`
39914
40137
  );
39915
- } else if (streamIdleTimeout) {
39916
- params.log(
39917
- `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stream_idle_timeout answerLen=${iterAnswer.length} toolUseBlocks=${assembler.hasToolUseBlock ? 1 : 0}`
39918
- );
39919
- }
39920
- if (stopReason === "tool_use" && toolUses.length === 0) {
39921
- params.log(
39922
- `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stop=tool_use tool_use blocks missing id (provider SSE); retrying`
39923
- );
39924
- continue;
39925
- }
39926
- if (stopReason === "tool_use" && toolUses.length > 0) {
39927
- const maxToolUsesPerAssistant = params.maxToolUsesPerAssistant && params.maxToolUsesPerAssistant > 0 ? Math.floor(params.maxToolUsesPerAssistant) : Number.POSITIVE_INFINITY;
39928
- const limited = limitToolUsesForAssistantMessage({
39929
- toolUses,
39930
- blocks: finalized.blocks,
39931
- maxToolUses: maxToolUsesPerAssistant
39932
- });
39933
- lastToolName = limited.toolUses[limited.toolUses.length - 1]?.name ?? lastToolName;
39934
- if (limited.dropped.length > 0) {
40138
+ if (!stopReason && toolUses.length > 0) {
40139
+ stopReason = "tool_use";
39935
40140
  params.log(
39936
- `[XKZOOM][native-reply][anthropic-turn] tool_use serial-limit iteration=${iteration} kept=${limited.toolUses.map((tu) => `${tu.name}:${tu.id}`).join(",")} dropped=${limited.dropped.map((tu) => `${tu.name}:${tu.id}`).join(",")}`
40141
+ `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stop_reason_synthesized=tool_use toolCalls=${toolUses.length} idleTimeout=${streamIdleTimeout ? 1 : 0}`
40142
+ );
40143
+ } else if (!stopReason && iterAnswer.trim().length > 0) {
40144
+ stopReason = "end_turn";
40145
+ params.log(
40146
+ `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stop_reason_synthesized=end_turn answerLen=${iterAnswer.length} idleTimeout=${streamIdleTimeout ? 1 : 0}`
40147
+ );
40148
+ } else if (streamIdleTimeout && iterAnswer.trim().length > 0 && assembler.hasToolUseBlock && toolUses.length === 0) {
40149
+ stopReason = "end_turn";
40150
+ params.log(
40151
+ `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} incomplete_tool_use_dropped answerLen=${iterAnswer.length} idleTimeout=1`
40152
+ );
40153
+ } else if (streamIdleTimeout) {
40154
+ params.log(
40155
+ `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stream_idle_timeout answerLen=${iterAnswer.length} toolUseBlocks=${assembler.hasToolUseBlock ? 1 : 0}`
39937
40156
  );
39938
40157
  }
39939
- const assistantBlocks = mergeResolvedToolInputsIntoAssistantBlocks(limited.blocks, limited.toolUses);
39940
- const blockPartsById = indexToolUseBlockParts(assembler.collectToolUseBlockParts());
39941
- const notExecutable = limited.toolUses.filter((tu) => !isExecutableToolUseInput(tu.name, tu.input));
39942
- if (notExecutable.length > 0) {
39943
- for (const toolUse of notExecutable) {
39944
- const readiness = diagnoseToolUseInputReadiness(toolUse.name, toolUse.input);
39945
- const streamParts = blockPartsById.get(toolUse.id) ?? {
39946
- id: toolUse.id,
39947
- name: toolUse.name,
39948
- partialJson: ""
39949
- };
39950
- params.log(formatToolInputDiagLine({ iteration, parts: streamParts, readiness }));
39951
- }
40158
+ const needsFollowUp = modelTurnNeedsFollowUp(toolUses.length);
40159
+ if (stopReason === "tool_use" && !needsFollowUp) {
39952
40160
  params.log(
39953
- `[XKZOOM][native-reply][anthropic-turn] tool_use incomplete input after retry; delegating error envelope iteration=${iteration} tools=${notExecutable.map((tu) => `${tu.name}:${tu.id}`).join(",")}`
40161
+ `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stop=tool_use tool_use blocks missing id (provider SSE); retrying`
39954
40162
  );
40163
+ return { kind: "follow_up", reason: "tool_use_missing_id" };
39955
40164
  }
39956
- const thinkingByToolId = toolThinkingById(assistantBlocks, limited.toolUses);
39957
- messages = [...messages, assistantTurnTranscriptMessage(assistantBlocks)];
39958
- const results = await Promise.all(
39959
- limited.toolUses.map(async (toolUse) => {
39960
- const args = visibleToolUseArgs(toolUse.input);
39961
- const readiness = diagnoseToolUseInputReadiness(toolUse.name, toolUse.input);
39962
- const streamParts = blockPartsById.get(toolUse.id) ?? {
39963
- id: toolUse.id,
39964
- name: toolUse.name,
39965
- partialJson: ""
39966
- };
39967
- params.log(formatToolInputDiagLine({ iteration, parts: streamParts, readiness }));
39968
- if (!turnEarlyToolStartIds.has(toolUse.id)) {
39969
- emitToolUseStartEvent({
39970
- toolUse,
39971
- thinking: thinkingByToolId.get(toolUse.id),
39972
- onToolEvent: params.onToolEvent
39973
- });
39974
- turnEarlyToolStartIds.add(toolUse.id);
39975
- } else if (Object.keys(args).length > 0 || thinkingByToolId.has(toolUse.id)) {
39976
- emitToolUseStartEvent({
39977
- toolUse,
39978
- thinking: thinkingByToolId.get(toolUse.id),
39979
- onToolEvent: params.onToolEvent
39980
- });
39981
- params.log(
39982
- `[XKZOOM][native-reply][anthropic-turn] tool_use execute iteration=${iteration} id=${toolUse.id} name=${toolUse.name} argsKeys=${Object.keys(args).join(",")}`
39983
- );
40165
+ if (needsFollowUp) {
40166
+ if (stopReason !== "tool_use") {
40167
+ params.log(
40168
+ `[XKZOOM][native-reply][anthropic-turn] needs_follow_up_by_tool_use iteration=${iteration} stop=${stopReason ?? "none"} toolCalls=${toolUses.length}`
40169
+ );
40170
+ }
40171
+ const maxToolUsesPerAssistant = params.maxToolUsesPerAssistant && params.maxToolUsesPerAssistant > 0 ? Math.floor(params.maxToolUsesPerAssistant) : Number.POSITIVE_INFINITY;
40172
+ const limited = limitToolUsesForAssistantMessage({
40173
+ toolUses,
40174
+ blocks: finalized.blocks,
40175
+ maxToolUses: maxToolUsesPerAssistant
40176
+ });
40177
+ lastToolName = limited.toolUses[limited.toolUses.length - 1]?.name ?? lastToolName;
40178
+ if (limited.dropped.length > 0) {
40179
+ params.log(
40180
+ `[XKZOOM][native-reply][anthropic-turn] tool_use serial-limit iteration=${iteration} kept=${limited.toolUses.map((tu) => `${tu.name}:${tu.id}`).join(",")} dropped=${limited.dropped.map((tu) => `${tu.name}:${tu.id}`).join(",")}`
40181
+ );
40182
+ }
40183
+ const assistantBlocks = mergeResolvedToolInputsIntoAssistantBlocks(limited.blocks, limited.toolUses);
40184
+ const blockPartsById = indexToolUseBlockParts(assembler.collectToolUseBlockParts());
40185
+ const notExecutable = limited.toolUses.filter((tu) => !isExecutableToolUseInput(tu.name, tu.input));
40186
+ if (notExecutable.length > 0) {
40187
+ for (const toolUse of notExecutable) {
40188
+ const readiness = diagnoseToolUseInputReadiness(toolUse.name, toolUse.input);
40189
+ const streamParts = blockPartsById.get(toolUse.id) ?? {
40190
+ id: toolUse.id,
40191
+ name: toolUse.name,
40192
+ partialJson: ""
40193
+ };
40194
+ params.log(formatToolInputDiagLine({ iteration, parts: streamParts, readiness }));
39984
40195
  }
39985
- const result = await params.executeToolUse(toolUse);
39986
- params.onToolEvent?.({
39987
- phase: "result",
39988
- toolCallId: toolUse.id,
39989
- result: toolResultContentToString(result.content),
39990
- isError: result.is_error === true
39991
- });
39992
- return result;
39993
- })
39994
- );
39995
- messages = [...messages, toolResultsTranscriptMessage(results)];
39996
- toolCalls += limited.toolUses.length;
39997
- params.log(
39998
- `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stop=tool_use toolCalls=${limited.toolUses.length} cumulativeToolCalls=${toolCalls}` + (limited.toolUses.length > 1 ? ` parallel=1` : "")
39999
- );
40000
- continue;
40001
- }
40002
- finalAnswer = iterAnswer;
40003
- finalReasoning = iterReasoning;
40004
- if (reasoningOn && !iterReasoning.trim()) {
40005
- const thinkingFromBlocks = finalized.blocks.filter((b) => b.type === "thinking").map((b) => b.thinking).join("");
40006
- if (thinkingFromBlocks.trim()) {
40007
- iterReasoning = thinkingFromBlocks;
40008
- finalReasoning = thinkingFromBlocks;
40196
+ params.log(
40197
+ `[XKZOOM][native-reply][anthropic-turn] tool_use incomplete input after retry; delegating error envelope iteration=${iteration} tools=${notExecutable.map((tu) => `${tu.name}:${tu.id}`).join(",")}`
40198
+ );
40199
+ }
40200
+ const thinkingByToolId = toolThinkingById(assistantBlocks, limited.toolUses);
40201
+ messages = [...messages, assistantTurnTranscriptMessage(assistantBlocks)];
40202
+ const results = await Promise.all(
40203
+ limited.toolUses.map(async (toolUse) => {
40204
+ const args = visibleToolUseArgs(toolUse.input);
40205
+ const readiness = diagnoseToolUseInputReadiness(toolUse.name, toolUse.input);
40206
+ const streamParts = blockPartsById.get(toolUse.id) ?? {
40207
+ id: toolUse.id,
40208
+ name: toolUse.name,
40209
+ partialJson: ""
40210
+ };
40211
+ params.log(formatToolInputDiagLine({ iteration, parts: streamParts, readiness }));
40212
+ if (!turnEarlyToolStartIds.has(toolUse.id)) {
40213
+ emitToolUseStartEvent({
40214
+ toolUse,
40215
+ thinking: thinkingByToolId.get(toolUse.id),
40216
+ onToolEvent: params.onToolEvent
40217
+ });
40218
+ turnEarlyToolStartIds.add(toolUse.id);
40219
+ } else if (Object.keys(args).length > 0 || thinkingByToolId.has(toolUse.id)) {
40220
+ emitToolUseStartEvent({
40221
+ toolUse,
40222
+ thinking: thinkingByToolId.get(toolUse.id),
40223
+ onToolEvent: params.onToolEvent
40224
+ });
40225
+ params.log(
40226
+ `[XKZOOM][native-reply][anthropic-turn] tool_use execute iteration=${iteration} id=${toolUse.id} name=${toolUse.name} argsKeys=${Object.keys(args).join(",")}`
40227
+ );
40228
+ }
40229
+ const result = await params.executeToolUse(toolUse);
40230
+ params.onToolEvent?.({
40231
+ phase: "result",
40232
+ toolCallId: toolUse.id,
40233
+ result: toolResultContentToString(result.content),
40234
+ isError: result.is_error === true
40235
+ });
40236
+ return result;
40237
+ })
40238
+ );
40239
+ lastToolResult = results[results.length - 1] ?? lastToolResult;
40240
+ messages = [...messages, toolResultsTranscriptMessage(results)];
40241
+ toolCalls += limited.toolUses.length;
40242
+ params.log(
40243
+ `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stop=tool_use toolCalls=${limited.toolUses.length} cumulativeToolCalls=${toolCalls}` + (limited.toolUses.length > 1 ? ` parallel=1` : "")
40244
+ );
40245
+ return { kind: "follow_up", reason: "tool_use" };
40246
+ }
40247
+ finalAnswer = iterAnswer;
40248
+ finalReasoning = iterReasoning;
40249
+ if (reasoningOn && !iterReasoning.trim()) {
40250
+ const thinkingFromBlocks = finalized.blocks.filter((b) => b.type === "thinking").map((b) => b.thinking).join("");
40251
+ if (thinkingFromBlocks.trim()) {
40252
+ iterReasoning = thinkingFromBlocks;
40253
+ finalReasoning = thinkingFromBlocks;
40254
+ }
40009
40255
  }
40010
- }
40011
- if (reasoningOn && blockStats.thinkingBlocks === 0) {
40256
+ if (reasoningOn && blockStats.thinkingBlocks === 0) {
40257
+ params.log(
40258
+ `[XKZOOM][native-reply][anthropic-turn] reasoning_requested_but_no_thinking_block iteration=${iteration} stop=${stopReason ?? "none"} answerLen=${iterAnswer.length}`
40259
+ );
40260
+ }
40261
+ const finalThinkingBlock = finalized.blocks.find((b) => b.type === "thinking");
40262
+ finalReasoningSignature = finalThinkingBlock?.type === "thinking" ? finalThinkingBlock.signature ?? "" : "";
40263
+ if (!assembler.hasToolUseBlock || stopReason === "end_turn") {
40264
+ liveDeliver.flush();
40265
+ if (reasoningOn && iterReasoning.trim()) {
40266
+ liveDeliver.ensureReasoningTextDelivered(iterReasoning);
40267
+ }
40268
+ }
40269
+ finalLiveDeliver = liveDeliver;
40012
40270
  params.log(
40013
- `[XKZOOM][native-reply][anthropic-turn] reasoning_requested_but_no_thinking_block iteration=${iteration} stop=${stopReason ?? "none"} answerLen=${iterAnswer.length}`
40271
+ `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stop=${stopReason ?? "none"} answerLen=${finalAnswer.length} reasoningLen=${finalReasoning.length} liveDelivered=${liveDeliver.hasDelivered ? 1 : 0} done`
40014
40272
  );
40273
+ return { kind: "final", value: void 0 };
40015
40274
  }
40016
- const finalThinkingBlock = finalized.blocks.find((b) => b.type === "thinking");
40017
- finalReasoningSignature = finalThinkingBlock?.type === "thinking" ? finalThinkingBlock.signature ?? "" : "";
40018
- if (!assembler.hasToolUseBlock || stopReason === "end_turn") {
40019
- liveDeliver.flush();
40020
- if (reasoningOn && iterReasoning.trim()) {
40021
- liveDeliver.ensureReasoningTextDelivered(iterReasoning);
40022
- }
40023
- }
40024
- finalLiveDeliver = liveDeliver;
40275
+ });
40276
+ iterations = loopResult.iterations;
40277
+ let answerToDeliver = finalAnswer;
40278
+ const initialVisibleLen = answerToDeliver.trim().length + (reasoningOn ? finalReasoning.trim().length : 0);
40279
+ if (initialVisibleLen === 0 && toolCalls > 0) {
40280
+ answerToDeliver = synthesizeFinalTextFromToolResult({
40281
+ toolName: lastToolName,
40282
+ toolCalls,
40283
+ result: lastToolResult
40284
+ });
40285
+ finalAnswer = answerToDeliver;
40025
40286
  params.log(
40026
- `[XKZOOM][native-reply][anthropic-turn] iteration=${iteration} stop=${stopReason ?? "none"} answerLen=${finalAnswer.length} reasoningLen=${finalReasoning.length} liveDelivered=${liveDeliver.hasDelivered ? 1 : 0} done`
40287
+ `[XKZOOM][native-reply][anthropic-turn] synthesized final from last tool_result toolCalls=${toolCalls} lastToolName=${lastToolName || "unknown"} answerLen=${answerToDeliver.length}`
40027
40288
  );
40028
- break;
40029
40289
  }
40030
- const answerToDeliver = finalAnswer;
40031
- if (iterations >= maxIterations && stopReason === "tool_use") {
40032
- const details = formatStreamEmptyDetails({
40290
+ if (loopResult.kind === "exhausted" && loopResult.lastFollowUpReason) {
40291
+ const streamDetails = formatStreamEmptyDetails({
40033
40292
  iterations,
40034
40293
  stopReason,
40035
40294
  toolCalls,
@@ -40039,9 +40298,15 @@ async function runAnthropicMessagesTurn(params) {
40039
40298
  idleTimeout: finalStreamIdleTimeout,
40040
40299
  lastToolName
40041
40300
  });
40301
+ const details = `${formatModelTurnLoopGuardDetails({
40302
+ maxIterations,
40303
+ iterations,
40304
+ lastFollowUpReason: loopResult.lastFollowUpReason,
40305
+ lastToolName
40306
+ })} (${streamDetails})`;
40042
40307
  params.log(`[XKZOOM][native-reply][anthropic-turn] loop_guard ${details}`);
40043
40308
  throw new Error(
40044
- `native anthropic-turn loop_guard: maxIterations=${maxIterations} reached before final answer (${details})`
40309
+ `native anthropic-turn loop_guard: ${details}`
40045
40310
  );
40046
40311
  }
40047
40312
  const visibleLen = answerToDeliver.trim().length + (reasoningOn ? finalReasoning.trim().length : 0);
@@ -40077,6 +40342,14 @@ async function runAnthropicMessagesTurn(params) {
40077
40342
  `[XKZOOM][native-reply][anthropic-turn] forced-tool-no-call fallback_to_final_text=1 ${details}`
40078
40343
  );
40079
40344
  }
40345
+ const liveDeliverySuppressedForToolTurn = toolsAvailable && !allowSpeculativeToolTurnLiveDeliver;
40346
+ if (liveDeliverySuppressedForToolTurn && finalLiveDeliver && answerToDeliver.trim().length > 0 && finalLiveDeliver.answerLen === 0 && !finalLiveDeliver.isAnswerFullyDelivered(answerToDeliver)) {
40347
+ finalLiveDeliver.onTextDelta(answerToDeliver);
40348
+ finalLiveDeliver.flush();
40349
+ params.log(
40350
+ `[XKZOOM][native-reply][anthropic-turn] tool-turn final replay via pure_delta answerLen=${answerToDeliver.length}`
40351
+ );
40352
+ }
40080
40353
  if (finalLiveDeliver?.isAnswerFullyDelivered(answerToDeliver)) {
40081
40354
  params.log(
40082
40355
  `[XKZOOM][native-reply][anthropic-turn] skip duplicate sendFinalReply answerLen=${answerToDeliver.length}`