@qwen-code/qwen-code 0.20.1-preview.7215 → 0.20.2-gdpval-vl-agent.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (327) hide show
  1. package/bundled/qc-helper/docs/configuration/settings.md +1 -1
  2. package/bundled/qc-helper/docs/features/auto-mode.md +19 -16
  3. package/bundled/qc-helper/docs/features/commands.md +54 -0
  4. package/bundled/qc-helper/docs/features/sub-agents.md +16 -7
  5. package/bundled/qc-helper/docs/integration-github-action.md +1 -1
  6. package/bundled/qc-helper/docs/qwen-serve.md +2 -1
  7. package/bundled/review/DESIGN.md +2 -2
  8. package/bundled/review/SKILL.md +4 -4
  9. package/chunks/{MaxSizedBox-EH6G5AEH.js → MaxSizedBox-KYNG7EN7.js} +38 -35
  10. package/chunks/{StandaloneSessionPicker-264A3TEA.js → StandaloneSessionPicker-7XN4WVVG.js} +55 -52
  11. package/chunks/{acpAgent-6RBIJFDI.js → acpAgent-FTFFYP5G.js} +1536 -512
  12. package/chunks/{agent-QURXGAA3.js → agent-Y76LTTOT.js} +34 -31
  13. package/chunks/{agent-headless-CRGX4ICQ.js → agent-headless-IVAEQPK6.js} +34 -31
  14. package/chunks/{anthropicContentGenerator-BWBAZGTW.js → anthropicContentGenerator-HGWAHO24.js} +11 -13
  15. package/chunks/{artifact-tool-IUJ7QWCX.js → artifact-tool-56T5IMBP.js} +3 -3
  16. package/chunks/{askUserQuestion-IUMUUTDQ.js → askUserQuestion-E25OBIC2.js} +3 -3
  17. package/chunks/{bridge-MNFVKPMI.js → bridge-4M77KUEV.js} +39 -36
  18. package/chunks/{build-SSCNEHZZ.js → build-GHIZ4MSZ.js} +1 -1
  19. package/chunks/{ca-2SL2BXTK.js → ca-N6VVUFVB.js} +611 -201
  20. package/chunks/{channel-worker-group-53CMOPFT.js → channel-worker-group-QZV2SP5U.js} +4 -4
  21. package/chunks/{channel-worker-manager-UTXILKC2.js → channel-worker-manager-3GMAU45H.js} +4 -4
  22. package/chunks/{channel-worker-supervisor-ZGO2W2MD.js → channel-worker-supervisor-QCXSXCRY.js} +3 -3
  23. package/chunks/{chunk-UQES76OO.js → chunk-2HGTVAOW.js} +6 -6
  24. package/chunks/{chunk-2HOVDT7W.js → chunk-2LI23QA6.js} +1 -1
  25. package/chunks/{chunk-ANHT55MR.js → chunk-2P6CNEHB.js} +1 -1
  26. package/chunks/chunk-2RFKHEXL.js +74 -0
  27. package/chunks/{chunk-BF32GYSY.js → chunk-3IABAQR6.js} +1 -1
  28. package/chunks/chunk-3Z43GZUQ.js +32 -0
  29. package/chunks/chunk-43T5WDQ7.js +127 -0
  30. package/chunks/{chunk-DA7OOKVN.js → chunk-4CTP6VR6.js} +29 -2
  31. package/chunks/{chunk-JD3MKVKL.js → chunk-4K56OJFJ.js} +1 -1
  32. package/chunks/{chunk-KTUQMDEP.js → chunk-4K7VDKAD.js} +1 -1
  33. package/chunks/{chunk-QKYTTBYW.js → chunk-4LVZNIDO.js} +1 -1
  34. package/chunks/{chunk-ZEOZL37W.js → chunk-57FIIFJN.js} +1 -1
  35. package/chunks/{chunk-7YBZGNEC.js → chunk-5G3ZVADU.js} +308 -199
  36. package/chunks/{chunk-X4CGDBKA.js → chunk-6GEJX3LE.js} +3 -3
  37. package/chunks/{chunk-6GUTHAN7.js → chunk-6HOCJNO5.js} +1 -1
  38. package/chunks/{chunk-GMGDLUC7.js → chunk-6IL7KRLE.js} +1 -1
  39. package/chunks/chunk-6PVPNMXU.js +29 -0
  40. package/chunks/{chunk-BDBMYST4.js → chunk-6X4GWOPW.js} +1 -1
  41. package/chunks/{chunk-4ODB7WIB.js → chunk-6ZBPS62S.js} +1 -1
  42. package/chunks/{chunk-AYCDXHZB.js → chunk-7Z6JQEL6.js} +1 -1
  43. package/chunks/{chunk-WAX3ITOA.js → chunk-A3TAEAHX.js} +1 -1
  44. package/chunks/{chunk-OLMETXLX.js → chunk-ACW3VNUE.js} +2 -2
  45. package/chunks/{chunk-IB35C3IL.js → chunk-AVQ6EX4J.js} +1 -1
  46. package/chunks/{chunk-TTSKHF43.js → chunk-BK6UOUJ2.js} +2 -2
  47. package/chunks/{chunk-6OH6A5EX.js → chunk-BLAEKN6K.js} +20603 -17709
  48. package/chunks/chunk-BULDBTYC.js +153 -0
  49. package/chunks/{chunk-XNP57UDV.js → chunk-C3EXYVFX.js} +2 -2
  50. package/chunks/{chunk-FVS747N7.js → chunk-C54UTDOC.js} +23 -19
  51. package/chunks/{chunk-MAQQGNQ5.js → chunk-CBOQ3HY7.js} +466 -10
  52. package/chunks/{chunk-VFAE4AGH.js → chunk-CGZ5SV23.js} +72 -67
  53. package/chunks/{chunk-WKRXIHD6.js → chunk-COAARUPK.js} +8 -8
  54. package/chunks/{chunk-GA7VRJVN.js → chunk-E2ZK5M4P.js} +5 -5
  55. package/chunks/{chunk-5SCI6E3E.js → chunk-E4IMU4Y5.js} +1 -1
  56. package/chunks/{chunk-E5GIFWE3.js → chunk-EEFRJ5CT.js} +54 -33
  57. package/chunks/{chunk-WXAXH7IJ.js → chunk-ESQHGKPJ.js} +1 -1
  58. package/chunks/{chunk-NEEB7UEN.js → chunk-FFFM6NJV.js} +1 -2
  59. package/chunks/{chunk-Z5R4JMOL.js → chunk-FJ2IUWNQ.js} +4 -4
  60. package/chunks/{chunk-JVTCARQ6.js → chunk-FQI7LT7T.js} +4 -4
  61. package/chunks/{chunk-BRXIO5WY.js → chunk-FTNI3D7D.js} +7 -7
  62. package/chunks/{chunk-OMH3276Y.js → chunk-GHRSKGHF.js} +7 -7
  63. package/chunks/{chunk-OONJNQ42.js → chunk-GPSKDNEE.js} +3 -3
  64. package/chunks/{chunk-KPZNOZPC.js → chunk-GWM4PDYK.js} +19 -19
  65. package/chunks/{chunk-NBMIC7DR.js → chunk-H24SOJIQ.js} +2 -2
  66. package/chunks/{chunk-FNGK2Z5B.js → chunk-H4AR2JQF.js} +3 -3
  67. package/chunks/{chunk-WOT64EP2.js → chunk-HCJQORKC.js} +2 -2
  68. package/chunks/{chunk-7KDI2IB2.js → chunk-HDATOR4J.js} +4 -4
  69. package/chunks/{chunk-IE4JSQ5L.js → chunk-HIYP7IR4.js} +39 -37
  70. package/chunks/{chunk-N6YTEVLV.js → chunk-HL6AKUGD.js} +10 -4
  71. package/chunks/{chunk-BAIEQKR5.js → chunk-HPQFGWOD.js} +5 -5
  72. package/chunks/chunk-HTR4WV6U.js +327 -0
  73. package/chunks/{chunk-SDXIH6OA.js → chunk-IFUNDCQ6.js} +137 -5
  74. package/chunks/{chunk-Z6UEAQTP.js → chunk-IFVECEIK.js} +178 -61
  75. package/chunks/{chunk-QOK6RMIP.js → chunk-IKP54WUL.js} +4 -4
  76. package/chunks/{chunk-IUSNI6IX.js → chunk-ISMD2AB3.js} +1 -1
  77. package/chunks/{chunk-G45X5TRN.js → chunk-JCW2R7WC.js} +1 -72
  78. package/chunks/{chunk-LZYWWWCZ.js → chunk-KF6CTNTJ.js} +8 -9
  79. package/chunks/{chunk-EIAK6Q2B.js → chunk-KHOVYUHX.js} +2 -2
  80. package/chunks/chunk-KWK7UE6L.js +6194 -0
  81. package/chunks/{chunk-WBTZGWQ6.js → chunk-L5F3T6TQ.js} +1 -1
  82. package/chunks/{chunk-RELYEO3R.js → chunk-L7ASZD66.js} +244 -1607
  83. package/chunks/{chunk-UJEZQ562.js → chunk-LESHKUWF.js} +3 -5
  84. package/chunks/{chunk-OOCI5VVU.js → chunk-LIZRAKPB.js} +1 -1
  85. package/chunks/{chunk-Q3ZBFXK4.js → chunk-LKB5YL5T.js} +143 -36
  86. package/chunks/{chunk-MKLKHZAK.js → chunk-LU3RXCM7.js} +1 -1
  87. package/chunks/{chunk-B453NMZJ.js → chunk-M3EQ3GZC.js} +3 -3
  88. package/chunks/{chunk-TCKTNY66.js → chunk-M4VFMLQK.js} +6 -6
  89. package/chunks/{chunk-26LLB6FM.js → chunk-MDZTPSXO.js} +2 -2
  90. package/chunks/{chunk-4SLLEAQP.js → chunk-MJPBB2GK.js} +591 -316
  91. package/chunks/chunk-NABLFI57.js +82 -0
  92. package/chunks/{chunk-T7DDD7CZ.js → chunk-NAXEEGJU.js} +4 -4
  93. package/chunks/{chunk-467G3SV5.js → chunk-NPQDJGKU.js} +1 -1
  94. package/chunks/{chunk-FLTN6NRU.js → chunk-O4OT3DM3.js} +5 -1
  95. package/chunks/{chunk-3EUZWNWA.js → chunk-OPDZT2VG.js} +1 -1
  96. package/chunks/chunk-OQ5SYCPE.js +10017 -0
  97. package/chunks/{chunk-C27BYUX6.js → chunk-OQB4EXO4.js} +14 -11
  98. package/chunks/{chunk-V25Z5UUB.js → chunk-P6PBZL3N.js} +7 -6
  99. package/chunks/{chunk-5NWV4NFB.js → chunk-PRAUGUNM.js} +3 -3
  100. package/chunks/{chunk-MC2DOZS7.js → chunk-PVT6E3ZI.js} +3 -3
  101. package/chunks/{chunk-KXEGCGUG.js → chunk-Q22WWVR6.js} +31 -6
  102. package/chunks/{chunk-JDI67JFB.js → chunk-Q2YKNMLS.js} +3 -3
  103. package/chunks/{chunk-PBATSWUQ.js → chunk-QBUDF33N.js} +1 -1
  104. package/chunks/{chunk-Y2ENGUD6.js → chunk-QKTHJXCS.js} +1 -1
  105. package/chunks/{chunk-BVLROR2T.js → chunk-QLJUC7TG.js} +1 -1
  106. package/chunks/{chunk-UEY4AYUL.js → chunk-QNLNLENL.js} +2 -2
  107. package/chunks/{chunk-OKWRU4NO.js → chunk-RC7A7SSL.js} +3 -3
  108. package/chunks/chunk-RCUEYZDE.js +2290 -0
  109. package/chunks/{chunk-EVSTCA7S.js → chunk-RMY5SX7S.js} +368 -113
  110. package/chunks/{chunk-4WUAQ2DO.js → chunk-RTQSXHS7.js} +2 -2
  111. package/chunks/{chunk-RFIAR4YL.js → chunk-RV4C2ZFG.js} +1 -1
  112. package/chunks/{chunk-NIJEXGV6.js → chunk-RVLZCXEE.js} +79 -10
  113. package/chunks/{chunk-Q4RBU7WX.js → chunk-S333CBIA.js} +6 -6
  114. package/chunks/{chunk-JNWZQ27S.js → chunk-SP5WRGVG.js} +3 -3
  115. package/chunks/{chunk-FSL5W5TI.js → chunk-T2L47JJK.js} +3 -3
  116. package/chunks/{chunk-PWVTCGBP.js → chunk-TA4S377U.js} +30 -20
  117. package/chunks/{chunk-TB6UDU4T.js → chunk-THJNPLI4.js} +16 -16
  118. package/chunks/chunk-U6TQGUNB.js +20687 -0
  119. package/chunks/chunk-U7ZFW55U.js +2098 -0
  120. package/chunks/{chunk-W7H223ZZ.js → chunk-UGYMA4EI.js} +1 -1
  121. package/chunks/{chunk-X6YQWCIJ.js → chunk-UH3WSE5L.js} +13 -1
  122. package/chunks/{chunk-P2YAOGJD.js → chunk-UKU3NGW6.js} +3 -3
  123. package/chunks/{chunk-NOWTNYC7.js → chunk-UVFCANV5.js} +8 -8
  124. package/chunks/{chunk-CVDW42JT.js → chunk-V4AKJQ26.js} +1 -1
  125. package/chunks/{chunk-Z5Q65RVH.js → chunk-VJPRLNLR.js} +1 -1
  126. package/chunks/{chunk-Y4CRUWFZ.js → chunk-VTXX72XS.js} +60 -35
  127. package/chunks/{chunk-R3VWUU2E.js → chunk-VYPFXUCB.js} +1 -1
  128. package/chunks/chunk-WHGVTP7Q.js +1049 -0
  129. package/chunks/{chunk-IKP5DXZY.js → chunk-WOWQQGGN.js} +5 -5
  130. package/chunks/{chunk-D2VIDMVM.js → chunk-X6N25LXS.js} +2 -2
  131. package/chunks/chunk-XHATNRQA.js +1500 -0
  132. package/chunks/{chunk-2DXOIVUI.js → chunk-YLSB23Y2.js} +11 -11
  133. package/chunks/{chunk-S35ZDXOS.js → chunk-YM3SZTH4.js} +2 -1
  134. package/chunks/{chunk-OF2BBLYQ.js → chunk-YNWJAOPL.js} +2 -2
  135. package/chunks/{chunk-GKY2OJ7R.js → chunk-ZHERRXZJ.js} +1 -1
  136. package/chunks/{chunk-AR27OPIU.js → chunk-ZKFJKN23.js} +2 -2
  137. package/chunks/{computer-use-R7KA6UJ6.js → computer-use-UKQBH7UM.js} +39 -36
  138. package/chunks/{config-utils-6FXFJUYB.js → config-utils-FYTBZLCJ.js} +3 -3
  139. package/chunks/{contextCommand-KAQQPHZ4.js → contextCommand-ESHGAVWX.js} +36 -33
  140. package/chunks/{create-sub-session-TDPDBU4K.js → create-sub-session-574EPZUU.js} +34 -31
  141. package/chunks/{create-sub-session-X5RVIHCK.js → create-sub-session-AZ77LBL3.js} +3 -3
  142. package/chunks/{cron-create-AC5FFLN7.js → cron-create-KTWJM7QT.js} +5 -5
  143. package/chunks/{cron-delete-JEB3FAHA.js → cron-delete-2P3I5ULL.js} +5 -5
  144. package/chunks/{cron-list-NBYPCNIB.js → cron-list-PXDPGEDQ.js} +5 -5
  145. package/chunks/{daemon-RG2MAI6T.js → daemon-GJRFILYS.js} +323 -99
  146. package/chunks/daemon-status-provider-GZXZP3NU.js +80 -0
  147. package/chunks/{de-I7ZIYXZC.js → de-4IBXM7CN.js} +5 -1
  148. package/chunks/{dist-AU7NQQRP.js → dist-OAV7LJGJ.js} +1 -1
  149. package/chunks/{dist-FUTEXY6A.js → dist-OMW6WDEO.js} +1 -1
  150. package/chunks/{dist-2MIU4UUH.js → dist-PJLG2XYX.js} +1 -1
  151. package/chunks/{dist-53PZYC5B.js → dist-UIFWIFRO.js} +2 -2
  152. package/chunks/{dist-2BHAYBKP.js → dist-XBJVSWS2.js} +1 -1
  153. package/chunks/{dist-WGTQO7F2.js → dist-XRYV6TJP.js} +65 -25
  154. package/chunks/{earlyInputCapture-WC7RI5HV.js → earlyInputCapture-GI3HGQIT.js} +35 -32
  155. package/chunks/{edit-6MHKCJCM.js → edit-EBJK74B3.js} +42 -41
  156. package/chunks/{en-XE34GKAA.js → en-USMCCJAJ.js} +5 -1
  157. package/chunks/{enter-worktree-O7VJ2E7A.js → enter-worktree-2ETY5CSV.js} +39 -36
  158. package/chunks/{enterPlanMode-5XYAALIO.js → enterPlanMode-NY4U2727.js} +45 -37
  159. package/chunks/{environment-LSKFNLBU.js → environment-33IR3NOU.js} +36 -33
  160. package/chunks/{errors-ZFVCY6HG.js → errors-2OCY23IC.js} +36 -33
  161. package/chunks/{exit-worktree-MYIK66T7.js → exit-worktree-Y4ULJ45U.js} +39 -36
  162. package/chunks/{exitPlanMode-7MBNU76O.js → exitPlanMode-SECI2EQ6.js} +39 -36
  163. package/chunks/{fast-path-RNLIB64C.js → fast-path-6Z7RW5J5.js} +3 -2
  164. package/chunks/{fr-X7KDVZIY.js → fr-WVHEBDDB.js} +5 -1
  165. package/chunks/{gemini-WK5ISEAQ.js → gemini-XLGLUGSU.js} +93 -89
  166. package/chunks/{geminiContentGenerator-NUJQBZBW.js → geminiContentGenerator-NNZZDH24.js} +5 -5
  167. package/chunks/{getMachineId-bsd-EXV7SWPA.js → getMachineId-bsd-QFVLPUPT.js} +1 -1
  168. package/chunks/{getMachineId-darwin-IUOMFXU3.js → getMachineId-darwin-DGMQQE2E.js} +1 -1
  169. package/chunks/{getMachineId-linux-K7XJYFHL.js → getMachineId-linux-R4Z6CSWC.js} +1 -1
  170. package/chunks/{getMachineId-unsupported-EA5FDRJ6.js → getMachineId-unsupported-Z3SBVBUV.js} +1 -1
  171. package/chunks/{getMachineId-win-KBA6RAI5.js → getMachineId-win-SCK5UFDT.js} +1 -1
  172. package/chunks/{glob-7P6RYY4L.js → glob-KZA64SSV.js} +41 -38
  173. package/chunks/{grep-V3QHNP2J.js → grep-ONHQMY3V.js} +41 -38
  174. package/chunks/handleAutoUpdate-PRTJISXQ.js +73 -0
  175. package/chunks/{i18n-B7IO7WQT.js → i18n-ZTKKG5R5.js} +35 -32
  176. package/chunks/{initializer-E5TIC3CW.js → initializer-FPPZGBYN.js} +40 -37
  177. package/chunks/{installationInfo-XLPNAISK.js → installationInfo-DV2C27HT.js} +37 -32
  178. package/chunks/{ja-2ICT3KXF.js → ja-KY4ROZTE.js} +5 -1
  179. package/chunks/{keychain-token-storage-DWRJMNH3.js → keychain-token-storage-6ACJDYIB.js} +3 -3
  180. package/chunks/{list-3CZR5I42.js → list-KEHCNUAK.js} +42 -39
  181. package/chunks/{loadedSettingsAdapter-X5BSC6CE.js → loadedSettingsAdapter-7RZ6M3WH.js} +39 -36
  182. package/chunks/{loop-wakeup-HMHCT5GU.js → loop-wakeup-RNMRVA66.js} +6 -6
  183. package/chunks/{ls-IW5HYDG4.js → ls-J2ZI5XYK.js} +5 -5
  184. package/chunks/{lsp-4RL52YIZ.js → lsp-UMS3NUB5.js} +3 -3
  185. package/chunks/managed-npm-update-EBKNOG37.js +332 -0
  186. package/chunks/{mcp-4C4HWXAR.js → mcp-NHXKZRRP.js} +39 -36
  187. package/chunks/{monitor-3CJDNZB2.js → monitor-FMUAIFFH.js} +39 -36
  188. package/chunks/nonInteractiveCli-I2GPZNTP.js +132 -0
  189. package/chunks/{notebook-edit-MX366HCT.js → notebook-edit-V7RNXKVL.js} +43 -42
  190. package/chunks/{openaiContentGenerator-KRPNNJGZ.js → openaiContentGenerator-IBVUUZDH.js} +19 -18
  191. package/chunks/{pidfile-K7T2JLUJ.js → pidfile-AMTGL2H2.js} +35 -32
  192. package/chunks/{processUtils-YXL3VIBR.js → processUtils-3ZT2JF6D.js} +2 -2
  193. package/chunks/{pt-JJ4XPIBP.js → pt-OK455PLH.js} +5 -1
  194. package/chunks/{qwenContentGenerator-GJVXFZ3U.js → qwenContentGenerator-E72VVWS3.js} +41 -38
  195. package/chunks/{qwenOAuth2-UZTIBQLY.js → qwenOAuth2-YCC3HP24.js} +17 -16
  196. package/chunks/{read-file-S5XQSYOW.js → read-file-5EWNGUXN.js} +13 -11
  197. package/chunks/{read-mcp-resource-OIBCNIX7.js → read-mcp-resource-F6HYMDUY.js} +3 -3
  198. package/chunks/{record-artifact-HDMK4LHG.js → record-artifact-7GCFLDD7.js} +3 -3
  199. package/chunks/{resumeHistoryUtils-IKR6XD2S.js → resumeHistoryUtils-IH4RNB76.js} +41 -38
  200. package/chunks/{ripGrep-H65GRSQX.js → ripGrep-B6A6N7GI.js} +34 -31
  201. package/chunks/{ru-STR4KTW7.js → ru-7SPDGMGD.js} +5 -1
  202. package/chunks/{run-qwen-serve-7SKAQOAA.js → run-qwen-serve-6PKSMF6Z.js} +115 -74
  203. package/chunks/{runtime-I2STBGPR.js → runtime-ASRANXO6.js} +45 -40
  204. package/chunks/{scheduler-6F7HETNO.js → scheduler-IABM76UZ.js} +34 -31
  205. package/chunks/sdk-exporters-grpc-ETLH47EP.js +23214 -0
  206. package/chunks/sdk-exporters-http-6MCQH335.js +563 -0
  207. package/chunks/sdk-impl-HOLWAXC6.js +9193 -0
  208. package/chunks/{send-message-WXVVK4DB.js → send-message-KBO6X4ZS.js} +7 -5
  209. package/chunks/{serve-4ATEWSEA.js → serve-A4DT5D32.js} +39 -36
  210. package/chunks/{server-YPUPFV2O.js → server-DZ5ZSVRE.js} +2317 -472
  211. package/chunks/{session-AZFIERIY.js → session-G2R3CYU6.js} +87 -172
  212. package/chunks/{settings-EFQHLTM3.js → settings-7TNSXUTO.js} +43 -40
  213. package/chunks/{shell-FWXWBJ4Q.js → shell-5BRFGEMK.js} +34 -31
  214. package/chunks/{skill-A634MNCD.js → skill-3SWYEK7M.js} +24 -20
  215. package/chunks/{spawnChannel-KKBGGR47.js → spawnChannel-GGN2WVWW.js} +36 -33
  216. package/chunks/{src-BVROLD6N.js → src-5BPBNQ5S.js} +314 -236
  217. package/chunks/{standalone-update-ERLA3BDC.js → standalone-update-AHOZ56LS.js} +37 -34
  218. package/chunks/{startInteractiveUI-3VZ23WAY.js → startInteractiveUI-TLGOQVV7.js} +1105 -906
  219. package/chunks/{syntheticOutput-HCUFXSIA.js → syntheticOutput-H7RTI5KL.js} +4 -4
  220. package/chunks/{task-create-RIY5JTFC.js → task-create-7474AJJD.js} +10 -8
  221. package/chunks/{task-list-XBUCV3CO.js → task-list-633HGOIB.js} +6 -6
  222. package/chunks/{task-stop-QDFCCYR5.js → task-stop-MNUGHPIA.js} +3 -3
  223. package/chunks/{task-update-7PXKJQOI.js → task-update-66GQB5LI.js} +10 -8
  224. package/chunks/{team-create-ZZO7QFQ7.js → team-create-XHDF7UKM.js} +42 -39
  225. package/chunks/{team-delete-TNSSE2S5.js → team-delete-BB3CG3QF.js} +6 -6
  226. package/chunks/{team-plan-approval-3BZBJ46K.js → team-plan-approval-XKSBXWMH.js} +39 -36
  227. package/chunks/{theme-manager-FSFWNXFJ.js → theme-manager-6ZKLBFAN.js} +35 -32
  228. package/chunks/{todoWrite-OMAIGB6V.js → todoWrite-KRAUN54W.js} +5 -5
  229. package/chunks/{tool-search-VYXAAIDW.js → tool-search-UDNJCXYS.js} +21 -17
  230. package/chunks/{total-session-admission-PSMLQICS.js → total-session-admission-VWRCCDYM.js} +40 -37
  231. package/chunks/{tree-sitter-4D7QS7F6.js → tree-sitter-L5BFT64K.js} +1 -1
  232. package/chunks/{tree-sitter-bash-VEJGF5XF.js → tree-sitter-bash-ZKDNQGID.js} +1 -1
  233. package/chunks/{trustedFolders-QA3RK2NV.js → trustedFolders-TJI6OLAN.js} +35 -32
  234. package/chunks/{chunk-6EFTQYW7.js → undici-3FJYTMOF.js} +24 -399
  235. package/chunks/{chunk-L573Z2QZ.js → undici-PYHBDDPN.js} +1 -5
  236. package/chunks/{update-relaunch-LNLZFX3J.js → update-relaunch-RS5GB74A.js} +17 -17
  237. package/chunks/updateCheck-T4EEA5YR.js +88 -0
  238. package/chunks/{useAutoAcceptIndicator-DIWN27LT.js → useAutoAcceptIndicator-LLWMXC7F.js} +44 -41
  239. package/chunks/{validateNonInterActiveAuth-LOEOFCAF.js → validateNonInterActiveAuth-OJ3KYXAR.js} +74 -71
  240. package/chunks/{version-HBF2VBLE.js → version-ZCEUV5DO.js} +1 -1
  241. package/chunks/{web-fetch-BWGSD2BD.js → web-fetch-KQF4YFCI.js} +99 -42
  242. package/chunks/{web-search-OOHTCVR3.js → web-search-QDDGFGKI.js} +113 -61
  243. package/chunks/{workflow-LJAJBOR4.js → workflow-GIRKCX4P.js} +47 -43
  244. package/chunks/{workspace-providers-status-FYV7TTHA.js → workspace-providers-status-UTMAVTNE.js} +42 -39
  245. package/chunks/{workspace-registration-store-4EHGQW4Y.js → workspace-registration-store-EYJMJFZU.js} +8 -2
  246. package/chunks/{workspace-registry-BKD7VC4Y.js → workspace-registry-4W4UW6MY.js} +40 -37
  247. package/chunks/{workspace-service-75RHX6KR.js → workspace-service-DJCPY6ZN.js} +46 -43
  248. package/chunks/{workspace-skills-status-WBZBZI6A.js → workspace-skills-status-VQ2LKXXX.js} +40 -37
  249. package/chunks/write-file-PLK6RQ7M.js +65 -0
  250. package/chunks/{zh-TW-4RR3YHNN.js → zh-TW-BM47YBFH.js} +5 -1
  251. package/chunks/{zh-6ANG2HTL.js → zh-WY5DWYZD.js} +5 -1
  252. package/cli-entry.js +164 -12
  253. package/cli.js +18 -11
  254. package/locales/ca.js +772 -203
  255. package/locales/de.js +8 -2
  256. package/locales/en.js +8 -2
  257. package/locales/fr.js +8 -2
  258. package/locales/ja.js +8 -2
  259. package/locales/pt.js +8 -2
  260. package/locales/ru.js +8 -2
  261. package/locales/zh-TW.js +8 -2
  262. package/locales/zh.js +8 -2
  263. package/package.json +3 -3
  264. package/web-shell/assets/{arc-Buk1besA.js → arc-DIQrcXXh.js} +1 -1
  265. package/web-shell/assets/{architectureDiagram-3BPJPVTR-B1aUKYDC.js → architectureDiagram-3BPJPVTR-CbPd-DSw.js} +1 -1
  266. package/web-shell/assets/{blockDiagram-GPEHLZMM-CRTdg3Zx.js → blockDiagram-GPEHLZMM-yzBIVhMX.js} +1 -1
  267. package/web-shell/assets/{c4Diagram-AAUBKEIU-DFdRMp5g.js → c4Diagram-AAUBKEIU-B88Swcsu.js} +1 -1
  268. package/web-shell/assets/channel-BaTMUesZ.js +1 -0
  269. package/web-shell/assets/{chunk-2J33WTMH-4rYQdkEI.js → chunk-2J33WTMH-BbOLo6NX.js} +1 -1
  270. package/web-shell/assets/{chunk-4BX2VUAB-Coi-pQJy.js → chunk-4BX2VUAB-Bg6in0r0.js} +1 -1
  271. package/web-shell/assets/{chunk-55IACEB6-BtBjz02t.js → chunk-55IACEB6-Bv9QRyLI.js} +1 -1
  272. package/web-shell/assets/{chunk-727SXJPM-CGYOWorl.js → chunk-727SXJPM-CFokiv61.js} +1 -1
  273. package/web-shell/assets/{chunk-AQP2D5EJ-CH5AKhqx.js → chunk-AQP2D5EJ-DS2Oxf6L.js} +1 -1
  274. package/web-shell/assets/{chunk-FMBD7UC4-Cd50-w85.js → chunk-FMBD7UC4-D2NkHD3B.js} +1 -1
  275. package/web-shell/assets/{chunk-ND2GUHAM-C2wF3KCK.js → chunk-ND2GUHAM-BsT_UC5B.js} +1 -1
  276. package/web-shell/assets/{chunk-QZHKN3VN-pCeRTaWi.js → chunk-QZHKN3VN-tnJo3zln.js} +1 -1
  277. package/web-shell/assets/classDiagram-4FO5ZUOK-CyBPzWud.js +1 -0
  278. package/web-shell/assets/classDiagram-v2-Q7XG4LA2-CyBPzWud.js +1 -0
  279. package/web-shell/assets/{cose-bilkent-S5V4N54A-B-_fAB6D.js → cose-bilkent-S5V4N54A-BTMa6DAZ.js} +1 -1
  280. package/web-shell/assets/{dagre-BM42HDAG-ChSPNHpL.js → dagre-BM42HDAG-ujGX7Owg.js} +1 -1
  281. package/web-shell/assets/{diagram-2AECGRRQ-BX7cFOF3.js → diagram-2AECGRRQ-fU4-dbPa.js} +1 -1
  282. package/web-shell/assets/{diagram-5GNKFQAL-BQUTW92n.js → diagram-5GNKFQAL-Bdm-TYSA.js} +1 -1
  283. package/web-shell/assets/{diagram-KO2AKTUF-BkYPh3e4.js → diagram-KO2AKTUF-Bkhz85Z9.js} +1 -1
  284. package/web-shell/assets/{diagram-LMA3HP47-Cl6jsNyx.js → diagram-LMA3HP47-Bzu3q26p.js} +1 -1
  285. package/web-shell/assets/{diagram-OG6HWLK6-DRWoHz8n.js → diagram-OG6HWLK6-CZrXbG5Q.js} +1 -1
  286. package/web-shell/assets/{erDiagram-TEJ5UH35-CGvFcZco.js → erDiagram-TEJ5UH35-BjozEAYu.js} +1 -1
  287. package/web-shell/assets/{flowDiagram-I6XJVG4X-vms6oVdv.js → flowDiagram-I6XJVG4X-B3a2I8c-.js} +1 -1
  288. package/web-shell/assets/{ganttDiagram-6RSMTGT7-ukT_sfmi.js → ganttDiagram-6RSMTGT7-CIMn9fNm.js} +1 -1
  289. package/web-shell/assets/{gitGraphDiagram-PVQCEYII-Bn2ZE2Ut.js → gitGraphDiagram-PVQCEYII-DlFy9KRx.js} +1 -1
  290. package/web-shell/assets/{index-wFXp7W68.js → index-BODUAzQA.js} +1 -1
  291. package/web-shell/assets/index-C54DNMF7.js +1209 -0
  292. package/web-shell/assets/index-lWqBfc78.css +5 -0
  293. package/web-shell/assets/{infoDiagram-5YYISTIA-DHJdSi7x.js → infoDiagram-5YYISTIA-BmKjQgCy.js} +1 -1
  294. package/web-shell/assets/{ishikawaDiagram-YF4QCWOH-DOvd2Wph.js → ishikawaDiagram-YF4QCWOH-BrQEMZz2.js} +1 -1
  295. package/web-shell/assets/{journeyDiagram-JHISSGLW-CH_urMCT.js → journeyDiagram-JHISSGLW-D-2r7Xrt.js} +1 -1
  296. package/web-shell/assets/{kanban-definition-UN3LZRKU-FKiBdgbH.js → kanban-definition-UN3LZRKU-CndsFHCX.js} +1 -1
  297. package/web-shell/assets/{linear-0ZVQFVKf.js → linear-D-IwNnKx.js} +1 -1
  298. package/web-shell/assets/{mermaid.core-DJ05ZZIK.js → mermaid.core-4ll09sri.js} +5 -5
  299. package/web-shell/assets/{mindmap-definition-RKZ34NQL-BPuUhkUm.js → mindmap-definition-RKZ34NQL-maMRIxjo.js} +1 -1
  300. package/web-shell/assets/{pieDiagram-4H26LBE5-yLFKcXyG.js → pieDiagram-4H26LBE5-aunUDhrJ.js} +1 -1
  301. package/web-shell/assets/{quadrantDiagram-W4KKPZXB-irWqc1pE.js → quadrantDiagram-W4KKPZXB-D3K0P1NZ.js} +1 -1
  302. package/web-shell/assets/{requirementDiagram-4Y6WPE33-B_4uMoIV.js → requirementDiagram-4Y6WPE33-CX2X9HRc.js} +1 -1
  303. package/web-shell/assets/{sankeyDiagram-5OEKKPKP-ciA4GPwk.js → sankeyDiagram-5OEKKPKP-CDroWk7l.js} +1 -1
  304. package/web-shell/assets/{sequenceDiagram-3UESZ5HK-CRdZvy0U.js → sequenceDiagram-3UESZ5HK-DTk-2b16.js} +1 -1
  305. package/web-shell/assets/{stateDiagram-AJRCARHV-DaYIkCCn.js → stateDiagram-AJRCARHV-Cud64hQr.js} +1 -1
  306. package/web-shell/assets/stateDiagram-v2-BHNVJYJU-g-uUpecT.js +1 -0
  307. package/web-shell/assets/{timeline-definition-PNZ67QCA-oBUKv6iH.js → timeline-definition-PNZ67QCA-DfD5okf_.js} +1 -1
  308. package/web-shell/assets/{vennDiagram-CIIHVFJN-CGW9Sdmb.js → vennDiagram-CIIHVFJN-BYl8ay25.js} +1 -1
  309. package/web-shell/assets/{wardley-L42UT6IY-CvwKJOCm.js → wardley-L42UT6IY-BZFAt10J.js} +1 -1
  310. package/web-shell/assets/{wardleyDiagram-YWT4CUSO-Ipc260sN.js → wardleyDiagram-YWT4CUSO-BIWn0GA7.js} +1 -1
  311. package/web-shell/assets/{xychartDiagram-2RQKCTM6-D6-CM7pK.js → xychartDiagram-2RQKCTM6-1_H4xblT.js} +1 -1
  312. package/web-shell/index.html +2 -2
  313. package/chunks/chunk-ETD6K42I.js +0 -358
  314. package/chunks/chunk-I5NLVPZJ.js +0 -45
  315. package/chunks/chunk-ONWW74X6.js +0 -74639
  316. package/chunks/chunk-W7FJ3N32.js +0 -49
  317. package/chunks/daemon-status-provider-LVTVJGAD.js +0 -77
  318. package/chunks/handleAutoUpdate-AAQ6PL3E.js +0 -70
  319. package/chunks/nonInteractiveCli-QTEHDDFH.js +0 -129
  320. package/chunks/updateCheck-JJEUQ54U.js +0 -73
  321. package/chunks/write-file-M2DTFILF.js +0 -599
  322. package/web-shell/assets/channel-04R0vLbG.js +0 -1
  323. package/web-shell/assets/classDiagram-4FO5ZUOK-Bw9SOwAV.js +0 -1
  324. package/web-shell/assets/classDiagram-v2-Q7XG4LA2-Bw9SOwAV.js +0 -1
  325. package/web-shell/assets/index-DgkKrjw3.js +0 -1187
  326. package/web-shell/assets/index-Rv6mOAN9.css +0 -5
  327. package/web-shell/assets/stateDiagram-v2-BHNVJYJU-DWBoO4UY.js +0 -1
@@ -0,0 +1,2290 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import {
4
+ DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH,
5
+ EVENT_CHAT_COMPRESSION,
6
+ SERVICE_NAME,
7
+ SPAN_HOOK,
8
+ SPAN_INTERACTION,
9
+ SPAN_LLM_REQUEST,
10
+ SPAN_SUBAGENT,
11
+ SPAN_TOOL,
12
+ SPAN_TOOL_BLOCKED_ON_USER,
13
+ SPAN_TOOL_EXECUTION,
14
+ safeJsonStringify
15
+ } from "./chunk-BULDBTYC.js";
16
+ import {
17
+ createDebugLogger,
18
+ getCurrentSessionId,
19
+ setSessionContext,
20
+ setShellTracePropagation
21
+ } from "./chunk-OQB4EXO4.js";
22
+ import {
23
+ DiagLogLevel,
24
+ ROOT_CONTEXT,
25
+ SpanKind,
26
+ SpanStatusCode,
27
+ TraceFlags,
28
+ ValueType,
29
+ context,
30
+ diag,
31
+ init_esm,
32
+ metrics,
33
+ trace
34
+ } from "./chunk-THJNPLI4.js";
35
+ import {
36
+ init_esbuild_shims
37
+ } from "./chunk-5O2XNYP6.js";
38
+ import {
39
+ __name
40
+ } from "./chunk-J2S4EL5Y.js";
41
+
42
+ // packages/core/src/telemetry/metrics.ts
43
+ init_esbuild_shims();
44
+ init_esm();
45
+ var TOOL_CALL_COUNT = `${SERVICE_NAME}.tool.call.count`;
46
+ var TOOL_CALL_LATENCY = `${SERVICE_NAME}.tool.call.latency`;
47
+ var API_REQUEST_COUNT = `${SERVICE_NAME}.api.request.count`;
48
+ var API_REQUEST_LATENCY = `${SERVICE_NAME}.api.request.latency`;
49
+ var TOKEN_USAGE = `${SERVICE_NAME}.token.usage`;
50
+ var SESSION_COUNT = `${SERVICE_NAME}.session.count`;
51
+ var FILE_OPERATION_COUNT = `${SERVICE_NAME}.file.operation.count`;
52
+ var INVALID_CHUNK_COUNT = `${SERVICE_NAME}.chat.invalid_chunk.count`;
53
+ var CONTENT_RETRY_COUNT = `${SERVICE_NAME}.chat.content_retry.count`;
54
+ var CONTENT_RETRY_FAILURE_COUNT = `${SERVICE_NAME}.chat.content_retry_failure.count`;
55
+ var API_RETRY_COUNT = `${SERVICE_NAME}.api.retry.count`;
56
+ var MODEL_SLASH_COMMAND_CALL_COUNT = `${SERVICE_NAME}.slash_command.model.call_count`;
57
+ var SUBAGENT_EXECUTION_COUNT = `${SERVICE_NAME}.subagent.execution.count`;
58
+ var ARENA_SESSION_COUNT = `${SERVICE_NAME}.arena.session.count`;
59
+ var ARENA_SESSION_DURATION = `${SERVICE_NAME}.arena.session.duration`;
60
+ var ARENA_AGENT_COUNT = `${SERVICE_NAME}.arena.agent.count`;
61
+ var ARENA_AGENT_DURATION = `${SERVICE_NAME}.arena.agent.duration`;
62
+ var ARENA_AGENT_TOKENS = `${SERVICE_NAME}.arena.agent.tokens`;
63
+ var ARENA_RESULT_SELECTED = `${SERVICE_NAME}.arena.result.selected`;
64
+ var STARTUP_TIME = `${SERVICE_NAME}.startup.duration`;
65
+ var MEMORY_USAGE = `${SERVICE_NAME}.memory.usage`;
66
+ var CPU_USAGE = `${SERVICE_NAME}.cpu.usage`;
67
+ var TOOL_QUEUE_DEPTH = `${SERVICE_NAME}.tool.queue.depth`;
68
+ var TOOL_EXECUTION_BREAKDOWN = `${SERVICE_NAME}.tool.execution.breakdown`;
69
+ var TOKEN_EFFICIENCY = `${SERVICE_NAME}.token.efficiency`;
70
+ var API_REQUEST_BREAKDOWN = `${SERVICE_NAME}.api.request.breakdown`;
71
+ var PERFORMANCE_SCORE = `${SERVICE_NAME}.performance.score`;
72
+ var REGRESSION_DETECTION = `${SERVICE_NAME}.performance.regression`;
73
+ var REGRESSION_PERCENTAGE_CHANGE = `${SERVICE_NAME}.performance.regression.percentage_change`;
74
+ var BASELINE_COMPARISON = `${SERVICE_NAME}.performance.baseline.comparison`;
75
+ var MEMORY_EXTRACT_COUNT = `${SERVICE_NAME}.memory.extract.count`;
76
+ var MEMORY_EXTRACT_DURATION = `${SERVICE_NAME}.memory.extract.duration`;
77
+ var MEMORY_DREAM_COUNT = `${SERVICE_NAME}.memory.dream.count`;
78
+ var MEMORY_DREAM_DURATION = `${SERVICE_NAME}.memory.dream.duration`;
79
+ var MEMORY_RECALL_COUNT = `${SERVICE_NAME}.memory.recall.count`;
80
+ var MEMORY_RECALL_DURATION = `${SERVICE_NAME}.memory.recall.duration`;
81
+ var CHANNEL_MEMORY_RECALL_COUNT = `${SERVICE_NAME}.channel.memory.recall.count`;
82
+ var CHANNEL_MEMORY_RECALL_DURATION = `${SERVICE_NAME}.channel.memory.recall.duration`;
83
+ var CHANNEL_MEMORY_RECALL_SELECTED_COUNT = `${SERVICE_NAME}.channel.memory.recall.selected_count`;
84
+ var MEMORY_RECALL_DELIVERY_COUNT = `${SERVICE_NAME}.memory.recall.delivery.count`;
85
+ var MEMORY_RECALL_DELIVERY_LATENCY = `${SERVICE_NAME}.memory.recall.delivery.latency`;
86
+ var baseMetricDefinition = {
87
+ // session.id on metrics is opt-in: each session is a new value, so
88
+ // attaching it by default would create unbounded time-series fan-out on
89
+ // every metric backend. Operators who need session-level metric slicing
90
+ // can enable QWEN_TELEMETRY_METRICS_INCLUDE_SESSION_ID or
91
+ // telemetry.metrics.includeSessionId. Spans and logs always carry
92
+ // session.id for trace/log correlation.
93
+ getCommonAttributes: /* @__PURE__ */ __name((config) => {
94
+ const out = {};
95
+ if (config.getTelemetryMetricsIncludeSessionId()) {
96
+ out["session.id"] = config.getSessionId();
97
+ }
98
+ return out;
99
+ }, "getCommonAttributes")
100
+ };
101
+ var COUNTER_DEFINITIONS = {
102
+ [TOOL_CALL_COUNT]: {
103
+ description: "Counts tool calls, tagged by function name and success.",
104
+ valueType: ValueType.INT,
105
+ assign: /* @__PURE__ */ __name((c) => toolCallCounter = c, "assign"),
106
+ attributes: {}
107
+ },
108
+ [API_REQUEST_COUNT]: {
109
+ description: "Counts API requests, tagged by model and status.",
110
+ valueType: ValueType.INT,
111
+ assign: /* @__PURE__ */ __name((c) => apiRequestCounter = c, "assign"),
112
+ attributes: {}
113
+ },
114
+ [TOKEN_USAGE]: {
115
+ description: "Counts the total number of tokens used.",
116
+ valueType: ValueType.INT,
117
+ assign: /* @__PURE__ */ __name((c) => tokenUsageCounter = c, "assign"),
118
+ attributes: {}
119
+ },
120
+ [SESSION_COUNT]: {
121
+ description: "Count of CLI sessions started.",
122
+ valueType: ValueType.INT,
123
+ assign: /* @__PURE__ */ __name((c) => sessionCounter = c, "assign"),
124
+ attributes: {}
125
+ },
126
+ [FILE_OPERATION_COUNT]: {
127
+ description: "Counts file operations (create, read, update).",
128
+ valueType: ValueType.INT,
129
+ assign: /* @__PURE__ */ __name((c) => fileOperationCounter = c, "assign"),
130
+ attributes: {}
131
+ },
132
+ [INVALID_CHUNK_COUNT]: {
133
+ description: "Counts invalid chunks received from a stream.",
134
+ valueType: ValueType.INT,
135
+ assign: /* @__PURE__ */ __name((c) => invalidChunkCounter = c, "assign"),
136
+ attributes: {}
137
+ },
138
+ [CONTENT_RETRY_COUNT]: {
139
+ description: "Counts retries due to content errors (e.g., empty stream).",
140
+ valueType: ValueType.INT,
141
+ assign: /* @__PURE__ */ __name((c) => contentRetryCounter = c, "assign"),
142
+ attributes: {}
143
+ },
144
+ [CONTENT_RETRY_FAILURE_COUNT]: {
145
+ description: "Counts occurrences of all content retries failing.",
146
+ valueType: ValueType.INT,
147
+ assign: /* @__PURE__ */ __name((c) => contentRetryFailureCounter = c, "assign"),
148
+ attributes: {}
149
+ },
150
+ [API_RETRY_COUNT]: {
151
+ description: "Counts HTTP-status retries (429/5xx) at LLM call sites, emitted by retryWithBackoff onRetry callback.",
152
+ valueType: ValueType.INT,
153
+ assign: /* @__PURE__ */ __name((c) => apiRetryCounter = c, "assign"),
154
+ attributes: {}
155
+ },
156
+ [MODEL_SLASH_COMMAND_CALL_COUNT]: {
157
+ description: "Counts model slash command calls.",
158
+ valueType: ValueType.INT,
159
+ assign: /* @__PURE__ */ __name((c) => modelSlashCommandCallCounter = c, "assign"),
160
+ attributes: {}
161
+ },
162
+ [EVENT_CHAT_COMPRESSION]: {
163
+ description: "Counts chat compression events.",
164
+ valueType: ValueType.INT,
165
+ assign: /* @__PURE__ */ __name((c) => chatCompressionCounter = c, "assign"),
166
+ attributes: {}
167
+ }
168
+ };
169
+ var HISTOGRAM_DEFINITIONS = {
170
+ [TOOL_CALL_LATENCY]: {
171
+ description: "Latency of tool calls in milliseconds.",
172
+ unit: "ms",
173
+ valueType: ValueType.INT,
174
+ assign: /* @__PURE__ */ __name((h) => toolCallLatencyHistogram = h, "assign"),
175
+ attributes: {}
176
+ },
177
+ [API_REQUEST_LATENCY]: {
178
+ description: "Latency of API requests in milliseconds.",
179
+ unit: "ms",
180
+ valueType: ValueType.INT,
181
+ assign: /* @__PURE__ */ __name((h) => apiRequestLatencyHistogram = h, "assign"),
182
+ attributes: {}
183
+ }
184
+ };
185
+ var PERFORMANCE_COUNTER_DEFINITIONS = {
186
+ [REGRESSION_DETECTION]: {
187
+ description: "Performance regression detection events.",
188
+ valueType: ValueType.INT,
189
+ assign: /* @__PURE__ */ __name((c) => regressionDetectionCounter = c, "assign"),
190
+ attributes: {}
191
+ }
192
+ };
193
+ var PERFORMANCE_HISTOGRAM_DEFINITIONS = {
194
+ [STARTUP_TIME]: {
195
+ description: "CLI startup time in milliseconds, broken down by initialization phase.",
196
+ unit: "ms",
197
+ valueType: ValueType.DOUBLE,
198
+ assign: /* @__PURE__ */ __name((h) => startupTimeHistogram = h, "assign"),
199
+ attributes: {}
200
+ },
201
+ [MEMORY_USAGE]: {
202
+ description: "Memory usage in bytes.",
203
+ unit: "bytes",
204
+ valueType: ValueType.INT,
205
+ assign: /* @__PURE__ */ __name((h) => memoryUsageGauge = h, "assign"),
206
+ attributes: {}
207
+ },
208
+ [CPU_USAGE]: {
209
+ description: "CPU usage percentage.",
210
+ unit: "percent",
211
+ valueType: ValueType.DOUBLE,
212
+ assign: /* @__PURE__ */ __name((h) => cpuUsageGauge = h, "assign"),
213
+ attributes: {}
214
+ },
215
+ [TOOL_QUEUE_DEPTH]: {
216
+ description: "Number of tools in execution queue.",
217
+ unit: "count",
218
+ valueType: ValueType.INT,
219
+ assign: /* @__PURE__ */ __name((h) => toolQueueDepthGauge = h, "assign"),
220
+ attributes: {}
221
+ },
222
+ [TOOL_EXECUTION_BREAKDOWN]: {
223
+ description: "Tool execution time breakdown by phase in milliseconds.",
224
+ unit: "ms",
225
+ valueType: ValueType.INT,
226
+ assign: /* @__PURE__ */ __name((h) => toolExecutionBreakdownHistogram = h, "assign"),
227
+ attributes: {}
228
+ },
229
+ [TOKEN_EFFICIENCY]: {
230
+ description: "Token efficiency metrics (tokens per operation, cache hit rate, etc.).",
231
+ unit: "ratio",
232
+ valueType: ValueType.DOUBLE,
233
+ assign: /* @__PURE__ */ __name((h) => tokenEfficiencyHistogram = h, "assign"),
234
+ attributes: {}
235
+ },
236
+ [API_REQUEST_BREAKDOWN]: {
237
+ description: "API request time breakdown by phase in milliseconds.",
238
+ unit: "ms",
239
+ valueType: ValueType.INT,
240
+ assign: /* @__PURE__ */ __name((h) => apiRequestBreakdownHistogram = h, "assign"),
241
+ attributes: {}
242
+ },
243
+ [PERFORMANCE_SCORE]: {
244
+ description: "Composite performance score (0-100).",
245
+ unit: "score",
246
+ valueType: ValueType.DOUBLE,
247
+ assign: /* @__PURE__ */ __name((h) => performanceScoreGauge = h, "assign"),
248
+ attributes: {}
249
+ },
250
+ [REGRESSION_PERCENTAGE_CHANGE]: {
251
+ description: "Percentage change compared to baseline for detected regressions.",
252
+ unit: "percent",
253
+ valueType: ValueType.DOUBLE,
254
+ assign: /* @__PURE__ */ __name((h) => regressionPercentageChangeHistogram = h, "assign"),
255
+ attributes: {}
256
+ },
257
+ [BASELINE_COMPARISON]: {
258
+ description: "Performance comparison to established baseline (percentage change).",
259
+ unit: "percent",
260
+ valueType: ValueType.DOUBLE,
261
+ assign: /* @__PURE__ */ __name((h) => baselineComparisonHistogram = h, "assign"),
262
+ attributes: {}
263
+ }
264
+ };
265
+ var FileOperation = /* @__PURE__ */ ((FileOperation2) => {
266
+ FileOperation2["CREATE"] = "create";
267
+ FileOperation2["READ"] = "read";
268
+ FileOperation2["UPDATE"] = "update";
269
+ return FileOperation2;
270
+ })(FileOperation || {});
271
+ var PerformanceMetricType = /* @__PURE__ */ ((PerformanceMetricType2) => {
272
+ PerformanceMetricType2["STARTUP"] = "startup";
273
+ PerformanceMetricType2["MEMORY"] = "memory";
274
+ PerformanceMetricType2["CPU"] = "cpu";
275
+ PerformanceMetricType2["TOOL_EXECUTION"] = "tool_execution";
276
+ PerformanceMetricType2["API_REQUEST"] = "api_request";
277
+ PerformanceMetricType2["TOKEN_EFFICIENCY"] = "token_efficiency";
278
+ return PerformanceMetricType2;
279
+ })(PerformanceMetricType || {});
280
+ var MemoryMetricType = /* @__PURE__ */ ((MemoryMetricType2) => {
281
+ MemoryMetricType2["HEAP_USED"] = "heap_used";
282
+ MemoryMetricType2["HEAP_TOTAL"] = "heap_total";
283
+ MemoryMetricType2["EXTERNAL"] = "external";
284
+ MemoryMetricType2["RSS"] = "rss";
285
+ return MemoryMetricType2;
286
+ })(MemoryMetricType || {});
287
+ var ToolExecutionPhase = /* @__PURE__ */ ((ToolExecutionPhase2) => {
288
+ ToolExecutionPhase2["VALIDATION"] = "validation";
289
+ ToolExecutionPhase2["PREPARATION"] = "preparation";
290
+ ToolExecutionPhase2["EXECUTION"] = "execution";
291
+ ToolExecutionPhase2["RESULT_PROCESSING"] = "result_processing";
292
+ return ToolExecutionPhase2;
293
+ })(ToolExecutionPhase || {});
294
+ var ApiRequestPhase = /* @__PURE__ */ ((ApiRequestPhase2) => {
295
+ ApiRequestPhase2["REQUEST_PREPARATION"] = "request_preparation";
296
+ ApiRequestPhase2["NETWORK_LATENCY"] = "network_latency";
297
+ ApiRequestPhase2["RESPONSE_PROCESSING"] = "response_processing";
298
+ ApiRequestPhase2["TOKEN_PROCESSING"] = "token_processing";
299
+ return ApiRequestPhase2;
300
+ })(ApiRequestPhase || {});
301
+ var cliMeter;
302
+ var toolCallCounter;
303
+ var toolCallLatencyHistogram;
304
+ var apiRequestCounter;
305
+ var apiRequestLatencyHistogram;
306
+ var tokenUsageCounter;
307
+ var sessionCounter;
308
+ var fileOperationCounter;
309
+ var chatCompressionCounter;
310
+ var invalidChunkCounter;
311
+ var contentRetryCounter;
312
+ var contentRetryFailureCounter;
313
+ var apiRetryCounter;
314
+ var subagentExecutionCounter;
315
+ var modelSlashCommandCallCounter;
316
+ var startupTimeHistogram;
317
+ var memoryUsageGauge;
318
+ var cpuUsageGauge;
319
+ var toolQueueDepthGauge;
320
+ var toolExecutionBreakdownHistogram;
321
+ var tokenEfficiencyHistogram;
322
+ var apiRequestBreakdownHistogram;
323
+ var performanceScoreGauge;
324
+ var regressionDetectionCounter;
325
+ var regressionPercentageChangeHistogram;
326
+ var baselineComparisonHistogram;
327
+ var arenaSessionCounter;
328
+ var arenaSessionDurationHistogram;
329
+ var arenaAgentCounter;
330
+ var arenaAgentDurationHistogram;
331
+ var arenaAgentTokensCounter;
332
+ var arenaResultSelectedCounter;
333
+ var memoryExtractCounter;
334
+ var memoryExtractDurationHistogram;
335
+ var memoryDreamCounter;
336
+ var memoryDreamDurationHistogram;
337
+ var memoryRecallCounter;
338
+ var memoryRecallDurationHistogram;
339
+ var channelMemoryRecallCounter;
340
+ var channelMemoryRecallDurationHistogram;
341
+ var channelMemoryRecallSelectedCountHistogram;
342
+ var memoryRecallDeliveryCounter;
343
+ var memoryRecallDeliveryLatencyHistogram;
344
+ var isMetricsInitialized = false;
345
+ var isPerformanceMonitoringEnabled = false;
346
+ function getMeter() {
347
+ if (!cliMeter) {
348
+ cliMeter = metrics.getMeter(SERVICE_NAME);
349
+ }
350
+ return cliMeter;
351
+ }
352
+ __name(getMeter, "getMeter");
353
+ function initializeMetrics(config) {
354
+ if (isMetricsInitialized) return;
355
+ const meter = getMeter();
356
+ if (!meter) return;
357
+ Object.entries(COUNTER_DEFINITIONS).forEach(
358
+ ([name, { description, valueType, assign }]) => {
359
+ assign(meter.createCounter(name, { description, valueType }));
360
+ }
361
+ );
362
+ subagentExecutionCounter = meter.createCounter(SUBAGENT_EXECUTION_COUNT, {
363
+ description: "Counts subagent execution events, tagged by status and subagent name.",
364
+ valueType: ValueType.INT
365
+ });
366
+ arenaSessionCounter = meter.createCounter(ARENA_SESSION_COUNT, {
367
+ description: "Counts arena sessions by status and display backend.",
368
+ valueType: ValueType.INT
369
+ });
370
+ arenaSessionDurationHistogram = meter.createHistogram(
371
+ ARENA_SESSION_DURATION,
372
+ {
373
+ description: "Duration of arena sessions in milliseconds.",
374
+ unit: "ms",
375
+ valueType: ValueType.INT
376
+ }
377
+ );
378
+ arenaAgentCounter = meter.createCounter(ARENA_AGENT_COUNT, {
379
+ description: "Counts arena agent completions by status and model.",
380
+ valueType: ValueType.INT
381
+ });
382
+ arenaAgentDurationHistogram = meter.createHistogram(ARENA_AGENT_DURATION, {
383
+ description: "Duration of arena agent execution in milliseconds.",
384
+ unit: "ms",
385
+ valueType: ValueType.INT
386
+ });
387
+ arenaAgentTokensCounter = meter.createCounter(ARENA_AGENT_TOKENS, {
388
+ description: "Token usage by arena agents.",
389
+ valueType: ValueType.INT
390
+ });
391
+ arenaResultSelectedCounter = meter.createCounter(ARENA_RESULT_SELECTED, {
392
+ description: "Counts arena result selections by model.",
393
+ valueType: ValueType.INT
394
+ });
395
+ Object.entries(HISTOGRAM_DEFINITIONS).forEach(
396
+ ([name, { description, unit, valueType, assign }]) => {
397
+ assign(meter.createHistogram(name, { description, unit, valueType }));
398
+ }
399
+ );
400
+ sessionCounter?.add(1, baseMetricDefinition.getCommonAttributes(config));
401
+ memoryExtractCounter = meter.createCounter(MEMORY_EXTRACT_COUNT, {
402
+ description: "Counts auto-memory extraction runs, tagged by trigger and status.",
403
+ valueType: ValueType.INT
404
+ });
405
+ memoryExtractDurationHistogram = meter.createHistogram(
406
+ MEMORY_EXTRACT_DURATION,
407
+ {
408
+ description: "Duration of auto-memory extraction in milliseconds.",
409
+ unit: "ms",
410
+ valueType: ValueType.INT
411
+ }
412
+ );
413
+ memoryDreamCounter = meter.createCounter(MEMORY_DREAM_COUNT, {
414
+ description: "Counts auto-memory dream (consolidation) runs, tagged by trigger and status.",
415
+ valueType: ValueType.INT
416
+ });
417
+ memoryDreamDurationHistogram = meter.createHistogram(MEMORY_DREAM_DURATION, {
418
+ description: "Duration of auto-memory dream runs in milliseconds.",
419
+ unit: "ms",
420
+ valueType: ValueType.INT
421
+ });
422
+ memoryRecallCounter = meter.createCounter(MEMORY_RECALL_COUNT, {
423
+ description: "Counts auto-memory recall operations, tagged by strategy.",
424
+ valueType: ValueType.INT
425
+ });
426
+ memoryRecallDurationHistogram = meter.createHistogram(
427
+ MEMORY_RECALL_DURATION,
428
+ {
429
+ description: "Duration of auto-memory recall operations in milliseconds.",
430
+ unit: "ms",
431
+ valueType: ValueType.INT
432
+ }
433
+ );
434
+ channelMemoryRecallCounter = meter.createCounter(
435
+ CHANNEL_MEMORY_RECALL_COUNT,
436
+ {
437
+ description: "Counts channel memory recall attempts by cache path and bounded result.",
438
+ valueType: ValueType.INT
439
+ }
440
+ );
441
+ channelMemoryRecallDurationHistogram = meter.createHistogram(
442
+ CHANNEL_MEMORY_RECALL_DURATION,
443
+ {
444
+ description: "Duration of channel memory recall attempts.",
445
+ unit: "ms",
446
+ valueType: ValueType.DOUBLE,
447
+ advice: {
448
+ explicitBucketBoundaries: [0.1, 0.5, 1, 2, 5, 10, 25, 50, 100, 250]
449
+ }
450
+ }
451
+ );
452
+ channelMemoryRecallSelectedCountHistogram = meter.createHistogram(
453
+ CHANNEL_MEMORY_RECALL_SELECTED_COUNT,
454
+ {
455
+ description: "Number of channel memory entries selected per attempt.",
456
+ valueType: ValueType.INT
457
+ }
458
+ );
459
+ memoryRecallDeliveryCounter = meter.createCounter(
460
+ MEMORY_RECALL_DELIVERY_COUNT,
461
+ {
462
+ description: "Counts auto-memory recall delivery outcomes, tagged by phase and delivery point.",
463
+ valueType: ValueType.INT
464
+ }
465
+ );
466
+ memoryRecallDeliveryLatencyHistogram = meter.createHistogram(
467
+ MEMORY_RECALL_DELIVERY_LATENCY,
468
+ {
469
+ description: "Latency from auto-memory recall prefetch start to delivery or discard.",
470
+ unit: "ms",
471
+ valueType: ValueType.INT
472
+ }
473
+ );
474
+ initializePerformanceMonitoring(config);
475
+ isMetricsInitialized = true;
476
+ }
477
+ __name(initializeMetrics, "initializeMetrics");
478
+ function recordChatCompressionMetrics(config, attributes) {
479
+ if (!chatCompressionCounter || !isMetricsInitialized) return;
480
+ chatCompressionCounter.add(1, {
481
+ ...baseMetricDefinition.getCommonAttributes(config),
482
+ ...attributes
483
+ });
484
+ }
485
+ __name(recordChatCompressionMetrics, "recordChatCompressionMetrics");
486
+ function recordToolCallMetrics(config, durationMs, attributes) {
487
+ if (!toolCallCounter || !toolCallLatencyHistogram || !isMetricsInitialized)
488
+ return;
489
+ const metricAttributes = {
490
+ ...baseMetricDefinition.getCommonAttributes(config),
491
+ ...attributes
492
+ };
493
+ toolCallCounter.add(1, metricAttributes);
494
+ toolCallLatencyHistogram.record(durationMs, {
495
+ ...baseMetricDefinition.getCommonAttributes(config),
496
+ function_name: attributes.function_name
497
+ });
498
+ }
499
+ __name(recordToolCallMetrics, "recordToolCallMetrics");
500
+ function recordTokenUsageMetrics(config, tokenCount, attributes) {
501
+ if (!tokenUsageCounter || !isMetricsInitialized) return;
502
+ tokenUsageCounter.add(tokenCount, {
503
+ ...baseMetricDefinition.getCommonAttributes(config),
504
+ ...attributes
505
+ });
506
+ }
507
+ __name(recordTokenUsageMetrics, "recordTokenUsageMetrics");
508
+ function recordApiResponseMetrics(config, durationMs, attributes) {
509
+ if (!apiRequestCounter || !apiRequestLatencyHistogram || !isMetricsInitialized)
510
+ return;
511
+ const metricAttributes = {
512
+ ...baseMetricDefinition.getCommonAttributes(config),
513
+ model: attributes.model,
514
+ status_code: attributes.status_code ?? "ok"
515
+ };
516
+ apiRequestCounter.add(1, metricAttributes);
517
+ apiRequestLatencyHistogram.record(durationMs, {
518
+ ...baseMetricDefinition.getCommonAttributes(config),
519
+ model: attributes.model
520
+ });
521
+ }
522
+ __name(recordApiResponseMetrics, "recordApiResponseMetrics");
523
+ function recordApiErrorMetrics(config, durationMs, attributes) {
524
+ if (!apiRequestCounter || !apiRequestLatencyHistogram || !isMetricsInitialized)
525
+ return;
526
+ const metricAttributes = {
527
+ ...baseMetricDefinition.getCommonAttributes(config),
528
+ model: attributes.model,
529
+ status_code: attributes.status_code ?? "error",
530
+ error_type: attributes.error_type ?? "unknown"
531
+ };
532
+ apiRequestCounter.add(1, metricAttributes);
533
+ apiRequestLatencyHistogram.record(durationMs, {
534
+ ...baseMetricDefinition.getCommonAttributes(config),
535
+ model: attributes.model
536
+ });
537
+ }
538
+ __name(recordApiErrorMetrics, "recordApiErrorMetrics");
539
+ function recordFileOperationMetric(config, attributes) {
540
+ if (!fileOperationCounter || !isMetricsInitialized) return;
541
+ fileOperationCounter.add(1, {
542
+ ...baseMetricDefinition.getCommonAttributes(config),
543
+ ...attributes
544
+ });
545
+ }
546
+ __name(recordFileOperationMetric, "recordFileOperationMetric");
547
+ function recordInvalidChunk(config) {
548
+ if (!invalidChunkCounter || !isMetricsInitialized) return;
549
+ invalidChunkCounter.add(1, baseMetricDefinition.getCommonAttributes(config));
550
+ }
551
+ __name(recordInvalidChunk, "recordInvalidChunk");
552
+ function recordContentRetry(config) {
553
+ if (!contentRetryCounter || !isMetricsInitialized) return;
554
+ contentRetryCounter.add(1, baseMetricDefinition.getCommonAttributes(config));
555
+ }
556
+ __name(recordContentRetry, "recordContentRetry");
557
+ function recordContentRetryFailure(config) {
558
+ if (!contentRetryFailureCounter || !isMetricsInitialized) return;
559
+ contentRetryFailureCounter.add(
560
+ 1,
561
+ baseMetricDefinition.getCommonAttributes(config)
562
+ );
563
+ }
564
+ __name(recordContentRetryFailure, "recordContentRetryFailure");
565
+ function recordApiRetry(config, attributes) {
566
+ if (!apiRetryCounter || !isMetricsInitialized) return;
567
+ apiRetryCounter.add(1, {
568
+ ...baseMetricDefinition.getCommonAttributes(config),
569
+ ...attributes
570
+ });
571
+ }
572
+ __name(recordApiRetry, "recordApiRetry");
573
+ function recordModelSlashCommand(config, event) {
574
+ if (!modelSlashCommandCallCounter || !isMetricsInitialized) return;
575
+ modelSlashCommandCallCounter.add(1, {
576
+ ...baseMetricDefinition.getCommonAttributes(config),
577
+ "slash_command.model.model_name": event.model_name
578
+ });
579
+ }
580
+ __name(recordModelSlashCommand, "recordModelSlashCommand");
581
+ function initializePerformanceMonitoring(config) {
582
+ const meter = getMeter();
583
+ if (!meter) return;
584
+ isPerformanceMonitoringEnabled = config.getTelemetryEnabled();
585
+ if (!isPerformanceMonitoringEnabled) return;
586
+ Object.entries(PERFORMANCE_COUNTER_DEFINITIONS).forEach(
587
+ ([name, { description, valueType, assign }]) => {
588
+ assign(meter.createCounter(name, { description, valueType }));
589
+ }
590
+ );
591
+ Object.entries(PERFORMANCE_HISTOGRAM_DEFINITIONS).forEach(
592
+ ([name, { description, unit, valueType, assign }]) => {
593
+ assign(meter.createHistogram(name, { description, unit, valueType }));
594
+ }
595
+ );
596
+ }
597
+ __name(initializePerformanceMonitoring, "initializePerformanceMonitoring");
598
+ function recordStartupPerformance(config, durationMs, attributes) {
599
+ if (!startupTimeHistogram || !isPerformanceMonitoringEnabled) return;
600
+ const metricAttributes = {
601
+ ...baseMetricDefinition.getCommonAttributes(config),
602
+ phase: attributes.phase,
603
+ ...attributes.details
604
+ };
605
+ startupTimeHistogram.record(durationMs, metricAttributes);
606
+ }
607
+ __name(recordStartupPerformance, "recordStartupPerformance");
608
+ function recordMemoryUsage(config, bytes, attributes) {
609
+ if (!memoryUsageGauge || !isPerformanceMonitoringEnabled) return;
610
+ const metricAttributes = {
611
+ ...baseMetricDefinition.getCommonAttributes(config),
612
+ ...attributes
613
+ };
614
+ memoryUsageGauge.record(bytes, metricAttributes);
615
+ }
616
+ __name(recordMemoryUsage, "recordMemoryUsage");
617
+ function recordCpuUsage(config, percentage, attributes) {
618
+ if (!cpuUsageGauge || !isPerformanceMonitoringEnabled) return;
619
+ const metricAttributes = {
620
+ ...baseMetricDefinition.getCommonAttributes(config),
621
+ ...attributes
622
+ };
623
+ cpuUsageGauge.record(percentage, metricAttributes);
624
+ }
625
+ __name(recordCpuUsage, "recordCpuUsage");
626
+ function recordToolQueueDepth(config, queueDepth) {
627
+ if (!toolQueueDepthGauge || !isPerformanceMonitoringEnabled) return;
628
+ const attributes = {
629
+ ...baseMetricDefinition.getCommonAttributes(config)
630
+ };
631
+ toolQueueDepthGauge.record(queueDepth, attributes);
632
+ }
633
+ __name(recordToolQueueDepth, "recordToolQueueDepth");
634
+ function recordToolExecutionBreakdown(config, durationMs, attributes) {
635
+ if (!toolExecutionBreakdownHistogram || !isPerformanceMonitoringEnabled)
636
+ return;
637
+ const metricAttributes = {
638
+ ...baseMetricDefinition.getCommonAttributes(config),
639
+ ...attributes
640
+ };
641
+ toolExecutionBreakdownHistogram.record(durationMs, metricAttributes);
642
+ }
643
+ __name(recordToolExecutionBreakdown, "recordToolExecutionBreakdown");
644
+ function recordTokenEfficiency(config, value, attributes) {
645
+ if (!tokenEfficiencyHistogram || !isPerformanceMonitoringEnabled) return;
646
+ const metricAttributes = {
647
+ ...baseMetricDefinition.getCommonAttributes(config),
648
+ ...attributes
649
+ };
650
+ tokenEfficiencyHistogram.record(value, metricAttributes);
651
+ }
652
+ __name(recordTokenEfficiency, "recordTokenEfficiency");
653
+ function recordApiRequestBreakdown(config, durationMs, attributes) {
654
+ if (!apiRequestBreakdownHistogram || !isPerformanceMonitoringEnabled) return;
655
+ const metricAttributes = {
656
+ ...baseMetricDefinition.getCommonAttributes(config),
657
+ ...attributes
658
+ };
659
+ apiRequestBreakdownHistogram.record(durationMs, metricAttributes);
660
+ }
661
+ __name(recordApiRequestBreakdown, "recordApiRequestBreakdown");
662
+ function recordPerformanceScore(config, score, attributes) {
663
+ if (!performanceScoreGauge || !isPerformanceMonitoringEnabled) return;
664
+ const metricAttributes = {
665
+ ...baseMetricDefinition.getCommonAttributes(config),
666
+ ...attributes
667
+ };
668
+ performanceScoreGauge.record(score, metricAttributes);
669
+ }
670
+ __name(recordPerformanceScore, "recordPerformanceScore");
671
+ function recordPerformanceRegression(config, attributes) {
672
+ if (!regressionDetectionCounter || !isPerformanceMonitoringEnabled) return;
673
+ const metricAttributes = {
674
+ ...baseMetricDefinition.getCommonAttributes(config),
675
+ ...attributes
676
+ };
677
+ regressionDetectionCounter.add(1, metricAttributes);
678
+ if (attributes.baseline_value !== 0 && regressionPercentageChangeHistogram) {
679
+ const percentageChange = (attributes.current_value - attributes.baseline_value) / attributes.baseline_value * 100;
680
+ regressionPercentageChangeHistogram.record(
681
+ percentageChange,
682
+ metricAttributes
683
+ );
684
+ }
685
+ }
686
+ __name(recordPerformanceRegression, "recordPerformanceRegression");
687
+ function recordBaselineComparison(config, attributes) {
688
+ if (!baselineComparisonHistogram || !isPerformanceMonitoringEnabled) return;
689
+ if (attributes.baseline_value === 0) {
690
+ diag.warn("Baseline value is zero, skipping comparison.");
691
+ return;
692
+ }
693
+ const percentageChange = (attributes.current_value - attributes.baseline_value) / attributes.baseline_value * 100;
694
+ const metricAttributes = {
695
+ ...baseMetricDefinition.getCommonAttributes(config),
696
+ ...attributes
697
+ };
698
+ baselineComparisonHistogram.record(percentageChange, metricAttributes);
699
+ }
700
+ __name(recordBaselineComparison, "recordBaselineComparison");
701
+ function isPerformanceMonitoringActive() {
702
+ return isPerformanceMonitoringEnabled && isMetricsInitialized;
703
+ }
704
+ __name(isPerformanceMonitoringActive, "isPerformanceMonitoringActive");
705
+ function recordSubagentExecutionMetrics(config, subagentName, status, terminateReason) {
706
+ if (!subagentExecutionCounter || !isMetricsInitialized) return;
707
+ const attributes = {
708
+ ...baseMetricDefinition.getCommonAttributes(config),
709
+ subagent_name: subagentName,
710
+ status
711
+ };
712
+ if (terminateReason) {
713
+ attributes["terminate_reason"] = terminateReason;
714
+ }
715
+ subagentExecutionCounter.add(1, attributes);
716
+ }
717
+ __name(recordSubagentExecutionMetrics, "recordSubagentExecutionMetrics");
718
+ function recordArenaSessionStartedMetrics(config) {
719
+ if (!isMetricsInitialized) return;
720
+ arenaSessionCounter?.add(1, {
721
+ ...baseMetricDefinition.getCommonAttributes(config),
722
+ status: "started"
723
+ });
724
+ }
725
+ __name(recordArenaSessionStartedMetrics, "recordArenaSessionStartedMetrics");
726
+ function recordArenaAgentCompletedMetrics(config, modelId, status, durationMs, inputTokens, outputTokens) {
727
+ if (!isMetricsInitialized) return;
728
+ const common = baseMetricDefinition.getCommonAttributes(config);
729
+ arenaAgentCounter?.add(1, {
730
+ ...common,
731
+ status,
732
+ model_id: modelId
733
+ });
734
+ arenaAgentDurationHistogram?.record(durationMs, {
735
+ ...common,
736
+ model_id: modelId
737
+ });
738
+ if (inputTokens > 0) {
739
+ arenaAgentTokensCounter?.add(inputTokens, {
740
+ ...common,
741
+ model_id: modelId,
742
+ type: "input"
743
+ });
744
+ }
745
+ if (outputTokens > 0) {
746
+ arenaAgentTokensCounter?.add(outputTokens, {
747
+ ...common,
748
+ model_id: modelId,
749
+ type: "output"
750
+ });
751
+ }
752
+ }
753
+ __name(recordArenaAgentCompletedMetrics, "recordArenaAgentCompletedMetrics");
754
+ function recordArenaSessionEndedMetrics(config, status, displayBackend, durationMs, winnerModelId) {
755
+ if (!isMetricsInitialized) return;
756
+ const common = baseMetricDefinition.getCommonAttributes(config);
757
+ arenaSessionCounter?.add(1, {
758
+ ...common,
759
+ status,
760
+ ...displayBackend ? { display_backend: displayBackend } : {}
761
+ });
762
+ if (durationMs !== void 0 && arenaSessionDurationHistogram) {
763
+ arenaSessionDurationHistogram.record(durationMs, {
764
+ ...common,
765
+ status
766
+ });
767
+ }
768
+ if (winnerModelId) {
769
+ arenaResultSelectedCounter?.add(1, {
770
+ ...common,
771
+ model_id: winnerModelId
772
+ });
773
+ }
774
+ }
775
+ __name(recordArenaSessionEndedMetrics, "recordArenaSessionEndedMetrics");
776
+ function recordMemoryExtractMetrics(config, durationMs, attrs) {
777
+ if (!isMetricsInitialized) return;
778
+ const common = baseMetricDefinition.getCommonAttributes(config);
779
+ memoryExtractCounter?.add(1, {
780
+ ...common,
781
+ trigger: attrs.trigger,
782
+ status: attrs.status
783
+ });
784
+ memoryExtractDurationHistogram?.record(durationMs, {
785
+ ...common,
786
+ trigger: attrs.trigger,
787
+ status: attrs.status
788
+ });
789
+ }
790
+ __name(recordMemoryExtractMetrics, "recordMemoryExtractMetrics");
791
+ function recordMemoryDreamMetrics(config, durationMs, attrs) {
792
+ if (!isMetricsInitialized) return;
793
+ const common = baseMetricDefinition.getCommonAttributes(config);
794
+ memoryDreamCounter?.add(1, {
795
+ ...common,
796
+ trigger: attrs.trigger,
797
+ status: attrs.status
798
+ });
799
+ memoryDreamDurationHistogram?.record(durationMs, {
800
+ ...common,
801
+ trigger: attrs.trigger,
802
+ status: attrs.status
803
+ });
804
+ }
805
+ __name(recordMemoryDreamMetrics, "recordMemoryDreamMetrics");
806
+ function recordMemoryRecallMetrics(config, durationMs, attrs) {
807
+ if (!isMetricsInitialized) return;
808
+ const common = baseMetricDefinition.getCommonAttributes(config);
809
+ memoryRecallCounter?.add(1, { ...common, strategy: attrs.strategy });
810
+ memoryRecallDurationHistogram?.record(durationMs, {
811
+ ...common,
812
+ strategy: attrs.strategy
813
+ });
814
+ }
815
+ __name(recordMemoryRecallMetrics, "recordMemoryRecallMetrics");
816
+ function recordChannelMemoryRecallMetrics(observation) {
817
+ if (!isMetricsInitialized) return;
818
+ const attributes = {
819
+ cache: observation.cache,
820
+ result: observation.result
821
+ };
822
+ channelMemoryRecallCounter?.add(1, attributes);
823
+ channelMemoryRecallDurationHistogram?.record(
824
+ observation.durationMs,
825
+ attributes
826
+ );
827
+ channelMemoryRecallSelectedCountHistogram?.record(
828
+ observation.selectedCount,
829
+ attributes
830
+ );
831
+ }
832
+ __name(recordChannelMemoryRecallMetrics, "recordChannelMemoryRecallMetrics");
833
+ function recordMemoryRecallDeliveryMetrics(config, latencyMs, attrs) {
834
+ if (!isMetricsInitialized) return;
835
+ const common = baseMetricDefinition.getCommonAttributes(config);
836
+ const metricAttributes = {
837
+ ...common,
838
+ phase: attrs.phase,
839
+ delivery_point: attrs.delivery_point,
840
+ strategy: attrs.strategy,
841
+ ...attrs.discard_reason ? { discard_reason: attrs.discard_reason } : {}
842
+ };
843
+ memoryRecallDeliveryCounter?.add(1, metricAttributes);
844
+ memoryRecallDeliveryLatencyHistogram?.record(latencyMs, metricAttributes);
845
+ }
846
+ __name(recordMemoryRecallDeliveryMetrics, "recordMemoryRecallDeliveryMetrics");
847
+
848
+ // packages/core/src/telemetry/detailed-span-attributes.ts
849
+ init_esbuild_shims();
850
+ import { createHash as createHash2 } from "node:crypto";
851
+
852
+ // packages/core/src/telemetry/sdk.ts
853
+ init_esbuild_shims();
854
+ init_esm();
855
+
856
+ // packages/core/src/telemetry/tracer.ts
857
+ init_esbuild_shims();
858
+ init_esm();
859
+
860
+ // packages/core/src/telemetry/trace-id-utils.ts
861
+ init_esbuild_shims();
862
+ import { createHash } from "node:crypto";
863
+ function deriveTraceId(sessionId) {
864
+ return createHash("sha256").update(sessionId).digest("hex").slice(0, 32);
865
+ }
866
+ __name(deriveTraceId, "deriveTraceId");
867
+ function randomSpanId() {
868
+ const bytes = new Uint8Array(8);
869
+ crypto.getRandomValues(bytes);
870
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
871
+ }
872
+ __name(randomSpanId, "randomSpanId");
873
+ function randomHexString(length) {
874
+ const bytes = new Uint8Array(Math.ceil(length / 2));
875
+ crypto.getRandomValues(bytes);
876
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("").slice(0, length);
877
+ }
878
+ __name(randomHexString, "randomHexString");
879
+
880
+ // packages/core/src/telemetry/tracer.ts
881
+ var tracer = trace.getTracer(SERVICE_NAME);
882
+ var debugLogger = createDebugLogger("OTEL_TRACER");
883
+ var TELEMETRY_WARNING_INTERVAL_MS = 3e4;
884
+ var API_CALL_FAILED_SPAN_STATUS_MESSAGE = "API call failed";
885
+ var API_CALL_ABORTED_SPAN_STATUS_MESSAGE = "API call aborted";
886
+ var lastTelemetryWarningMs;
887
+ var suppressedTelemetryWarnings = 0;
888
+ function warnTelemetryOperationFailed(operation, error) {
889
+ const now = Date.now();
890
+ if (lastTelemetryWarningMs !== void 0 && now - lastTelemetryWarningMs < TELEMETRY_WARNING_INTERVAL_MS) {
891
+ suppressedTelemetryWarnings += 1;
892
+ return;
893
+ }
894
+ const suppressedSuffix = suppressedTelemetryWarnings > 0 ? `; suppressed ${suppressedTelemetryWarnings} similar warning(s)` : "";
895
+ suppressedTelemetryWarnings = 0;
896
+ lastTelemetryWarningMs = now;
897
+ try {
898
+ debugLogger.warn(
899
+ `OTel span ${operation} failed: ${error instanceof Error ? error.message : String(error)}${suppressedSuffix}`
900
+ );
901
+ } catch {
902
+ }
903
+ }
904
+ __name(warnTelemetryOperationFailed, "warnTelemetryOperationFailed");
905
+ function safeSetStatus(span, status) {
906
+ try {
907
+ span.setStatus(status);
908
+ } catch (error) {
909
+ warnTelemetryOperationFailed("setStatus", error);
910
+ }
911
+ }
912
+ __name(safeSetStatus, "safeSetStatus");
913
+ function shouldForceSampled() {
914
+ const sampler = process.env["OTEL_TRACES_SAMPLER"]?.trim().toLowerCase() ?? "";
915
+ if (!sampler || sampler.startsWith("parentbased_")) {
916
+ if (sampler.includes("always_off")) return false;
917
+ return true;
918
+ }
919
+ return sampler === "always_on";
920
+ }
921
+ __name(shouldForceSampled, "shouldForceSampled");
922
+ function createSessionRootContext(sessionId) {
923
+ const traceId = deriveTraceId(sessionId);
924
+ const spanId = randomSpanId();
925
+ const rootSpan = trace.wrapSpanContext({
926
+ traceId,
927
+ spanId,
928
+ traceFlags: shouldForceSampled() ? TraceFlags.SAMPLED : TraceFlags.NONE,
929
+ isRemote: false
930
+ });
931
+ return trace.setSpan(ROOT_CONTEXT, rootSpan);
932
+ }
933
+ __name(createSessionRootContext, "createSessionRootContext");
934
+
935
+ // packages/core/src/telemetry/session-tracing.ts
936
+ init_esbuild_shims();
937
+ init_esm();
938
+ import { AsyncLocalStorage } from "node:async_hooks";
939
+ var debugLogger2 = createDebugLogger("SESSION_TRACING");
940
+ function resolveParentContext(parent) {
941
+ if (parent) {
942
+ return trace.setSpan(context.active(), parent.span);
943
+ }
944
+ return context.active();
945
+ }
946
+ __name(resolveParentContext, "resolveParentContext");
947
+ var NOOP_SPAN = trace.wrapSpanContext({
948
+ traceId: "0".repeat(32),
949
+ spanId: "0".repeat(16),
950
+ traceFlags: 0
951
+ });
952
+ var interactionContext = new AsyncLocalStorage();
953
+ var toolContext = new AsyncLocalStorage();
954
+ var subagentContext = new AsyncLocalStorage();
955
+ function isInNativeSubagentSpan() {
956
+ const ctx = subagentContext.getStore();
957
+ return ctx !== void 0 && !ctx.ended;
958
+ }
959
+ __name(isInNativeSubagentSpan, "isInNativeSubagentSpan");
960
+ function resolveSessionId(parentCtx) {
961
+ const fromParent = parentCtx?.attributes?.["session.id"];
962
+ return typeof fromParent === "string" && fromParent ? fromParent : getCurrentSessionId();
963
+ }
964
+ __name(resolveSessionId, "resolveSessionId");
965
+ var activeSpans = /* @__PURE__ */ new Map();
966
+ var strongSpans = /* @__PURE__ */ new Map();
967
+ var interactionSequence = 0;
968
+ var lastInteractionCtx;
969
+ var cleanupIntervalStarted = false;
970
+ var SPAN_TTL_MS_DEFAULT = 30 * 60 * 1e3;
971
+ var SPAN_TTL_MS_LONG = 4 * 60 * 60 * 1e3;
972
+ var LONG_TTL_SUBAGENT_KINDS = /* @__PURE__ */ new Set([
973
+ "fork",
974
+ "background"
975
+ ]);
976
+ function ttlFor(ctx) {
977
+ if (ctx.type === "subagent") {
978
+ const kind = ctx.attributes["qwen-code.subagent.invocation_kind"];
979
+ if (typeof kind === "string" && LONG_TTL_SUBAGENT_KINDS.has(kind)) {
980
+ return SPAN_TTL_MS_LONG;
981
+ }
982
+ }
983
+ return SPAN_TTL_MS_DEFAULT;
984
+ }
985
+ __name(ttlFor, "ttlFor");
986
+ function sweepStaleSpans(now) {
987
+ for (const [spanId, weakRef] of activeSpans) {
988
+ const ctx = weakRef.deref();
989
+ if (ctx === void 0) {
990
+ activeSpans.delete(spanId);
991
+ strongSpans.delete(spanId);
992
+ continue;
993
+ }
994
+ if (now - ctx.startTime < ttlFor(ctx)) continue;
995
+ if (!ctx.ended) {
996
+ ctx.ended = true;
997
+ const ageMs = now - ctx.startTime;
998
+ const toolName = ctx.attributes["tool.name"];
999
+ const callId = ctx.attributes["tool.call_id"];
1000
+ try {
1001
+ ctx.span.setAttributes({
1002
+ "qwen-code.span.ttl_expired": true,
1003
+ "qwen-code.span.duration_ms": ageMs,
1004
+ ...ctx.type === "tool.blocked_on_user" ? {
1005
+ decision: "aborted",
1006
+ source: "system"
1007
+ } : {},
1008
+ ...ctx.type === "subagent" ? {
1009
+ "qwen-code.subagent.status": "aborted",
1010
+ "qwen-code.subagent.terminate_reason": "ttl_swept",
1011
+ // Mirror the subagent-specific duration_ms key that
1012
+ // endSubagentSpan stamps so dashboards querying that
1013
+ // namespace see TTL-swept spans too (they currently
1014
+ // only get the generic qwen-code.span.duration_ms
1015
+ // above). wenshao @ #4410.
1016
+ "qwen-code.subagent.duration_ms": ageMs
1017
+ } : {}
1018
+ });
1019
+ } catch (error) {
1020
+ debugLogger2.warn(
1021
+ `Failed to stamp TTL attrs on stale span ${spanId}: ${error instanceof Error ? error.message : String(error)}`
1022
+ );
1023
+ }
1024
+ const ctxLabel = toolName && callId ? `${ctx.type} (tool.name=${toolName}, tool.call_id=${callId})` : ctx.type;
1025
+ debugLogger2.warn(
1026
+ `Stale ${ctxLabel} span ended by TTL safety net (age=${ageMs}ms, spanId=${spanId})`
1027
+ );
1028
+ try {
1029
+ ctx.span.end();
1030
+ } catch (error) {
1031
+ debugLogger2.warn(
1032
+ `Failed to end stale span ${spanId}: ${error instanceof Error ? error.message : String(error)}`
1033
+ );
1034
+ }
1035
+ }
1036
+ activeSpans.delete(spanId);
1037
+ strongSpans.delete(spanId);
1038
+ }
1039
+ }
1040
+ __name(sweepStaleSpans, "sweepStaleSpans");
1041
+ function ensureCleanupInterval() {
1042
+ if (cleanupIntervalStarted) return;
1043
+ cleanupIntervalStarted = true;
1044
+ const interval = setInterval(() => sweepStaleSpans(Date.now()), 6e4);
1045
+ if (typeof interval.unref === "function") {
1046
+ interval.unref();
1047
+ }
1048
+ }
1049
+ __name(ensureCleanupInterval, "ensureCleanupInterval");
1050
+ function getSpanId(span) {
1051
+ return span.spanContext().spanId || "";
1052
+ }
1053
+ __name(getSpanId, "getSpanId");
1054
+ var SPAN_ERROR_MAX_CHARS = 1024;
1055
+ function truncateSpanError(s) {
1056
+ if (s.length <= SPAN_ERROR_MAX_CHARS) return s;
1057
+ let end = SPAN_ERROR_MAX_CHARS;
1058
+ const code = s.charCodeAt(end - 1);
1059
+ if (code >= 55296 && code <= 56319) end--;
1060
+ return s.slice(0, end) + "\u2026[truncated]";
1061
+ }
1062
+ __name(truncateSpanError, "truncateSpanError");
1063
+ function getTracer() {
1064
+ return trace.getTracer(SERVICE_NAME, "1.0.0");
1065
+ }
1066
+ __name(getTracer, "getTracer");
1067
+ function startInteractionSpan(config, options) {
1068
+ if (!isTelemetrySdkInitialized()) return;
1069
+ ensureCleanupInterval();
1070
+ interactionSequence++;
1071
+ const attributes = {
1072
+ "session.id": config.getSessionId(),
1073
+ "qwen-code.prompt_id": options.promptId,
1074
+ "qwen-code.message_type": options.messageType,
1075
+ "qwen-code.model": options.model,
1076
+ "qwen-code.approval_mode": config.getApprovalMode(),
1077
+ "interaction.sequence": interactionSequence
1078
+ };
1079
+ const span = getTracer().startSpan(
1080
+ SPAN_INTERACTION,
1081
+ { kind: SpanKind.INTERNAL, attributes },
1082
+ ROOT_CONTEXT
1083
+ );
1084
+ const spanId = getSpanId(span);
1085
+ const spanContextObj = {
1086
+ span,
1087
+ startTime: Date.now(),
1088
+ attributes,
1089
+ type: "interaction"
1090
+ };
1091
+ activeSpans.set(spanId, new WeakRef(spanContextObj));
1092
+ strongSpans.set(spanId, spanContextObj);
1093
+ lastInteractionCtx = spanContextObj;
1094
+ interactionContext.enterWith(spanContextObj);
1095
+ }
1096
+ __name(startInteractionSpan, "startInteractionSpan");
1097
+ function endInteractionSpan(status, metadata) {
1098
+ const spanCtx = interactionContext.getStore() ?? lastInteractionCtx;
1099
+ if (!spanCtx) return;
1100
+ if (spanCtx.ended) {
1101
+ debugLogger2.debug(
1102
+ `endInteractionSpan: span ${getSpanId(spanCtx.span)} already ended (possible TTL sweep race)`
1103
+ );
1104
+ return;
1105
+ }
1106
+ spanCtx.ended = true;
1107
+ lastInteractionCtx = void 0;
1108
+ const duration = Date.now() - spanCtx.startTime;
1109
+ spanCtx.span.setAttributes({
1110
+ "interaction.duration_ms": duration,
1111
+ "qwen-code.turn_status": status
1112
+ });
1113
+ if (status === "error") {
1114
+ spanCtx.span.setStatus({
1115
+ code: SpanStatusCode.ERROR,
1116
+ message: metadata?.errorMessage ?? "unknown error"
1117
+ });
1118
+ } else {
1119
+ spanCtx.span.setStatus({ code: SpanStatusCode.OK });
1120
+ }
1121
+ spanCtx.span.end();
1122
+ const spanId = getSpanId(spanCtx.span);
1123
+ activeSpans.delete(spanId);
1124
+ strongSpans.delete(spanId);
1125
+ interactionContext.enterWith(void 0);
1126
+ }
1127
+ __name(endInteractionSpan, "endInteractionSpan");
1128
+ async function withInteractionSpan(config, options, fn, getResultStatus) {
1129
+ if (!isTelemetrySdkInitialized()) return await fn();
1130
+ ensureCleanupInterval();
1131
+ interactionSequence++;
1132
+ const attributes = {
1133
+ "session.id": config.getSessionId(),
1134
+ "qwen-code.prompt_id": options.promptId,
1135
+ "qwen-code.message_type": options.messageType,
1136
+ "qwen-code.model": options.model,
1137
+ "qwen-code.approval_mode": config.getApprovalMode(),
1138
+ "interaction.sequence": interactionSequence
1139
+ };
1140
+ const parentContext = options.parentContext ?? ROOT_CONTEXT;
1141
+ const span = getTracer().startSpan(
1142
+ SPAN_INTERACTION,
1143
+ {
1144
+ kind: SpanKind.INTERNAL,
1145
+ attributes
1146
+ },
1147
+ parentContext
1148
+ );
1149
+ const spanId = getSpanId(span);
1150
+ const spanContextObj = {
1151
+ span,
1152
+ startTime: Date.now(),
1153
+ attributes,
1154
+ type: "interaction"
1155
+ };
1156
+ activeSpans.set(spanId, new WeakRef(spanContextObj));
1157
+ strongSpans.set(spanId, spanContextObj);
1158
+ const activeContext = trace.setSpan(parentContext, span);
1159
+ return await context.with(
1160
+ activeContext,
1161
+ async () => interactionContext.run(spanContextObj, async () => {
1162
+ let terminalStatus = "ok";
1163
+ let errorStatusSet = false;
1164
+ try {
1165
+ const result = await fn();
1166
+ terminalStatus = getResultStatus?.(result) ?? "ok";
1167
+ return result;
1168
+ } catch (error) {
1169
+ terminalStatus = "error";
1170
+ span.setStatus({
1171
+ code: SpanStatusCode.ERROR,
1172
+ message: truncateSpanError(
1173
+ error instanceof Error ? error.message : String(error)
1174
+ )
1175
+ });
1176
+ errorStatusSet = true;
1177
+ throw error;
1178
+ } finally {
1179
+ if (!spanContextObj.ended) {
1180
+ spanContextObj.ended = true;
1181
+ const duration = Date.now() - spanContextObj.startTime;
1182
+ span.setAttributes({
1183
+ "interaction.duration_ms": duration,
1184
+ "qwen-code.turn_status": terminalStatus
1185
+ });
1186
+ if (terminalStatus === "ok") {
1187
+ span.setStatus({ code: SpanStatusCode.OK });
1188
+ } else if (terminalStatus === "error" && !errorStatusSet) {
1189
+ span.setStatus({
1190
+ code: SpanStatusCode.ERROR,
1191
+ message: "interaction error"
1192
+ });
1193
+ }
1194
+ span.end();
1195
+ activeSpans.delete(spanId);
1196
+ strongSpans.delete(spanId);
1197
+ }
1198
+ }
1199
+ })
1200
+ );
1201
+ }
1202
+ __name(withInteractionSpan, "withInteractionSpan");
1203
+ function startLLMRequestSpan(model, promptId) {
1204
+ if (!isTelemetrySdkInitialized()) {
1205
+ return NOOP_SPAN;
1206
+ }
1207
+ const parentCtx = subagentContext.getStore() ?? interactionContext.getStore();
1208
+ const ctx = resolveParentContext(parentCtx);
1209
+ const sessionId = resolveSessionId(parentCtx);
1210
+ const attributes = {
1211
+ ...sessionId ? { "session.id": sessionId } : {},
1212
+ "qwen-code.model": model,
1213
+ "qwen-code.prompt_id": promptId,
1214
+ "llm_request.context": subagentContext.getStore() ? "subagent" : interactionContext.getStore() ? "interaction" : "standalone",
1215
+ // Dual-emit OTel GenAI semantic convention (Stable). Private name
1216
+ // (qwen-code.model) remains authoritative; gen_ai.* is a compat layer
1217
+ // for spec-aware backends. See docs/design/telemetry-llm-request-timing-design.md (D8).
1218
+ "gen_ai.request.model": model
1219
+ };
1220
+ const span = getTracer().startSpan(
1221
+ SPAN_LLM_REQUEST,
1222
+ { kind: SpanKind.INTERNAL, attributes },
1223
+ ctx
1224
+ );
1225
+ const spanId = getSpanId(span);
1226
+ const spanContextObj = {
1227
+ span,
1228
+ startTime: Date.now(),
1229
+ attributes,
1230
+ type: "llm_request"
1231
+ };
1232
+ activeSpans.set(spanId, new WeakRef(spanContextObj));
1233
+ strongSpans.set(spanId, spanContextObj);
1234
+ return span;
1235
+ }
1236
+ __name(startLLMRequestSpan, "startLLMRequestSpan");
1237
+ function endLLMRequestSpan(span, metadata) {
1238
+ const spanId = getSpanId(span);
1239
+ const spanCtx = activeSpans.get(spanId)?.deref();
1240
+ if (!spanCtx) return;
1241
+ if (spanCtx.ended) {
1242
+ debugLogger2.debug(
1243
+ `endLLMRequestSpan: span ${spanId} already ended (possible TTL sweep race)`
1244
+ );
1245
+ return;
1246
+ }
1247
+ spanCtx.ended = true;
1248
+ try {
1249
+ const duration = metadata?.durationMs ?? Date.now() - spanCtx.startTime;
1250
+ const endAttributes = { duration_ms: duration };
1251
+ if (metadata) {
1252
+ if (metadata.inputTokens !== void 0) {
1253
+ endAttributes["input_tokens"] = metadata.inputTokens;
1254
+ endAttributes["gen_ai.usage.input_tokens"] = metadata.inputTokens;
1255
+ }
1256
+ if (metadata.outputTokens !== void 0) {
1257
+ endAttributes["output_tokens"] = metadata.outputTokens;
1258
+ endAttributes["gen_ai.usage.output_tokens"] = metadata.outputTokens;
1259
+ }
1260
+ if (metadata.cachedInputTokens !== void 0) {
1261
+ endAttributes["cached_input_tokens"] = metadata.cachedInputTokens;
1262
+ endAttributes["gen_ai.usage.cached_tokens"] = metadata.cachedInputTokens;
1263
+ }
1264
+ if (metadata.ttftMs !== void 0) {
1265
+ endAttributes["ttft_ms"] = metadata.ttftMs;
1266
+ endAttributes["gen_ai.server.time_to_first_token"] = metadata.ttftMs / 1e3;
1267
+ }
1268
+ if (metadata.requestSetupMs !== void 0) {
1269
+ endAttributes["request_setup_ms"] = metadata.requestSetupMs;
1270
+ }
1271
+ if (metadata.attempt !== void 0) {
1272
+ endAttributes["attempt"] = metadata.attempt;
1273
+ }
1274
+ if (metadata.retryTotalDelayMs !== void 0) {
1275
+ endAttributes["retry_total_delay_ms"] = metadata.retryTotalDelayMs;
1276
+ }
1277
+ if (metadata.ttftMs !== void 0) {
1278
+ const samplingMs = Math.max(0, duration - metadata.ttftMs);
1279
+ endAttributes["sampling_ms"] = samplingMs;
1280
+ if (samplingMs > 0 && metadata.outputTokens !== void 0) {
1281
+ endAttributes["output_tokens_per_second"] = Math.round(metadata.outputTokens / (samplingMs / 1e3) * 100) / 100;
1282
+ }
1283
+ }
1284
+ endAttributes["success"] = metadata.success;
1285
+ if (metadata.error !== void 0)
1286
+ endAttributes["error"] = truncateSpanError(metadata.error);
1287
+ if (metadata.responseId !== void 0) {
1288
+ endAttributes["response_id"] = metadata.responseId;
1289
+ endAttributes["gen_ai.response.id"] = metadata.responseId;
1290
+ }
1291
+ if (metadata.finishReason !== void 0) {
1292
+ endAttributes["finish_reason"] = metadata.finishReason;
1293
+ endAttributes["gen_ai.response.finish_reasons"] = [
1294
+ metadata.finishReason
1295
+ ];
1296
+ }
1297
+ if (metadata.thoughtsTokenCount !== void 0) {
1298
+ endAttributes["thoughts_token_count"] = metadata.thoughtsTokenCount;
1299
+ endAttributes["gen_ai.usage.reasoning_tokens"] = metadata.thoughtsTokenCount;
1300
+ }
1301
+ if (metadata.subagentName !== void 0) {
1302
+ endAttributes["subagent_name"] = metadata.subagentName;
1303
+ }
1304
+ if (metadata.errorType !== void 0) {
1305
+ endAttributes["error_type"] = metadata.errorType;
1306
+ endAttributes["error.type"] = metadata.errorType;
1307
+ }
1308
+ if (metadata.errorStatusCode !== void 0) {
1309
+ endAttributes["error_status_code"] = metadata.errorStatusCode;
1310
+ }
1311
+ }
1312
+ spanCtx.span.setAttributes(endAttributes);
1313
+ try {
1314
+ if (metadata?.config && metadata.success) {
1315
+ const model = String(spanCtx.attributes["qwen-code.model"] ?? "");
1316
+ if (metadata.requestSetupMs !== void 0) {
1317
+ recordApiRequestBreakdown(metadata.config, metadata.requestSetupMs, {
1318
+ model,
1319
+ phase: "request_preparation" /* REQUEST_PREPARATION */
1320
+ });
1321
+ }
1322
+ if (metadata.ttftMs !== void 0) {
1323
+ recordApiRequestBreakdown(metadata.config, metadata.ttftMs, {
1324
+ model,
1325
+ phase: "network_latency" /* NETWORK_LATENCY */
1326
+ });
1327
+ }
1328
+ const breakdownSamplingMs = metadata.ttftMs !== void 0 ? Math.max(0, duration - metadata.ttftMs) : void 0;
1329
+ if (breakdownSamplingMs !== void 0 && breakdownSamplingMs > 0) {
1330
+ recordApiRequestBreakdown(metadata.config, breakdownSamplingMs, {
1331
+ model,
1332
+ phase: "response_processing" /* RESPONSE_PROCESSING */
1333
+ });
1334
+ }
1335
+ }
1336
+ } catch (error) {
1337
+ debugLogger2.warn(
1338
+ `Failed to record API request breakdown histogram: ${error instanceof Error ? error.message : String(error)}`
1339
+ );
1340
+ }
1341
+ if (metadata === void 0 || metadata.success) {
1342
+ spanCtx.span.setStatus({ code: SpanStatusCode.OK });
1343
+ } else {
1344
+ spanCtx.span.setStatus({
1345
+ code: SpanStatusCode.ERROR,
1346
+ message: metadata.error ? truncateSpanError(metadata.error) : "unknown error"
1347
+ });
1348
+ }
1349
+ } catch (error) {
1350
+ debugLogger2.warn(
1351
+ `Failed to update LLM request span attributes/status: ${error instanceof Error ? error.message : String(error)}`
1352
+ );
1353
+ }
1354
+ try {
1355
+ spanCtx.span.end();
1356
+ } catch (error) {
1357
+ debugLogger2.warn(
1358
+ `Failed to end LLM request span: ${error instanceof Error ? error.message : String(error)}`
1359
+ );
1360
+ }
1361
+ activeSpans.delete(spanId);
1362
+ strongSpans.delete(spanId);
1363
+ }
1364
+ __name(endLLMRequestSpan, "endLLMRequestSpan");
1365
+ function startToolSpan(toolName, attrs) {
1366
+ if (!isTelemetrySdkInitialized()) {
1367
+ return NOOP_SPAN;
1368
+ }
1369
+ const parentCtx = subagentContext.getStore() ?? interactionContext.getStore();
1370
+ const ctx = resolveParentContext(parentCtx);
1371
+ const sessionId = resolveSessionId(parentCtx);
1372
+ const attributes = {
1373
+ ...sessionId ? { "session.id": sessionId } : {},
1374
+ "tool.name": toolName,
1375
+ ...attrs
1376
+ };
1377
+ const span = getTracer().startSpan(
1378
+ SPAN_TOOL,
1379
+ { kind: SpanKind.INTERNAL, attributes },
1380
+ ctx
1381
+ );
1382
+ const spanId = getSpanId(span);
1383
+ const spanContextObj = {
1384
+ span,
1385
+ startTime: Date.now(),
1386
+ attributes,
1387
+ type: "tool"
1388
+ };
1389
+ activeSpans.set(spanId, new WeakRef(spanContextObj));
1390
+ strongSpans.set(spanId, spanContextObj);
1391
+ return span;
1392
+ }
1393
+ __name(startToolSpan, "startToolSpan");
1394
+ function runInToolSpanContext(span, fn) {
1395
+ const spanId = getSpanId(span);
1396
+ const spanCtx = activeSpans.get(spanId)?.deref();
1397
+ if (!spanCtx) return fn();
1398
+ const otelCtxWithSpan = trace.setSpan(context.active(), span);
1399
+ return toolContext.run(spanCtx, () => context.with(otelCtxWithSpan, fn));
1400
+ }
1401
+ __name(runInToolSpanContext, "runInToolSpanContext");
1402
+ function endToolSpan(span, metadata) {
1403
+ const spanId = getSpanId(span);
1404
+ const spanCtx = activeSpans.get(spanId)?.deref();
1405
+ if (!spanCtx) return;
1406
+ if (spanCtx.ended) {
1407
+ debugLogger2.debug(
1408
+ `endToolSpan: span ${spanId} already ended (possible TTL sweep race)`
1409
+ );
1410
+ return;
1411
+ }
1412
+ spanCtx.ended = true;
1413
+ try {
1414
+ const duration = Date.now() - spanCtx.startTime;
1415
+ const endAttributes = { duration_ms: duration };
1416
+ if (metadata) {
1417
+ if (metadata.success !== void 0)
1418
+ endAttributes["success"] = metadata.success;
1419
+ if (metadata.error !== void 0)
1420
+ endAttributes["error"] = truncateSpanError(metadata.error);
1421
+ }
1422
+ spanCtx.span.setAttributes(endAttributes);
1423
+ if (metadata) {
1424
+ if (metadata.success !== false) {
1425
+ spanCtx.span.setStatus({ code: SpanStatusCode.OK });
1426
+ } else {
1427
+ spanCtx.span.setStatus({
1428
+ code: SpanStatusCode.ERROR,
1429
+ message: metadata.error ? truncateSpanError(metadata.error) : "tool error"
1430
+ });
1431
+ }
1432
+ }
1433
+ } catch (error) {
1434
+ debugLogger2.warn(
1435
+ `Failed to update tool span attributes/status: ${error instanceof Error ? error.message : String(error)}`
1436
+ );
1437
+ }
1438
+ try {
1439
+ spanCtx.span.end();
1440
+ } catch (error) {
1441
+ debugLogger2.warn(
1442
+ `Failed to end tool span: ${error instanceof Error ? error.message : String(error)}`
1443
+ );
1444
+ }
1445
+ activeSpans.delete(spanId);
1446
+ strongSpans.delete(spanId);
1447
+ }
1448
+ __name(endToolSpan, "endToolSpan");
1449
+ function startToolExecutionSpan() {
1450
+ if (!isTelemetrySdkInitialized()) {
1451
+ return NOOP_SPAN;
1452
+ }
1453
+ const parentCtx = toolContext.getStore();
1454
+ if (!parentCtx) {
1455
+ debugLogger2.warn(
1456
+ "startToolExecutionSpan called outside runInToolSpanContext \u2014 span will not be parented to tool span"
1457
+ );
1458
+ }
1459
+ const ctx = resolveParentContext(parentCtx);
1460
+ const sessionId = resolveSessionId(
1461
+ parentCtx ?? interactionContext.getStore()
1462
+ );
1463
+ const span = getTracer().startSpan(
1464
+ SPAN_TOOL_EXECUTION,
1465
+ {
1466
+ kind: SpanKind.INTERNAL,
1467
+ attributes: sessionId ? { "session.id": sessionId } : {}
1468
+ },
1469
+ ctx
1470
+ );
1471
+ const spanId = getSpanId(span);
1472
+ const spanContextObj = {
1473
+ span,
1474
+ startTime: Date.now(),
1475
+ attributes: sessionId ? { "session.id": sessionId } : {},
1476
+ type: "tool.execution"
1477
+ };
1478
+ activeSpans.set(spanId, new WeakRef(spanContextObj));
1479
+ strongSpans.set(spanId, spanContextObj);
1480
+ return span;
1481
+ }
1482
+ __name(startToolExecutionSpan, "startToolExecutionSpan");
1483
+ function endToolExecutionSpan(span, metadata) {
1484
+ const spanId = getSpanId(span);
1485
+ const spanCtx = activeSpans.get(spanId)?.deref();
1486
+ if (!spanCtx) return;
1487
+ if (spanCtx.ended) {
1488
+ debugLogger2.debug(
1489
+ `endToolExecutionSpan: span ${spanId} already ended (possible TTL sweep race)`
1490
+ );
1491
+ return;
1492
+ }
1493
+ spanCtx.ended = true;
1494
+ try {
1495
+ const duration = Date.now() - spanCtx.startTime;
1496
+ const endAttributes = {};
1497
+ if (metadata?.attributes) {
1498
+ Object.assign(endAttributes, metadata.attributes);
1499
+ }
1500
+ endAttributes["duration_ms"] = duration;
1501
+ if (metadata) {
1502
+ if (metadata.success !== void 0)
1503
+ endAttributes["success"] = metadata.success;
1504
+ if (metadata.error !== void 0)
1505
+ endAttributes["error"] = truncateSpanError(metadata.error);
1506
+ }
1507
+ spanCtx.span.setAttributes(endAttributes);
1508
+ if (metadata && !metadata.cancelled) {
1509
+ if (metadata.success !== false) {
1510
+ spanCtx.span.setStatus({ code: SpanStatusCode.OK });
1511
+ } else {
1512
+ spanCtx.span.setStatus({
1513
+ code: SpanStatusCode.ERROR,
1514
+ message: metadata.error ? truncateSpanError(metadata.error) : "tool execution error"
1515
+ });
1516
+ }
1517
+ }
1518
+ } catch (error) {
1519
+ debugLogger2.warn(
1520
+ `Failed to update tool execution span attributes/status: ${error instanceof Error ? error.message : String(error)}`
1521
+ );
1522
+ }
1523
+ try {
1524
+ spanCtx.span.end();
1525
+ } catch (error) {
1526
+ debugLogger2.warn(
1527
+ `Failed to end tool execution span: ${error instanceof Error ? error.message : String(error)}`
1528
+ );
1529
+ }
1530
+ activeSpans.delete(spanId);
1531
+ strongSpans.delete(spanId);
1532
+ }
1533
+ __name(endToolExecutionSpan, "endToolExecutionSpan");
1534
+ function startToolBlockedOnUserSpan(toolSpan, attrs) {
1535
+ if (!isTelemetrySdkInitialized()) {
1536
+ return NOOP_SPAN;
1537
+ }
1538
+ ensureCleanupInterval();
1539
+ const parentSpanId = getSpanId(toolSpan);
1540
+ const parentSpanCtx = activeSpans.get(parentSpanId)?.deref();
1541
+ if (!parentSpanCtx) {
1542
+ debugLogger2.debug(
1543
+ "startToolBlockedOnUserSpan: tool span not in activeSpans (already ended?) \u2014 using resolveParentContext fallback"
1544
+ );
1545
+ }
1546
+ const ctx = parentSpanCtx ? trace.setSpan(context.active(), parentSpanCtx.span) : resolveParentContext(void 0);
1547
+ const sessionParentCtx = parentSpanCtx ?? subagentContext.getStore() ?? interactionContext.getStore() ?? void 0;
1548
+ const sessionId = resolveSessionId(sessionParentCtx);
1549
+ const attributes = {
1550
+ ...sessionId ? { "session.id": sessionId } : {}
1551
+ };
1552
+ if (attrs?.tool_name !== void 0) attributes["tool.name"] = attrs.tool_name;
1553
+ if (attrs?.call_id !== void 0) attributes["tool.call_id"] = attrs.call_id;
1554
+ const span = getTracer().startSpan(
1555
+ SPAN_TOOL_BLOCKED_ON_USER,
1556
+ { kind: SpanKind.INTERNAL, attributes },
1557
+ ctx
1558
+ );
1559
+ const spanId = getSpanId(span);
1560
+ const spanContextObj = {
1561
+ span,
1562
+ startTime: Date.now(),
1563
+ attributes,
1564
+ type: "tool.blocked_on_user"
1565
+ };
1566
+ activeSpans.set(spanId, new WeakRef(spanContextObj));
1567
+ strongSpans.set(spanId, spanContextObj);
1568
+ return span;
1569
+ }
1570
+ __name(startToolBlockedOnUserSpan, "startToolBlockedOnUserSpan");
1571
+ function endToolBlockedOnUserSpan(span, metadata) {
1572
+ const spanId = getSpanId(span);
1573
+ const spanCtx = activeSpans.get(spanId)?.deref();
1574
+ if (!spanCtx) return;
1575
+ if (spanCtx.ended) {
1576
+ debugLogger2.debug(
1577
+ `endToolBlockedOnUserSpan: span ${spanId} already ended (possible TTL sweep race)`
1578
+ );
1579
+ return;
1580
+ }
1581
+ spanCtx.ended = true;
1582
+ try {
1583
+ const duration = Date.now() - spanCtx.startTime;
1584
+ const endAttributes = { duration_ms: duration };
1585
+ if (metadata?.decision !== void 0)
1586
+ endAttributes["decision"] = metadata.decision;
1587
+ if (metadata?.source !== void 0)
1588
+ endAttributes["source"] = metadata.source;
1589
+ spanCtx.span.setAttributes(endAttributes);
1590
+ } catch (error) {
1591
+ debugLogger2.warn(
1592
+ `Failed to update blocked_on_user span attributes: ${error instanceof Error ? error.message : String(error)}`
1593
+ );
1594
+ }
1595
+ try {
1596
+ spanCtx.span.end();
1597
+ } catch (error) {
1598
+ debugLogger2.warn(
1599
+ `Failed to end blocked_on_user span: ${error instanceof Error ? error.message : String(error)}`
1600
+ );
1601
+ }
1602
+ activeSpans.delete(spanId);
1603
+ strongSpans.delete(spanId);
1604
+ }
1605
+ __name(endToolBlockedOnUserSpan, "endToolBlockedOnUserSpan");
1606
+ function startHookSpan(opts) {
1607
+ if (!isTelemetrySdkInitialized()) {
1608
+ return NOOP_SPAN;
1609
+ }
1610
+ ensureCleanupInterval();
1611
+ const parentCtx = toolContext.getStore() ?? subagentContext.getStore() ?? interactionContext.getStore() ?? void 0;
1612
+ const ctx = resolveParentContext(parentCtx);
1613
+ const sessionId = resolveSessionId(parentCtx);
1614
+ const attributes = {
1615
+ ...sessionId ? { "session.id": sessionId } : {},
1616
+ hook_event: opts.hookEvent,
1617
+ "tool.name": opts.toolName
1618
+ };
1619
+ if (opts.toolUseId !== void 0) attributes["tool.use_id"] = opts.toolUseId;
1620
+ if (opts.isInterrupt !== void 0)
1621
+ attributes["is_interrupt"] = opts.isInterrupt;
1622
+ const span = getTracer().startSpan(
1623
+ SPAN_HOOK,
1624
+ { kind: SpanKind.INTERNAL, attributes },
1625
+ ctx
1626
+ );
1627
+ const spanId = getSpanId(span);
1628
+ const spanContextObj = {
1629
+ span,
1630
+ startTime: Date.now(),
1631
+ attributes,
1632
+ type: "hook"
1633
+ };
1634
+ activeSpans.set(spanId, new WeakRef(spanContextObj));
1635
+ strongSpans.set(spanId, spanContextObj);
1636
+ return span;
1637
+ }
1638
+ __name(startHookSpan, "startHookSpan");
1639
+ function endHookSpan(span, metadata) {
1640
+ const spanId = getSpanId(span);
1641
+ const spanCtx = activeSpans.get(spanId)?.deref();
1642
+ if (!spanCtx) return;
1643
+ if (spanCtx.ended) {
1644
+ debugLogger2.debug(
1645
+ `endHookSpan: span ${spanId} already ended (possible TTL sweep race)`
1646
+ );
1647
+ return;
1648
+ }
1649
+ spanCtx.ended = true;
1650
+ try {
1651
+ const duration = Date.now() - spanCtx.startTime;
1652
+ const endAttributes = { duration_ms: duration };
1653
+ if (metadata) {
1654
+ if (metadata.success !== void 0)
1655
+ endAttributes["success"] = metadata.success;
1656
+ if (metadata.shouldProceed !== void 0)
1657
+ endAttributes["should_proceed"] = metadata.shouldProceed;
1658
+ if (metadata.shouldStop !== void 0)
1659
+ endAttributes["should_stop"] = metadata.shouldStop;
1660
+ if (metadata.blockType !== void 0)
1661
+ endAttributes["block_type"] = metadata.blockType;
1662
+ if (metadata.hasAdditionalContext !== void 0)
1663
+ endAttributes["has_additional_context"] = metadata.hasAdditionalContext;
1664
+ if (metadata.postBatchStop !== void 0)
1665
+ endAttributes["post_batch_stop"] = metadata.postBatchStop;
1666
+ if (metadata.postBatchStopReason !== void 0)
1667
+ endAttributes["post_batch_stop_reason"] = truncateSpanError(
1668
+ metadata.postBatchStopReason
1669
+ );
1670
+ if (metadata.error !== void 0)
1671
+ endAttributes["error"] = truncateSpanError(metadata.error);
1672
+ }
1673
+ spanCtx.span.setAttributes(endAttributes);
1674
+ if (metadata?.error !== void 0) {
1675
+ spanCtx.span.setStatus({
1676
+ code: SpanStatusCode.ERROR,
1677
+ message: truncateSpanError(metadata.error)
1678
+ });
1679
+ }
1680
+ } catch (error) {
1681
+ debugLogger2.warn(
1682
+ `Failed to update hook span attributes/status: ${error instanceof Error ? error.message : String(error)}`
1683
+ );
1684
+ }
1685
+ try {
1686
+ spanCtx.span.end();
1687
+ } catch (error) {
1688
+ debugLogger2.warn(
1689
+ `Failed to end hook span: ${error instanceof Error ? error.message : String(error)}`
1690
+ );
1691
+ }
1692
+ activeSpans.delete(spanId);
1693
+ strongSpans.delete(spanId);
1694
+ }
1695
+ __name(endHookSpan, "endHookSpan");
1696
+ function startSubagentSpan(opts) {
1697
+ if (!isTelemetrySdkInitialized()) return NOOP_SPAN;
1698
+ ensureCleanupInterval();
1699
+ const attributes = {
1700
+ // Spec-aligned (OTel GenAI Agent Spans, Development status).
1701
+ "gen_ai.operation.name": "invoke_agent",
1702
+ "gen_ai.provider.name": SERVICE_NAME,
1703
+ "gen_ai.agent.id": opts.agentId,
1704
+ "gen_ai.agent.name": opts.subagentName,
1705
+ "gen_ai.conversation.id": opts.sessionId,
1706
+ // Vendor (qwen-code-specific). Dual-emit id/name so dashboards already
1707
+ // querying spec keys still work.
1708
+ "qwen-code.subagent.id": opts.agentId,
1709
+ "qwen-code.subagent.name": opts.subagentName,
1710
+ "qwen-code.subagent.invocation_kind": opts.invocationKind,
1711
+ "qwen-code.subagent.is_built_in": opts.isBuiltIn,
1712
+ "qwen-code.subagent.depth": opts.depth
1713
+ };
1714
+ if (opts.modelOverride !== void 0) {
1715
+ attributes["gen_ai.request.model"] = opts.modelOverride;
1716
+ }
1717
+ if (opts.parentAgentId !== void 0) {
1718
+ attributes["qwen-code.subagent.parent_agent_id"] = opts.parentAgentId;
1719
+ }
1720
+ if (opts.invokingRequestId !== void 0) {
1721
+ attributes["qwen-code.subagent.invoking_request_id"] = opts.invokingRequestId;
1722
+ }
1723
+ const tracer2 = getTracer();
1724
+ let span;
1725
+ if (opts.invocationKind === "foreground") {
1726
+ span = tracer2.startSpan(SPAN_SUBAGENT, {
1727
+ kind: SpanKind.INTERNAL,
1728
+ attributes
1729
+ });
1730
+ } else {
1731
+ span = tracer2.startSpan(SPAN_SUBAGENT, {
1732
+ kind: SpanKind.INTERNAL,
1733
+ attributes,
1734
+ root: true,
1735
+ links: opts.invokerSpanContext ? [
1736
+ {
1737
+ context: opts.invokerSpanContext,
1738
+ attributes: { "qwen-code.link.kind": "invoker" }
1739
+ }
1740
+ ] : void 0
1741
+ });
1742
+ }
1743
+ const spanId = getSpanId(span);
1744
+ const spanContextObj = {
1745
+ span,
1746
+ startTime: Date.now(),
1747
+ attributes,
1748
+ type: "subagent"
1749
+ };
1750
+ activeSpans.set(spanId, new WeakRef(spanContextObj));
1751
+ strongSpans.set(spanId, spanContextObj);
1752
+ return span;
1753
+ }
1754
+ __name(startSubagentSpan, "startSubagentSpan");
1755
+ function runInSubagentSpanContext(span, fn) {
1756
+ const spanId = getSpanId(span);
1757
+ const spanCtx = activeSpans.get(spanId)?.deref();
1758
+ if (!spanCtx) return fn();
1759
+ const otelCtxWithSpan = trace.setSpan(context.active(), span);
1760
+ return subagentContext.run(
1761
+ spanCtx,
1762
+ () => toolContext.run(void 0, () => context.with(otelCtxWithSpan, fn))
1763
+ );
1764
+ }
1765
+ __name(runInSubagentSpanContext, "runInSubagentSpanContext");
1766
+ function endSubagentSpan(span, metadata) {
1767
+ const spanId = getSpanId(span);
1768
+ const spanCtx = activeSpans.get(spanId)?.deref();
1769
+ if (!spanCtx) {
1770
+ if (isTelemetrySdkInitialized()) {
1771
+ debugLogger2.warn(
1772
+ `endSubagentSpan: span ${spanId} not found in activeSpans (already swept?) \u2014 intended status=${metadata.status}, reason=${metadata.terminateReason ?? "none"}`
1773
+ );
1774
+ }
1775
+ return;
1776
+ }
1777
+ if (spanCtx.ended) {
1778
+ debugLogger2.warn(
1779
+ `endSubagentSpan: span ${spanId} already ended \u2014 intended status=${metadata.status}, reason=${metadata.terminateReason ?? "none"} (possible TTL sweep race)`
1780
+ );
1781
+ return;
1782
+ }
1783
+ spanCtx.ended = true;
1784
+ try {
1785
+ const duration = Date.now() - spanCtx.startTime;
1786
+ const endAttributes = {
1787
+ duration_ms: duration,
1788
+ "qwen-code.subagent.duration_ms": duration,
1789
+ "qwen-code.subagent.status": metadata.status
1790
+ };
1791
+ if (metadata.terminateReason !== void 0) {
1792
+ endAttributes["qwen-code.subagent.terminate_reason"] = metadata.terminateReason;
1793
+ }
1794
+ if (metadata.resultSummaryPresent !== void 0) {
1795
+ endAttributes["qwen-code.subagent.result_summary_present"] = metadata.resultSummaryPresent;
1796
+ }
1797
+ if (metadata.error !== void 0) {
1798
+ const truncated = truncateSpanError(metadata.error);
1799
+ endAttributes["exception.message"] = truncated;
1800
+ }
1801
+ if (metadata.errorType !== void 0) {
1802
+ endAttributes["error.type"] = metadata.errorType;
1803
+ }
1804
+ spanCtx.span.setAttributes(endAttributes);
1805
+ if (metadata.status === "completed") {
1806
+ spanCtx.span.setStatus({ code: SpanStatusCode.OK });
1807
+ } else if (metadata.status === "failed") {
1808
+ spanCtx.span.setStatus({
1809
+ code: SpanStatusCode.ERROR,
1810
+ message: metadata.error ? truncateSpanError(metadata.error) : "subagent failed"
1811
+ });
1812
+ }
1813
+ } catch (error) {
1814
+ debugLogger2.warn(
1815
+ `Failed to update subagent span attributes/status: ${error instanceof Error ? error.message : String(error)}`
1816
+ );
1817
+ }
1818
+ try {
1819
+ spanCtx.span.end();
1820
+ } catch (error) {
1821
+ debugLogger2.warn(
1822
+ `Failed to end subagent span: ${error instanceof Error ? error.message : String(error)}`
1823
+ );
1824
+ }
1825
+ activeSpans.delete(spanId);
1826
+ strongSpans.delete(spanId);
1827
+ }
1828
+ __name(endSubagentSpan, "endSubagentSpan");
1829
+ function getActiveInteractionSpan() {
1830
+ const ctx = interactionContext.getStore() ?? lastInteractionCtx;
1831
+ if (!ctx || ctx.ended) return void 0;
1832
+ return ctx.span;
1833
+ }
1834
+ __name(getActiveInteractionSpan, "getActiveInteractionSpan");
1835
+
1836
+ // packages/core/src/telemetry/sdk.ts
1837
+ function createTelemetryDiagLogger() {
1838
+ const debugLogger3 = createDebugLogger("OTEL");
1839
+ return {
1840
+ error: /* @__PURE__ */ __name((message, ...args) => debugLogger3.error(message, ...args), "error"),
1841
+ warn: /* @__PURE__ */ __name((message, ...args) => debugLogger3.warn(message, ...args), "warn"),
1842
+ info: /* @__PURE__ */ __name((message, ...args) => debugLogger3.info(message, ...args), "info"),
1843
+ debug: /* @__PURE__ */ __name((message, ...args) => debugLogger3.debug(message, ...args), "debug"),
1844
+ verbose: /* @__PURE__ */ __name((message, ...args) => debugLogger3.debug(message, ...args), "verbose")
1845
+ };
1846
+ }
1847
+ __name(createTelemetryDiagLogger, "createTelemetryDiagLogger");
1848
+ diag.setLogger(createTelemetryDiagLogger(), DiagLogLevel.WARN);
1849
+ var SHUTDOWN_TIMEOUT_MS = 1e4;
1850
+ var sdk;
1851
+ var telemetryInitialized = false;
1852
+ var telemetryInitPromise;
1853
+ var telemetryShutdownPromise;
1854
+ var activeMetricReader;
1855
+ function isTelemetrySdkInitialized() {
1856
+ return telemetryInitialized;
1857
+ }
1858
+ __name(isTelemetrySdkInitialized, "isTelemetrySdkInitialized");
1859
+ function initializeTelemetry(config) {
1860
+ if (telemetryInitialized || !config.getTelemetryEnabled()) {
1861
+ return Promise.resolve();
1862
+ }
1863
+ telemetryInitPromise ??= (async () => {
1864
+ const debugLogger3 = createDebugLogger("OTEL");
1865
+ try {
1866
+ const { startTelemetrySdk } = await import("./sdk-impl-HOLWAXC6.js");
1867
+ if (telemetryInitialized) return;
1868
+ const started = await startTelemetrySdk(config);
1869
+ if (!started) return;
1870
+ sdk = started.sdk;
1871
+ sdk.start();
1872
+ debugLogger3.debug("OpenTelemetry SDK started successfully.");
1873
+ telemetryInitialized = true;
1874
+ activeMetricReader = started.metricReader;
1875
+ const sessionId = config.getSessionId();
1876
+ setSessionContext(createSessionRootContext(sessionId), sessionId);
1877
+ setShellTracePropagation(
1878
+ config.getOutboundCorrelationPropagateTraceContext()
1879
+ );
1880
+ initializeMetrics(config);
1881
+ } catch (error) {
1882
+ debugLogger3.error("Error starting OpenTelemetry SDK:", error);
1883
+ }
1884
+ })().finally(() => {
1885
+ telemetryInitPromise = void 0;
1886
+ });
1887
+ return telemetryInitPromise;
1888
+ }
1889
+ __name(initializeTelemetry, "initializeTelemetry");
1890
+ function refreshSessionContext(sessionId) {
1891
+ if (!telemetryInitialized) return;
1892
+ try {
1893
+ setSessionContext(createSessionRootContext(sessionId), sessionId);
1894
+ } catch (error) {
1895
+ createDebugLogger("OTEL").warn("Failed to refresh session context:", error);
1896
+ }
1897
+ }
1898
+ __name(refreshSessionContext, "refreshSessionContext");
1899
+ function shutdownTelemetry() {
1900
+ if (telemetryShutdownPromise) {
1901
+ return telemetryShutdownPromise;
1902
+ }
1903
+ const pendingInit = telemetryInitPromise;
1904
+ if (!pendingInit && (!telemetryInitialized || !sdk)) {
1905
+ return Promise.resolve();
1906
+ }
1907
+ telemetryShutdownPromise = (async () => {
1908
+ if (pendingInit) {
1909
+ await pendingInit.catch(() => {
1910
+ });
1911
+ }
1912
+ if (!telemetryInitialized || !sdk) {
1913
+ telemetryShutdownPromise = void 0;
1914
+ return;
1915
+ }
1916
+ endInteractionSpan("cancelled");
1917
+ const currentSdk = sdk;
1918
+ const debugLogger3 = createDebugLogger("OTEL");
1919
+ let timer;
1920
+ let timedOut = false;
1921
+ try {
1922
+ const sdkShutdown = Promise.resolve(currentSdk.shutdown());
1923
+ sdkShutdown.catch((err) => {
1924
+ if (timedOut) {
1925
+ debugLogger3.warn(
1926
+ "SDK shutdown rejected after timeout:",
1927
+ err instanceof Error ? err.message : err
1928
+ );
1929
+ }
1930
+ });
1931
+ const timeout = new Promise((resolve) => {
1932
+ timer = setTimeout(() => {
1933
+ timedOut = true;
1934
+ resolve("timeout");
1935
+ }, SHUTDOWN_TIMEOUT_MS);
1936
+ timer.unref?.();
1937
+ });
1938
+ const result = await Promise.race([sdkShutdown, timeout]);
1939
+ clearTimeout(timer);
1940
+ if (result === "timeout") {
1941
+ const msg = `Telemetry shutdown timed out after ${SHUTDOWN_TIMEOUT_MS}ms.`;
1942
+ diag.warn(msg);
1943
+ debugLogger3.warn(msg);
1944
+ } else {
1945
+ debugLogger3.debug("OpenTelemetry SDK shut down successfully.");
1946
+ }
1947
+ } catch (error) {
1948
+ clearTimeout(timer);
1949
+ diag.error("Error shutting down SDK:", error);
1950
+ debugLogger3.error("Error shutting down SDK:", error);
1951
+ } finally {
1952
+ telemetryInitialized = false;
1953
+ sdk = void 0;
1954
+ activeMetricReader = void 0;
1955
+ telemetryShutdownPromise = void 0;
1956
+ setSessionContext(void 0);
1957
+ setShellTracePropagation(false);
1958
+ }
1959
+ })();
1960
+ return telemetryShutdownPromise;
1961
+ }
1962
+ __name(shutdownTelemetry, "shutdownTelemetry");
1963
+ var FORCE_FLUSH_TIMEOUT_MS = 2e3;
1964
+ async function forceFlushMetrics() {
1965
+ if (!telemetryInitialized || !activeMetricReader) return;
1966
+ const flush = activeMetricReader.forceFlush();
1967
+ flush.catch(() => {
1968
+ });
1969
+ let timer;
1970
+ const timeout = new Promise((_, reject) => {
1971
+ timer = setTimeout(
1972
+ () => reject(
1973
+ new Error(
1974
+ `forceFlushMetrics timed out after ${FORCE_FLUSH_TIMEOUT_MS}ms`
1975
+ )
1976
+ ),
1977
+ FORCE_FLUSH_TIMEOUT_MS
1978
+ );
1979
+ timer.unref?.();
1980
+ });
1981
+ try {
1982
+ await Promise.race([flush, timeout]);
1983
+ } finally {
1984
+ clearTimeout(timer);
1985
+ }
1986
+ }
1987
+ __name(forceFlushMetrics, "forceFlushMetrics");
1988
+
1989
+ // packages/core/src/telemetry/detailed-span-attributes.ts
1990
+ var SYSTEM_PROMPT_PREVIEW_LENGTH = 500;
1991
+ var SHORT_TRUNCATION_SUFFIX = "...[TRUNCATED]";
1992
+ var seenHashes = /* @__PURE__ */ new Set();
1993
+ function areSensitiveSpanAttributesEnabled(config) {
1994
+ return isTelemetrySdkInitialized() && config.getTelemetryIncludeSensitiveSpanAttributes();
1995
+ }
1996
+ __name(areSensitiveSpanAttributesEnabled, "areSensitiveSpanAttributesEnabled");
1997
+ function truncateContent(content, maxSize = DEFAULT_SENSITIVE_SPAN_ATTRIBUTE_MAX_LENGTH, originalLength = content.length) {
1998
+ if (!Number.isSafeInteger(maxSize) || maxSize < 1) {
1999
+ throw new TypeError(
2000
+ `maxSize must be a positive safe integer, got ${String(maxSize)}`
2001
+ );
2002
+ }
2003
+ if (!Number.isSafeInteger(originalLength) || originalLength < 0) {
2004
+ throw new TypeError(
2005
+ `originalLength must be a non-negative safe integer, got ${String(
2006
+ originalLength
2007
+ )}`
2008
+ );
2009
+ }
2010
+ if (originalLength < content.length) {
2011
+ throw new TypeError(
2012
+ `originalLength must be greater than or equal to content length, got ${originalLength} for content length ${content.length}`
2013
+ );
2014
+ }
2015
+ if (originalLength <= maxSize && content.length <= maxSize) {
2016
+ return { content, truncated: false };
2017
+ }
2018
+ if (originalLength > content.length && content.length <= maxSize) {
2019
+ return { content, truncated: true };
2020
+ }
2021
+ const suffix = `
2022
+
2023
+ [TRUNCATED - Content exceeds configured limit of ${maxSize} characters]`;
2024
+ if (suffix.length >= maxSize) {
2025
+ if (SHORT_TRUNCATION_SUFFIX.length >= maxSize) {
2026
+ return {
2027
+ content: SHORT_TRUNCATION_SUFFIX.slice(0, maxSize),
2028
+ truncated: true
2029
+ };
2030
+ }
2031
+ return {
2032
+ content: content.slice(0, maxSize - SHORT_TRUNCATION_SUFFIX.length) + SHORT_TRUNCATION_SUFFIX,
2033
+ truncated: true
2034
+ };
2035
+ }
2036
+ return {
2037
+ content: content.slice(0, maxSize - suffix.length) + suffix,
2038
+ truncated: true
2039
+ };
2040
+ }
2041
+ __name(truncateContent, "truncateContent");
2042
+ function getMaxContentSize(config) {
2043
+ return config.getTelemetrySensitiveSpanAttributeMaxLength();
2044
+ }
2045
+ __name(getMaxContentSize, "getMaxContentSize");
2046
+ function truncatePrefixedContent(prefix, content, maxSize) {
2047
+ const prefixedContent = `${prefix}${content}`;
2048
+ const result = truncateContent(prefixedContent, maxSize);
2049
+ return {
2050
+ ...result,
2051
+ originalLength: content.length
2052
+ };
2053
+ }
2054
+ __name(truncatePrefixedContent, "truncatePrefixedContent");
2055
+ function shortHash(content) {
2056
+ return createHash2("sha256").update(content).digest("hex").slice(0, 12);
2057
+ }
2058
+ __name(shortHash, "shortHash");
2059
+ function stringifyContentUnion(value) {
2060
+ if (typeof value === "string") return value;
2061
+ return safeJsonStringify(value) ?? "";
2062
+ }
2063
+ __name(stringifyContentUnion, "stringifyContentUnion");
2064
+ function addUserPromptAttributes(config, span, promptText) {
2065
+ if (!areSensitiveSpanAttributesEnabled(config) || !promptText) return;
2066
+ const { content, truncated, originalLength } = truncatePrefixedContent(
2067
+ `[USER PROMPT]
2068
+ `,
2069
+ promptText,
2070
+ getMaxContentSize(config)
2071
+ );
2072
+ span.setAttributes({
2073
+ new_context: content,
2074
+ ...truncated && {
2075
+ new_context_truncated: true,
2076
+ new_context_original_length: originalLength
2077
+ }
2078
+ });
2079
+ }
2080
+ __name(addUserPromptAttributes, "addUserPromptAttributes");
2081
+ function addSystemPromptAttributes(config, span, systemInstruction) {
2082
+ if (!areSensitiveSpanAttributesEnabled(config) || !systemInstruction) return;
2083
+ const text = stringifyContentUnion(systemInstruction);
2084
+ if (!text) return;
2085
+ const hash = `sp_${shortHash(text)}`;
2086
+ span.setAttributes({
2087
+ system_prompt_hash: hash,
2088
+ system_prompt_preview: text.slice(0, SYSTEM_PROMPT_PREVIEW_LENGTH),
2089
+ system_prompt_length: text.length
2090
+ });
2091
+ if (!seenHashes.has(hash)) {
2092
+ seenHashes.add(hash);
2093
+ const { content, truncated } = truncateContent(
2094
+ text,
2095
+ getMaxContentSize(config)
2096
+ );
2097
+ span.setAttribute("system_prompt", content);
2098
+ if (truncated) {
2099
+ span.setAttribute("system_prompt_truncated", true);
2100
+ }
2101
+ }
2102
+ }
2103
+ __name(addSystemPromptAttributes, "addSystemPromptAttributes");
2104
+ function addToolSchemaAttributes(config, span, tools) {
2105
+ if (!areSensitiveSpanAttributesEnabled(config) || !tools?.length) return;
2106
+ const declarations = [];
2107
+ for (const tool of tools) {
2108
+ const inner = tool["functionDeclarations"];
2109
+ if (Array.isArray(inner)) {
2110
+ declarations.push(...inner);
2111
+ } else {
2112
+ declarations.push(tool);
2113
+ }
2114
+ }
2115
+ const summary = [];
2116
+ for (const decl of declarations) {
2117
+ const declObj = decl;
2118
+ const name = typeof declObj["name"] === "string" ? declObj["name"] : "unknown_tool";
2119
+ const declJson = safeJsonStringify(decl) ?? `unstringifiable_${name}`;
2120
+ const hash = shortHash(declJson);
2121
+ summary.push({ name, hash });
2122
+ const hashKey = `tool_${hash}`;
2123
+ if (!seenHashes.has(hashKey)) {
2124
+ seenHashes.add(hashKey);
2125
+ const { content, truncated } = truncateContent(
2126
+ declJson,
2127
+ getMaxContentSize(config)
2128
+ );
2129
+ span.addEvent("tool_schema", {
2130
+ tool_name: name,
2131
+ tool_hash: hash,
2132
+ tool_definition: content,
2133
+ ...truncated && {
2134
+ tool_definition_truncated: true,
2135
+ tool_definition_original_length: declJson.length
2136
+ }
2137
+ });
2138
+ }
2139
+ }
2140
+ span.setAttributes({
2141
+ tools: safeJsonStringify(summary) ?? "[]",
2142
+ tools_count: summary.length
2143
+ });
2144
+ }
2145
+ __name(addToolSchemaAttributes, "addToolSchemaAttributes");
2146
+ function addModelOutputAttributes(config, span, responseText, originalLength) {
2147
+ if (!areSensitiveSpanAttributesEnabled(config) || !responseText) return;
2148
+ const responseTextOriginalLength = originalLength ?? responseText.length;
2149
+ const { content, truncated } = truncateContent(
2150
+ responseText,
2151
+ getMaxContentSize(config),
2152
+ responseTextOriginalLength
2153
+ );
2154
+ span.setAttributes({
2155
+ "response.model_output": content,
2156
+ ...truncated && {
2157
+ "response.model_output_truncated": true,
2158
+ "response.model_output_original_length": responseTextOriginalLength
2159
+ }
2160
+ });
2161
+ }
2162
+ __name(addModelOutputAttributes, "addModelOutputAttributes");
2163
+ function addToolInputAttributes(config, span, toolName, toolInput) {
2164
+ if (!areSensitiveSpanAttributesEnabled(config)) return;
2165
+ const { content, truncated, originalLength } = truncatePrefixedContent(
2166
+ `[TOOL INPUT: ${toolName}]
2167
+ `,
2168
+ toolInput,
2169
+ getMaxContentSize(config)
2170
+ );
2171
+ span.setAttributes({
2172
+ tool_input: content,
2173
+ ...truncated && {
2174
+ tool_input_truncated: true,
2175
+ tool_input_original_length: originalLength
2176
+ }
2177
+ });
2178
+ }
2179
+ __name(addToolInputAttributes, "addToolInputAttributes");
2180
+ function addToolResultAttributes(config, span, toolName, toolResult) {
2181
+ if (!areSensitiveSpanAttributesEnabled(config)) return;
2182
+ const { content, truncated, originalLength } = truncatePrefixedContent(
2183
+ `[TOOL RESULT: ${toolName}]
2184
+ `,
2185
+ toolResult,
2186
+ getMaxContentSize(config)
2187
+ );
2188
+ span.setAttributes({
2189
+ tool_result: content,
2190
+ ...truncated && {
2191
+ tool_result_truncated: true,
2192
+ tool_result_original_length: originalLength
2193
+ }
2194
+ });
2195
+ }
2196
+ __name(addToolResultAttributes, "addToolResultAttributes");
2197
+ function clearDetailedSpanState() {
2198
+ seenHashes.clear();
2199
+ }
2200
+ __name(clearDetailedSpanState, "clearDetailedSpanState");
2201
+
2202
+ export {
2203
+ FileOperation,
2204
+ PerformanceMetricType,
2205
+ MemoryMetricType,
2206
+ ToolExecutionPhase,
2207
+ ApiRequestPhase,
2208
+ getMeter,
2209
+ recordChatCompressionMetrics,
2210
+ recordToolCallMetrics,
2211
+ recordTokenUsageMetrics,
2212
+ recordApiResponseMetrics,
2213
+ recordApiErrorMetrics,
2214
+ recordFileOperationMetric,
2215
+ recordInvalidChunk,
2216
+ recordContentRetry,
2217
+ recordContentRetryFailure,
2218
+ recordApiRetry,
2219
+ recordModelSlashCommand,
2220
+ recordStartupPerformance,
2221
+ recordMemoryUsage,
2222
+ recordCpuUsage,
2223
+ recordToolQueueDepth,
2224
+ recordToolExecutionBreakdown,
2225
+ recordTokenEfficiency,
2226
+ recordApiRequestBreakdown,
2227
+ recordPerformanceScore,
2228
+ recordPerformanceRegression,
2229
+ recordBaselineComparison,
2230
+ isPerformanceMonitoringActive,
2231
+ recordSubagentExecutionMetrics,
2232
+ recordArenaSessionStartedMetrics,
2233
+ recordArenaAgentCompletedMetrics,
2234
+ recordArenaSessionEndedMetrics,
2235
+ recordMemoryExtractMetrics,
2236
+ recordMemoryDreamMetrics,
2237
+ recordMemoryRecallMetrics,
2238
+ recordChannelMemoryRecallMetrics,
2239
+ recordMemoryRecallDeliveryMetrics,
2240
+ deriveTraceId,
2241
+ randomSpanId,
2242
+ randomHexString,
2243
+ API_CALL_FAILED_SPAN_STATUS_MESSAGE,
2244
+ API_CALL_ABORTED_SPAN_STATUS_MESSAGE,
2245
+ safeSetStatus,
2246
+ areSensitiveSpanAttributesEnabled,
2247
+ truncateContent,
2248
+ addUserPromptAttributes,
2249
+ addSystemPromptAttributes,
2250
+ addToolSchemaAttributes,
2251
+ addModelOutputAttributes,
2252
+ addToolInputAttributes,
2253
+ addToolResultAttributes,
2254
+ clearDetailedSpanState,
2255
+ isInNativeSubagentSpan,
2256
+ truncateSpanError,
2257
+ startInteractionSpan,
2258
+ endInteractionSpan,
2259
+ withInteractionSpan,
2260
+ startLLMRequestSpan,
2261
+ endLLMRequestSpan,
2262
+ startToolSpan,
2263
+ runInToolSpanContext,
2264
+ endToolSpan,
2265
+ startToolExecutionSpan,
2266
+ endToolExecutionSpan,
2267
+ startToolBlockedOnUserSpan,
2268
+ endToolBlockedOnUserSpan,
2269
+ startHookSpan,
2270
+ endHookSpan,
2271
+ startSubagentSpan,
2272
+ runInSubagentSpanContext,
2273
+ endSubagentSpan,
2274
+ getActiveInteractionSpan,
2275
+ isTelemetrySdkInitialized,
2276
+ initializeTelemetry,
2277
+ refreshSessionContext,
2278
+ shutdownTelemetry,
2279
+ forceFlushMetrics
2280
+ };
2281
+ /**
2282
+ * @license
2283
+ * Copyright 2025 Google LLC
2284
+ * SPDX-License-Identifier: Apache-2.0
2285
+ */
2286
+ /**
2287
+ * @license
2288
+ * Copyright 2026 Qwen Team
2289
+ * SPDX-License-Identifier: Apache-2.0
2290
+ */