@qwen-code/qwen-code 0.23.2 → 0.23.3

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 (373) hide show
  1. package/README.md +35 -15
  2. package/bundled/computer-use/SKILL.md +1 -1
  3. package/bundled/qc-helper/docs/configuration/model-providers.md +66 -28
  4. package/bundled/qc-helper/docs/configuration/settings.md +5 -3
  5. package/bundled/qc-helper/docs/features/_meta.ts +1 -0
  6. package/bundled/qc-helper/docs/features/channels/dws.md +7 -1
  7. package/bundled/qc-helper/docs/features/commands.md +57 -9
  8. package/bundled/qc-helper/docs/features/computer-use.md +1 -1
  9. package/bundled/qc-helper/docs/features/cross-session-protocol.md +320 -0
  10. package/bundled/qc-helper/docs/features/goals.md +1 -1
  11. package/bundled/qc-helper/docs/qwen-serve.md +16 -3
  12. package/bundled/review/SKILL.md +82 -79
  13. package/bundled/review/references/posting.md +31 -14
  14. package/chunks/{MaxSizedBox-4C3BKKKY.js → MaxSizedBox-D4LW7RZZ.js} +58 -51
  15. package/chunks/{StandaloneSessionPicker-TXVF65YW.js → StandaloneSessionPicker-ALTTRWUP.js} +80 -73
  16. package/chunks/acp-subagent-executor-LEUN3N7N.js +919 -0
  17. package/chunks/{acpAgent-H5XBKGB4.js → acpAgent-BBSW7XZG.js} +509 -201
  18. package/chunks/{agent-T5LEFJIU.js → agent-SQ6OY3QD.js} +42 -36
  19. package/chunks/{agent-headless-VZKSRH36.js → agent-headless-RI2THRQ7.js} +42 -36
  20. package/chunks/{anthropicContentGenerator-PRJWWVYJ.js → anthropicContentGenerator-JSKMKS6V.js} +66 -34
  21. package/chunks/{artifact-tool-G5LHNECG.js → artifact-tool-PMYZCYNH.js} +2 -2
  22. package/chunks/{askUserQuestion-I5W5S3D6.js → askUserQuestion-4M4YYIB4.js} +2 -2
  23. package/chunks/{bridge-AOX5IY44.js → bridge-DAFMI72L.js} +62 -55
  24. package/chunks/{channel-management-service-MWQGHPAS.js → channel-management-service-OWDXVL7R.js} +8 -8
  25. package/chunks/{channel-settings-store-XZCGDGHW.js → channel-settings-store-4I6JONT7.js} +69 -62
  26. package/chunks/{channel-worker-group-SQ5FRWOH.js → channel-worker-group-F2ZZMLNS.js} +8 -8
  27. package/chunks/{channel-worker-manager-TU4ZNWOE.js → channel-worker-manager-2SZLJJSJ.js} +18 -9
  28. package/chunks/{channel-worker-supervisor-EMITFMCP.js → channel-worker-supervisor-ZFNWMG6D.js} +6 -6
  29. package/chunks/{chunk-GNY7B3CA.js → chunk-2ALXPGB4.js} +1 -1
  30. package/chunks/{chunk-LUNC5KCL.js → chunk-2PJRI3EH.js} +7 -7
  31. package/chunks/{chunk-CLKE4IY3.js → chunk-2SZH22YO.js} +1 -1
  32. package/chunks/{chunk-RNAJVXUG.js → chunk-2ZN3O5FT.js} +6 -6
  33. package/chunks/{chunk-HIXUUCGY.js → chunk-36HCNKDS.js} +1 -1
  34. package/chunks/{chunk-FGHPZGOP.js → chunk-3BTSSIJO.js} +38 -54
  35. package/chunks/{chunk-VBLAI2HA.js → chunk-3FPYT6QC.js} +0 -31
  36. package/chunks/{chunk-QB3KS3N3.js → chunk-3I7W2POO.js} +1 -1
  37. package/chunks/{chunk-QTB4VP4K.js → chunk-3KQBQ6FM.js} +136 -11
  38. package/chunks/{chunk-JO77FGNZ.js → chunk-3UXUOFO6.js} +19 -7
  39. package/chunks/{chunk-WDN64MVT.js → chunk-3XLK2QMY.js} +82 -16
  40. package/chunks/chunk-532WHF4F.js +127 -0
  41. package/chunks/{chunk-NX7ZTXFF.js → chunk-53GWJOLP.js} +1 -1
  42. package/chunks/{chunk-QQK4L3UU.js → chunk-5GLDOLNQ.js} +131 -26
  43. package/chunks/{chunk-WK7P62DV.js → chunk-5KI7ZDTB.js} +6 -6
  44. package/chunks/{chunk-ERXNTINK.js → chunk-6JACAGYH.js} +1 -1
  45. package/chunks/{chunk-CMWU6P4D.js → chunk-6W4HBUA2.js} +1 -1
  46. package/chunks/{chunk-AUTUFD5X.js → chunk-76RGWKLS.js} +1 -1
  47. package/chunks/{chunk-PDN7FJZV.js → chunk-7APZIRH3.js} +2 -2
  48. package/chunks/{chunk-WBU2PIZ5.js → chunk-7BXXIQG4.js} +16 -16
  49. package/chunks/{chunk-APXIW2TF.js → chunk-7ICHPMBQ.js} +4 -4
  50. package/chunks/{chunk-CWVZBIZJ.js → chunk-7Q2AXRDJ.js} +1 -1
  51. package/chunks/{chunk-WDVV3LRM.js → chunk-7QYWGTHB.js} +1 -1
  52. package/chunks/{chunk-RM244SCQ.js → chunk-AC6KDLH3.js} +1 -1
  53. package/chunks/{chunk-2WC3Y7YY.js → chunk-AEY27Z35.js} +401 -23
  54. package/chunks/{chunk-XDNFODER.js → chunk-AXTFYDXT.js} +1 -1
  55. package/chunks/chunk-AYEJOTIU.js +43 -0
  56. package/chunks/{chunk-ZN5TKAVR.js → chunk-BV6Q5HMY.js} +3 -3
  57. package/chunks/{chunk-TOOOLHVS.js → chunk-BWAMMKIS.js} +3 -3
  58. package/chunks/{chunk-IRGDIDGJ.js → chunk-BWQLXU37.js} +26 -19
  59. package/chunks/{process-registry-OAEG6WGC.js → chunk-BYUAT5OC.js} +1 -0
  60. package/chunks/{chunk-GOEVQADN.js → chunk-BZM5U74J.js} +287 -169
  61. package/chunks/chunk-CF5KXZZX.js +150 -0
  62. package/chunks/{chunk-TGNNLRC3.js → chunk-CJ3DHN5I.js} +1 -0
  63. package/chunks/{chunk-PFKGV6PO.js → chunk-CUEXOHQH.js} +9 -9
  64. package/chunks/chunk-CXTPVBFA.js +937 -0
  65. package/chunks/{chunk-LEAOJ43M.js → chunk-DAWWT2ID.js} +62 -59
  66. package/chunks/{chunk-CALTQWTZ.js → chunk-DLH7YIX6.js} +2 -2
  67. package/chunks/chunk-DT75RKNH.js +691 -0
  68. package/chunks/{chunk-TRWQQBVH.js → chunk-DTNV6UZY.js} +1 -1
  69. package/chunks/{chunk-3OAXF3UK.js → chunk-DYFOSJHU.js} +3080 -933
  70. package/chunks/{chunk-GSFV5RQW.js → chunk-E4UEO3XM.js} +3 -2
  71. package/chunks/{chunk-A7EFXK7P.js → chunk-E7LB57MB.js} +5 -5
  72. package/chunks/{chunk-KEPC5BOL.js → chunk-EDMXGXAK.js} +9 -9
  73. package/chunks/chunk-ELRMZTPF.js +374 -0
  74. package/chunks/chunk-ERU3SDXT.js +27 -0
  75. package/chunks/{chunk-O2FEO2CB.js → chunk-EUURTIV6.js} +18 -2
  76. package/chunks/{chunk-QFJZAY7W.js → chunk-EVTNACMT.js} +3 -3
  77. package/chunks/{chunk-4HOEU2OR.js → chunk-EWJTAP3Y.js} +1 -19
  78. package/chunks/{chunk-YQGW3M6Z.js → chunk-F42YYSCK.js} +8 -8
  79. package/chunks/{chunk-7PD7ZMX5.js → chunk-FCQJLMA2.js} +98 -5
  80. package/chunks/{chunk-4VY3ITHR.js → chunk-FN3JNDRU.js} +3 -3
  81. package/chunks/{chunk-R457KFV7.js → chunk-GCDXVPFK.js} +3 -3
  82. package/chunks/{chunk-IR6JKBAP.js → chunk-GOXQL4YH.js} +2 -2
  83. package/chunks/{chunk-YLOHCA6I.js → chunk-GSILBZLN.js} +2 -2
  84. package/chunks/{chunk-LNYV4GXX.js → chunk-GSKX53AN.js} +0 -139
  85. package/chunks/{chunk-4WMGYG3F.js → chunk-HBQ2NXOU.js} +2 -2
  86. package/chunks/{chunk-F2NYVASI.js → chunk-HBU7EKY4.js} +14 -12
  87. package/chunks/{chunk-6G4V7SE4.js → chunk-HG46TTAG.js} +1 -1
  88. package/chunks/{chunk-G5VOXCRX.js → chunk-HGAELO7B.js} +2 -2
  89. package/chunks/{chunk-FETY36NQ.js → chunk-HGEUHUEV.js} +1 -1
  90. package/chunks/{chunk-E6TI726I.js → chunk-HUXPEUFL.js} +1 -1
  91. package/chunks/{chunk-LYT2OU7D.js → chunk-IAEXTMED.js} +1 -1
  92. package/chunks/{chunk-IW6RQPQB.js → chunk-IJOS26LH.js} +1 -3
  93. package/chunks/{chunk-ORFIYTI2.js → chunk-IK2MWJP5.js} +1 -1
  94. package/chunks/{chunk-WXD7INFV.js → chunk-IL5M5NYD.js} +8 -8
  95. package/chunks/{chunk-KA5HR3G2.js → chunk-IUVIBDKU.js} +2 -2
  96. package/chunks/{chunk-5DQ4YTIZ.js → chunk-IV7GDNKC.js} +1 -1
  97. package/chunks/chunk-JL6APGBX.js +43 -0
  98. package/chunks/{chunk-N6S3NUYJ.js → chunk-JXNIF2O5.js} +1 -1
  99. package/chunks/{chunk-DAI65CMX.js → chunk-JYKWOREU.js} +1 -1
  100. package/chunks/chunk-K2OJUPOE.js +78 -0
  101. package/chunks/{chunk-KFECPHLV.js → chunk-KFZYGSJN.js} +3 -3
  102. package/chunks/{chunk-BK7D2JR6.js → chunk-KOKPXIAN.js} +3 -3
  103. package/chunks/{chunk-4I3WFI3U.js → chunk-LDVNJZGH.js} +12 -12
  104. package/chunks/{chunk-WXFCI3O5.js → chunk-LG5Y4OWO.js} +2 -2
  105. package/chunks/{chunk-3LPJ776W.js → chunk-LILGKQ4B.js} +10 -7
  106. package/chunks/{chunk-X7LFJF5D.js → chunk-LK2WUCDQ.js} +36 -84
  107. package/chunks/{chunk-7LTCFO6T.js → chunk-MF6E7FSA.js} +6 -5
  108. package/chunks/{chunk-ELD3OBPU.js → chunk-MHAADZOZ.js} +3 -3
  109. package/chunks/{chunk-4JNHNVAZ.js → chunk-MLQNSPRZ.js} +4 -4
  110. package/chunks/{chunk-NPKCVSXX.js → chunk-MOS5OAOG.js} +10 -8
  111. package/chunks/{chunk-IWABUX6T.js → chunk-MSNHNAQZ.js} +6 -6
  112. package/chunks/{chunk-HJ5UJQQL.js → chunk-N7VWZDWW.js} +1699 -1312
  113. package/chunks/{chunk-NB3NDQQK.js → chunk-NE624IVP.js} +1 -1
  114. package/chunks/{chunk-SOA4HKRJ.js → chunk-NFYEQRLG.js} +2 -2
  115. package/chunks/{chunk-G3ZUMSFS.js → chunk-NHCZJQE4.js} +6 -6
  116. package/chunks/{chunk-B25JYXZE.js → chunk-NHJKAR6E.js} +4 -4
  117. package/chunks/{chunk-ZP5XDLSA.js → chunk-NJQTG2G3.js} +12 -12
  118. package/chunks/{chunk-DARWOZY6.js → chunk-NLNQNBZ2.js} +1 -1
  119. package/chunks/{chunk-CCBTNJB4.js → chunk-NMCDMLHL.js} +27 -27
  120. package/chunks/{chunk-AO2VMS72.js → chunk-NMRCXKQ5.js} +3 -3
  121. package/chunks/{chunk-5BH2AIEY.js → chunk-NOAG7N22.js} +2 -2
  122. package/chunks/{chunk-VJJXG73H.js → chunk-NRXWJXJ4.js} +15 -0
  123. package/chunks/chunk-NUQ4GK5I.js +315 -0
  124. package/chunks/{chunk-J3VZF2AL.js → chunk-NUQVB25K.js} +2 -2
  125. package/chunks/{chunk-U6REWGVR.js → chunk-OLTN767L.js} +2 -2
  126. package/chunks/{chunk-R3JIDRUL.js → chunk-OX7IZ2G5.js} +4 -4
  127. package/chunks/{chunk-QAZ2MGYT.js → chunk-PLLIWEM3.js} +2 -2
  128. package/chunks/{chunk-KCF2436G.js → chunk-POC3YMHG.js} +4 -4
  129. package/chunks/{chunk-HZ2HUXX7.js → chunk-Q2LVVIKF.js} +1 -1
  130. package/chunks/{chunk-7NDZKE2M.js → chunk-Q5BD56BW.js} +3 -3
  131. package/chunks/{chunk-22GORRNY.js → chunk-QMUYLYT5.js} +1 -1
  132. package/chunks/{chunk-MV5DTLJV.js → chunk-R4Q2PEFV.js} +1 -1
  133. package/chunks/{chunk-GOKAOSCN.js → chunk-RLLRJJDR.js} +1 -1
  134. package/chunks/{chunk-5OZUKLL7.js → chunk-RWVD5RRY.js} +4 -4
  135. package/chunks/{chunk-ULZECEIP.js → chunk-RZHU3K6M.js} +2 -2
  136. package/chunks/{chunk-UYDQYDW2.js → chunk-S6Q6Q4P2.js} +1 -1
  137. package/chunks/{chunk-PQEISIKS.js → chunk-SAH4BD2J.js} +0 -67
  138. package/chunks/{chunk-LWX4WDFF.js → chunk-SBRX4BDI.js} +43 -15
  139. package/chunks/{chunk-TODNHE76.js → chunk-SODMFNAR.js} +5 -5
  140. package/chunks/{chunk-FAJPLSYF.js → chunk-SSGAAWLY.js} +89 -85
  141. package/chunks/{chunk-46MMBZHI.js → chunk-SYLECP23.js} +4 -4
  142. package/chunks/{chunk-6RZX2HIH.js → chunk-TBEXLLAO.js} +2 -2
  143. package/chunks/{chunk-MWIO7MF6.js → chunk-TP6FYVQT.js} +2 -0
  144. package/chunks/{chunk-HRPFBHW7.js → chunk-TPKQIA7G.js} +1 -0
  145. package/chunks/{chunk-QHLHE2OT.js → chunk-TWUKBNWM.js} +1 -1
  146. package/chunks/{chunk-H3Q3RSKZ.js → chunk-U7O65WKL.js} +1 -1
  147. package/chunks/{chunk-S5QR6CB5.js → chunk-UKMWZ5NS.js} +108 -887
  148. package/chunks/{chunk-OXR34GCD.js → chunk-UKZ45TJL.js} +1851 -34
  149. package/chunks/{chunk-CALNF3Z3.js → chunk-V2P3DOQR.js} +1 -1
  150. package/chunks/{chunk-FV4DM2M4.js → chunk-VG3Q2NC4.js} +7 -7
  151. package/chunks/{chunk-QTNCGZHQ.js → chunk-VX63RJXE.js} +9 -0
  152. package/chunks/{chunk-CRZBDVP2.js → chunk-VZUCTJ2P.js} +4 -4
  153. package/chunks/{chunk-2BMXHB6N.js → chunk-W5FIP7FC.js} +7 -7
  154. package/chunks/{chunk-7VEYUF3N.js → chunk-W5ZQMAEM.js} +1 -1
  155. package/chunks/{chunk-XQ4RDO5B.js → chunk-WBCPROWX.js} +1 -1
  156. package/chunks/{chunk-JYGIJA4W.js → chunk-X6K77VHC.js} +1 -1
  157. package/chunks/{chunk-7SVM3RP2.js → chunk-X7UJKOHZ.js} +3 -3
  158. package/chunks/{chunk-WXPPUPHM.js → chunk-XBZTAGB7.js} +1 -1
  159. package/chunks/{chunk-TRQNRP2H.js → chunk-XGYHNWL3.js} +45 -2
  160. package/chunks/{chunk-2EKVPSIJ.js → chunk-Y2MYW47X.js} +1 -1
  161. package/chunks/{chunk-OFVAS4AR.js → chunk-YBUMTY7B.js} +1 -1
  162. package/chunks/{chunk-67XTVRVB.js → chunk-YQHLFCPU.js} +7 -7
  163. package/chunks/{chunk-G37O7YO6.js → chunk-Z3GF56ME.js} +2 -2
  164. package/chunks/{chunk-XBVNNDPK.js → chunk-ZHKTKHMO.js} +8 -1
  165. package/chunks/{chunk-OWCFKIFQ.js → chunk-ZKYR7QS4.js} +1 -1
  166. package/chunks/{chunk-YZTGGCEE.js → chunk-ZKZHSB5W.js} +1 -1
  167. package/chunks/{chunk-565U2ANU.js → chunk-ZTTC7T4X.js} +1 -1
  168. package/chunks/{chunk-XSOXPG2L.js → chunk-ZU47FBOC.js} +36 -7
  169. package/chunks/{chunk-7OCIQNKX.js → chunk-ZW2EUO2A.js} +1 -1
  170. package/chunks/{config-utils-GPLIABL2.js → config-utils-L6KLDYIV.js} +62 -55
  171. package/chunks/{contextCommand-NCUQUDBY.js → contextCommand-UYEH7NIU.js} +59 -52
  172. package/chunks/{core-runtime-WKYKWVYU.js → core-runtime-NVHT3Z3V.js} +61 -54
  173. package/chunks/{create-sub-session-TGIX63YU.js → create-sub-session-TIGCFGCS.js} +2 -2
  174. package/chunks/{create-sub-session-PPLXB3JJ.js → create-sub-session-YWASE5VH.js} +59 -52
  175. package/chunks/{cron-create-GTPVMJCF.js → cron-create-AKWX67FO.js} +1 -1
  176. package/chunks/{cron-delete-ZBK27Z4K.js → cron-delete-XPB6IYZJ.js} +1 -1
  177. package/chunks/{cron-list-KTFKFDKC.js → cron-list-XBKO4WU5.js} +1 -1
  178. package/chunks/{daemon-2CKIAO3I.js → daemon-G5TYKZD6.js} +2 -2
  179. package/chunks/{daemon-git-worktree-guard-73ZWOLKL.js → daemon-git-worktree-guard-FOW4RQSK.js} +60 -53
  180. package/chunks/{daemon-status-provider-OK7VONJG.js → daemon-status-provider-O5KQZYMP.js} +67 -60
  181. package/chunks/{daemon-trust-policy-CAUCREG2.js → daemon-trust-policy-3ATXEON7.js} +64 -57
  182. package/chunks/{daemon-trust-policy-monitor-3Y36OOEQ.js → daemon-trust-policy-monitor-7MCNDNEC.js} +64 -57
  183. package/chunks/{deferred-core-runtime-Q7WFWYD3.js → deferred-core-runtime-JK5IXL5K.js} +57 -50
  184. package/chunks/{display-image-CTNHJRZC.js → display-image-NAH3AZ63.js} +3 -3
  185. package/chunks/{dist-NP7QKLVG.js → dist-AHJYPSJL.js} +3 -3
  186. package/chunks/{dist-6YDUH3BB.js → dist-AIKC5E5P.js} +2 -2
  187. package/chunks/{dist-Y5KC3IHW.js → dist-F2DVGTL3.js} +225 -6
  188. package/chunks/{dist-BNQVF565.js → dist-GWNQVPZT.js} +5 -5
  189. package/chunks/{dist-F6JLAJLE.js → dist-H6G3K26N.js} +3 -3
  190. package/chunks/{dist-ZDNJK74R.js → dist-KJGRVIGJ.js} +2 -2
  191. package/chunks/{dist-F34J4FZX.js → dist-KLZ7XGEQ.js} +2 -2
  192. package/chunks/{dist-UFTFGI6I.js → dist-ZA52JXAS.js} +2 -2
  193. package/chunks/{dist-XLV33CLY.js → dist-ZXTZTE54.js} +2 -2
  194. package/chunks/{edit-YJD6IETK.js → edit-SY35KYIE.js} +45 -39
  195. package/chunks/{en-YJNRUQG4.js → en-CAJHTIQT.js} +1 -0
  196. package/chunks/{enter-worktree-YFTKHXHZ.js → enter-worktree-54L5QJ3N.js} +4 -4
  197. package/chunks/{enterPlanMode-EFPVTWIH.js → enterPlanMode-HXX6KQJR.js} +42 -36
  198. package/chunks/{environment-HP3AXFTB.js → environment-DKXHG4HB.js} +60 -53
  199. package/chunks/{errors-22ON46G7.js → errors-ADY7LQJJ.js} +59 -52
  200. package/chunks/{exit-worktree-NF2XEMES.js → exit-worktree-EORJDKDS.js} +4 -4
  201. package/chunks/{exitPlanMode-MOQUNCBH.js → exitPlanMode-HSK2CQI6.js} +42 -36
  202. package/chunks/{fast-path-2X7BPMXX.js → fast-path-U636VWN2.js} +6 -6
  203. package/chunks/{fast-path-settings-SATXY3PD.js → fast-path-settings-V7MI7EZJ.js} +2 -2
  204. package/chunks/{glob-Y7ACIB3P.js → glob-GUGGTH5L.js} +45 -39
  205. package/chunks/{goal-tools-DABMICUC.js → goal-tools-PXYRSQGX.js} +42 -36
  206. package/chunks/{grep-BLHF2S5D.js → grep-3PKFKLCA.js} +2 -2
  207. package/chunks/{handleAutoUpdate-MCAMHYDI.js → handleAutoUpdate-5KHS4HIN.js} +60 -53
  208. package/chunks/{i18n-C3GDCALP.js → i18n-KSGKMUPT.js} +58 -51
  209. package/chunks/{image-gen-XP4NNIYG.js → image-gen-OCCR2WWU.js} +5 -4
  210. package/chunks/{initializer-4URDQL2G.js → initializer-YYT5XEZF.js} +64 -57
  211. package/chunks/{installationInfo-LBOL6SBV.js → installationInfo-UNSBPYW2.js} +57 -50
  212. package/chunks/{list-JOGBAC2R.js → list-YL6LDQKQ.js} +67 -60
  213. package/chunks/{list-agents-2CXPGJUE.js → list-agents-QLDXS5OD.js} +17 -7
  214. package/chunks/{llm-2KPNSAVY.js → llm-XGGLBGPH.js} +126 -119
  215. package/chunks/{llm-content-generator-GR3FOHLB.js → llm-content-generator-ZHQQT5W7.js} +5 -4
  216. package/chunks/{loadedSettingsAdapter-DVKROEJD.js → loadedSettingsAdapter-3DXLASK7.js} +64 -57
  217. package/chunks/{loggingContentGenerator-P4K6K5W4.js → loggingContentGenerator-V72OCCJO.js} +64 -57
  218. package/chunks/{loop-wakeup-HL6XOWI4.js → loop-wakeup-HHMYIC7Z.js} +2 -2
  219. package/chunks/{ls-YV7RKLKY.js → ls-N7ABR6HI.js} +4 -4
  220. package/chunks/{lsp-NO3AMRZT.js → lsp-LTOFWG5P.js} +1 -1
  221. package/chunks/{managed-npm-update-VWBKHNIN.js → managed-npm-update-HV5LPZH2.js} +57 -50
  222. package/chunks/{mcp-6YYNSYLK.js → mcp-IYVSIW6O.js} +64 -57
  223. package/chunks/{monitor-A255TNZR.js → monitor-TLBNM4MV.js} +44 -38
  224. package/chunks/{nonInteractiveCli-LXGIKQAT.js → nonInteractiveCli-LSJSQ2W4.js} +110 -103
  225. package/chunks/{notebook-edit-5UYHS2DM.js → notebook-edit-OSPOLZP6.js} +43 -37
  226. package/chunks/openai-WX26N5OJ.js +47 -0
  227. package/chunks/{openaiContentGenerator-A6MAMEO5.js → openaiContentGenerator-BE4S5TRD.js} +29 -23
  228. package/chunks/openaiResponsesContentGenerator-RTCAJ5V5.js +1658 -0
  229. package/chunks/{pidfile-B7DZC4TP.js → pidfile-H32FEPWA.js} +57 -50
  230. package/chunks/process-registry-X6ZCASEN.js +10 -0
  231. package/chunks/{processUtils-BPZ2MCZS.js → processUtils-SSLIPDEA.js} +2 -2
  232. package/chunks/{prompt-terminal-ledger-FYYTAOXS.js → prompt-terminal-ledger-I5SLL6UF.js} +58 -51
  233. package/chunks/{qwenContentGenerator-4IOJFD4S.js → qwenContentGenerator-TMQC623Z.js} +55 -47
  234. package/chunks/{qwenOAuth2-KX6LVYQ3.js → qwenOAuth2-3ZRQHHTC.js} +4 -3
  235. package/chunks/{read-file-A4H4O3VQ.js → read-file-T2QAIZE2.js} +11 -9
  236. package/chunks/{read-mcp-resource-D3N75DGF.js → read-mcp-resource-B37WANAQ.js} +1 -1
  237. package/chunks/{record-artifact-Q5CRGJTP.js → record-artifact-OAXWXZ5D.js} +2 -2
  238. package/chunks/record-source-D7R7X3GT.js +22 -0
  239. package/chunks/{report-findings-TJ34R7QK.js → report-findings-AR3VC6EQ.js} +3 -3
  240. package/chunks/{request-shutdown-LRKMTBAD.js → request-shutdown-IKNWTX5M.js} +5 -5
  241. package/chunks/{resumeHistoryUtils-YQQ43E4N.js → resumeHistoryUtils-QLKDH5GY.js} +63 -56
  242. package/chunks/{ripGrep-W32NWFTA.js → ripGrep-YGWL7KCV.js} +15 -13
  243. package/chunks/{run-qwen-serve-WBSWWIRV.js → run-qwen-serve-26KZDECC.js} +127 -102
  244. package/chunks/{runtime-VRVBX2E5.js → runtime-BMEIVDDG.js} +70 -63
  245. package/chunks/{scheduled-tasks-D65KJDA3.js → scheduled-tasks-NCFPP6VQ.js} +64 -57
  246. package/chunks/{scheduler-M2YPN7Z7.js → scheduler-47TVMUVN.js} +59 -52
  247. package/chunks/{sdk-exporters-grpc-MXTVSE3C.js → sdk-exporters-grpc-Y2ZUQDUQ.js} +2 -2
  248. package/chunks/{sdk-exporters-http-7R2ARBPV.js → sdk-exporters-http-VWTF4W6K.js} +3 -3
  249. package/chunks/{sdk-impl-YOLO7LV4.js → sdk-impl-G6FVTBQZ.js} +9 -9
  250. package/chunks/{send-message-76BKWKFZ.js → send-message-TWOGWCBG.js} +12 -9
  251. package/chunks/{serve-BE3H2P6P.js → serve-KL3G6LQQ.js} +64 -57
  252. package/chunks/{server-FLY5JERG.js → server-LBPYXZ5G.js} +2931 -518
  253. package/chunks/{session-JVN62R5K.js → session-YG6742LO.js} +118 -111
  254. package/chunks/{session-attachments-root-7ACGLHXA.js → session-attachments-root-OUBQDYC4.js} +57 -50
  255. package/chunks/{session-pr-refresh-TQS57SDK.js → session-pr-refresh-EKGMYNAW.js} +64 -57
  256. package/chunks/{settings-D44YMZFT.js → settings-DDNHJX2L.js} +69 -62
  257. package/chunks/{shell-3VE6I4V5.js → shell-KUCXWITU.js} +42 -36
  258. package/chunks/{skill-FHEGRRZU.js → skill-JQLKPNWZ.js} +33 -23
  259. package/chunks/{skill-settings-VHEJMBFL.js → skill-settings-XERQCUXZ.js} +63 -56
  260. package/chunks/{spawnChannel-T6MX2ZDN.js → spawnChannel-GQ45QFGB.js} +60 -53
  261. package/chunks/{standalone-update-QUGHFMCS.js → standalone-update-PRF3ILGZ.js} +59 -52
  262. package/chunks/{start-opentui-ui-IHIIZ2LE.js → start-opentui-ui-JDSOZE3N.js} +174 -157
  263. package/chunks/{startInteractiveUI-LR7K2ARZ.js → startInteractiveUI-RRW3JVHN.js} +533 -1119
  264. package/chunks/{syntheticOutput-D2P5V6RG.js → syntheticOutput-F6F27JMK.js} +2 -2
  265. package/chunks/{task-create-MWXJFRRM.js → task-create-Y623TBHB.js} +8 -8
  266. package/chunks/{task-list-EYO3FE57.js → task-list-FCPEEGWL.js} +1 -1
  267. package/chunks/{task-stop-BFSKRTGV.js → task-stop-QTKZXLPH.js} +1 -1
  268. package/chunks/{task-update-2JJJRHMT.js → task-update-YLSXF25N.js} +8 -8
  269. package/chunks/{team-create-GY3VFY47.js → team-create-5DRLOLOE.js} +44 -38
  270. package/chunks/{team-delete-IQZ6XGFI.js → team-delete-S7TLHZCF.js} +1 -1
  271. package/chunks/{team-plan-approval-BQPGZOT5.js → team-plan-approval-MWSGAL5T.js} +42 -36
  272. package/chunks/{terminal-image-renderer-YNYW5CQG.js → terminal-image-renderer-H7PD4FQW.js} +59 -52
  273. package/chunks/{theme-manager-U6CIK3GM.js → theme-manager-7AV73D6R.js} +57 -50
  274. package/chunks/{todoWrite-5ERKFWAK.js → todoWrite-5QI2H2FW.js} +4 -4
  275. package/chunks/{tool-search-XI3QWD5I.js → tool-search-UGYTBLUV.js} +17 -15
  276. package/chunks/{total-session-admission-3SNSJJ32.js → total-session-admission-JIHSTJ5S.js} +62 -55
  277. package/chunks/{trustedFolders-OVAQKNV5.js → trustedFolders-5VCBXFOP.js} +58 -51
  278. package/chunks/{update-relaunch-XV5O74E3.js → update-relaunch-4LF3APCV.js} +5 -5
  279. package/chunks/{updateCheck-CHUYWD6L.js → updateCheck-4T3WUE5F.js} +59 -52
  280. package/chunks/{useAutoAcceptIndicator-VKSVIXZC.js → useAutoAcceptIndicator-UMGB64Z6.js} +67 -60
  281. package/chunks/{validateNonInterActiveAuth-ZNUTD3E5.js → validateNonInterActiveAuth-GFJ72U2C.js} +107 -100
  282. package/chunks/{version-EK7VAGSI.js → version-EAAZN4T2.js} +1 -1
  283. package/chunks/{web-fetch-24KZO763.js → web-fetch-VRU3A2NI.js} +13 -11
  284. package/chunks/{web-search-CRNXKZ2X.js → web-search-NEGYQNDJ.js} +14 -10
  285. package/chunks/{web-shell-static-BFDESDD4.js → web-shell-static-CCN4JZEE.js} +1 -1
  286. package/chunks/workflow-UHPFALVZ.js +1224 -0
  287. package/chunks/{workspace-providers-status-MAM42IZS.js → workspace-providers-status-AEYISSU2.js} +68 -61
  288. package/chunks/{workspace-registration-store-HKLJEDQX.js → workspace-registration-store-A7RGKW62.js} +3 -1
  289. package/chunks/{workspace-registry-7RDDOBLN.js → workspace-registry-C2NGE6SD.js} +62 -55
  290. package/chunks/{workspace-runtime-coordinator-LEPDPXJO.js → workspace-runtime-coordinator-QKMZ24YF.js} +63 -56
  291. package/chunks/{workspace-service-5IFDCNN3.js → workspace-service-RQTTAGGC.js} +70 -63
  292. package/chunks/{workspace-skills-status-FJ3HNH4H.js → workspace-skills-status-5HWZU3HX.js} +65 -58
  293. package/chunks/{workspace-trust-reconciler-PQFHIWLR.js → workspace-trust-reconciler-KFWATZUU.js} +69 -62
  294. package/chunks/{write-file-ERG67ZFX.js → write-file-DPVB2SBQ.js} +44 -38
  295. package/chunks/{zh-VBFCRQBL.js → zh-S5V3Z5CR.js} +1 -0
  296. package/chunks/{zh-TW-N2TBF2F2.js → zh-TW-2K2WRFPY.js} +1 -0
  297. package/chunks/{zoom-image-WQYEC3SR.js → zoom-image-S7AWLAPC.js} +12 -10
  298. package/cli.js +13 -13
  299. package/export-transcript-document.css +1 -0
  300. package/export-transcript-document.js +164 -165
  301. package/locales/en.js +1 -0
  302. package/locales/zh-TW.js +1 -0
  303. package/locales/zh.js +1 -0
  304. package/package.json +5 -4
  305. package/web-shell/assets/{abnfDiagram-VCTEODGH-BRLgQbnT.js → abnfDiagram-VCTEODGH-nU24rpIE.js} +1 -1
  306. package/web-shell/assets/{arc-qAF9_XsR.js → arc-D1hTu8QI.js} +1 -1
  307. package/web-shell/assets/{architectureDiagram-5GKGNRK7-BorUttEz.js → architectureDiagram-5GKGNRK7-B_fgkKe7.js} +1 -1
  308. package/web-shell/assets/{blockDiagram-NRAW4CY4-Bj0qZVxu.js → blockDiagram-NRAW4CY4-C3pddUNg.js} +1 -1
  309. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BTqJis32.js → c4Diagram-UCG6FXSJ-kEFoC1ei.js} +1 -1
  310. package/web-shell/assets/channel-Blod4z1X.js +1 -0
  311. package/web-shell/assets/{chunk-2Q5K7J3B-RrQ5X8m-.js → chunk-2Q5K7J3B-DbT9wS7j.js} +1 -1
  312. package/web-shell/assets/{chunk-5VM5RSS4-uUjDl8wO.js → chunk-5VM5RSS4-CNbULt6O.js} +1 -1
  313. package/web-shell/assets/{chunk-F27PBJKO-C3JhpyzI.js → chunk-F27PBJKO-CbQRy4Tb.js} +1 -1
  314. package/web-shell/assets/{chunk-G27WJ6UU-C8ZNFs7F.js → chunk-G27WJ6UU-CVbXTxYk.js} +1 -1
  315. package/web-shell/assets/{chunk-JWPE2WC7-DNpXtEOs.js → chunk-JWPE2WC7-D89c_BXy.js} +1 -1
  316. package/web-shell/assets/{chunk-LCL6LL3I-DagA2ZLw.js → chunk-LCL6LL3I-B7-I_9KB.js} +1 -1
  317. package/web-shell/assets/{chunk-POPQ4Y6H-R23uH7Xm.js → chunk-POPQ4Y6H-DcLQFzS4.js} +1 -1
  318. package/web-shell/assets/{chunk-SVP7TREG-Qz9RN_BR.js → chunk-SVP7TREG-DyBb2Axj.js} +1 -1
  319. package/web-shell/assets/{chunk-XXDRQBXY-jYb1_hni.js → chunk-XXDRQBXY-BIA0eb5B.js} +1 -1
  320. package/web-shell/assets/classDiagram-DTDB5LWJ-D6hFDMqb.js +1 -0
  321. package/web-shell/assets/classDiagram-v2-JRS7N3AN-D6hFDMqb.js +1 -0
  322. package/web-shell/assets/{cose-bilkent-JH36ORCC-Cv2OunpE.js → cose-bilkent-JH36ORCC-Db2FYN85.js} +1 -1
  323. package/web-shell/assets/{cynefin-OW5HDTMX-LH42KFJx.js → cynefin-OW5HDTMX-i4GwmBVy.js} +1 -1
  324. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Dha4_OoR.js → cynefinDiagram-5FMLGOSQ-LENf_IUy.js} +1 -1
  325. package/web-shell/assets/{dagre-3AP2YEHR-Br5lnUKD.js → dagre-3AP2YEHR-CF9XVrD9.js} +1 -1
  326. package/web-shell/assets/{diagram-S7CK7UJ4-dpKq2bBX.js → diagram-S7CK7UJ4-DD5PJfSm.js} +1 -1
  327. package/web-shell/assets/{diagram-UQ7AKVKN-BAgHWpXr.js → diagram-UQ7AKVKN-CjD_sBMj.js} +1 -1
  328. package/web-shell/assets/{diagram-VSXAHHWV-GRRzpyE2.js → diagram-VSXAHHWV-U5WwMqyA.js} +1 -1
  329. package/web-shell/assets/{diagram-VX7I27RA-BNFiaYpG.js → diagram-VX7I27RA-BujpHJJf.js} +1 -1
  330. package/web-shell/assets/{diagram-Z3DM3KII-BisZzB_h.js → diagram-Z3DM3KII-3ZLtKEXo.js} +1 -1
  331. package/web-shell/assets/{ebnfDiagram-PWID7BFC-B1xbwycf.js → ebnfDiagram-PWID7BFC-BGpiquRm.js} +1 -1
  332. package/web-shell/assets/{erDiagram-SSCWMZ5O-CQMzbGE5.js → erDiagram-SSCWMZ5O-D0besu_U.js} +1 -1
  333. package/web-shell/assets/{flowDiagram-A5DVABFB-CZ_Zondl.js → flowDiagram-A5DVABFB-9DwDuIyr.js} +1 -1
  334. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-BTh2ShxS.js → ganttDiagram-EL5Y4UJY-CNlsAeNr.js} +1 -1
  335. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-oHOB-Uxt.js → gitGraphDiagram-WWUBYQGX-C_pPFiTR.js} +1 -1
  336. package/web-shell/assets/{index-DWoFMu5x.js → index-BYWs4JWq.js} +1 -1
  337. package/web-shell/assets/index-D3YS6KuJ.js +2173 -0
  338. package/web-shell/assets/index-eBxK3rs2.css +36 -0
  339. package/web-shell/assets/{infoDiagram-RXCK75RN-C0QpudbG.js → infoDiagram-RXCK75RN-Bpai64Ll.js} +1 -1
  340. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-a6B741uT.js → ishikawaDiagram-5VMMS53U-ktpJFq4r.js} +1 -1
  341. package/web-shell/assets/{journeyDiagram-EYS64GPL-Dbht9ICp.js → journeyDiagram-EYS64GPL-iz_DKgFX.js} +1 -1
  342. package/web-shell/assets/{kanban-definition-3QL26DDD-D4OFR8-h.js → kanban-definition-3QL26DDD-m_gG00Yt.js} +1 -1
  343. package/web-shell/assets/{layout-Dvdh5jRH.js → layout-qEvKgnvU.js} +1 -1
  344. package/web-shell/assets/{linear-Dvc6KIW2.js → linear-C6lklGdq.js} +1 -1
  345. package/web-shell/assets/{mermaid.core-CB36RfIb.js → mermaid.core-DSCYB_2P.js} +6 -6
  346. package/web-shell/assets/{mindmap-definition-FBJOCRG2-Fmqo1CjP.js → mindmap-definition-FBJOCRG2-DRQbT8w-.js} +1 -1
  347. package/web-shell/assets/{pegDiagram-XKGWAZYB-CCxYBoA4.js → pegDiagram-XKGWAZYB-BhD0q0i6.js} +1 -1
  348. package/web-shell/assets/{pieDiagram-E7YTZNPT-BVHKQFzt.js → pieDiagram-E7YTZNPT-BvIGQCSd.js} +1 -1
  349. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-l95IznwR.js → quadrantDiagram-AXDQQJYC-BDQtfpU-.js} +1 -1
  350. package/web-shell/assets/{railroadDiagram-O6MQD6OU-BlLdRdXp.js → railroadDiagram-O6MQD6OU-E1g2KIFK.js} +1 -1
  351. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-BkDLBR5w.js → requirementDiagram-EFPCY7ZU-CuerYJOe.js} +1 -1
  352. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-jAIqRp65.js → sankeyDiagram-P5KCCOFB-CqWyCZGA.js} +1 -1
  353. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-f-soZYPr.js → sequenceDiagram-WJ2MYXX4-B-YWb8x4.js} +1 -1
  354. package/web-shell/assets/{sizeCapture-X5ZJPWSS-BzOuAfB2.js → sizeCapture-X5ZJPWSS-BB7YY4Tl.js} +1 -1
  355. package/web-shell/assets/{stateDiagram-HBIQ2CUA-BPLSs12r.js → stateDiagram-HBIQ2CUA-C8LDpNHS.js} +1 -1
  356. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-C4CbdvGa.js +1 -0
  357. package/web-shell/assets/{swimlanes-XN3QIQJK-D-9E_RIR.js → swimlanes-XN3QIQJK-D94vOoxZ.js} +1 -1
  358. package/web-shell/assets/swimlanesDiagram-VK2B7HYN--QNSIOC8.js +8 -0
  359. package/web-shell/assets/{timeline-definition-24CTP7MA-CT56K-gV.js → timeline-definition-24CTP7MA-C9C8uEYm.js} +1 -1
  360. package/web-shell/assets/{vennDiagram-4TSXK5OY-B-vi4IyO.js → vennDiagram-4TSXK5OY-CYzMHbVW.js} +1 -1
  361. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-C9O7Ju98.js → wardleyDiagram-VM6X3IG4-G9nhtLES.js} +1 -1
  362. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-6d8w3jg2.js → xychartDiagram-S5SC5T6Z-ruD2Wjhg.js} +1 -1
  363. package/web-shell/index.html +29 -5
  364. package/chunks/chunk-V7RNNPGC.js +0 -44
  365. package/chunks/workflow-HD5NYMW5.js +0 -2907
  366. package/web-shell/assets/channel-COIuCrVH.js +0 -1
  367. package/web-shell/assets/classDiagram-DTDB5LWJ-DoX6OYqu.js +0 -1
  368. package/web-shell/assets/classDiagram-v2-JRS7N3AN-DoX6OYqu.js +0 -1
  369. package/web-shell/assets/index-CI1ysIEv.js +0 -2154
  370. package/web-shell/assets/index-CpxXGH-8.css +0 -36
  371. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-IRul-LaT.js +0 -1
  372. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-D6lgKepA.js +0 -8
  373. /package/chunks/{chunk-JA5CBKRP.js → chunk-7NXSVSFB.js} +0 -0
@@ -1,16 +1,50 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
3
  import {
4
+ AgentEventEmitter,
5
+ attachJsonlTranscriptWriter,
6
+ buildAgentTranscriptAttach,
7
+ deriveApprovalModeConfig,
8
+ deriveConfig,
9
+ deriveWorktreeConfig,
10
+ installSessionWorkflowRevisionWriteThrough,
4
11
  isActiveWorkflowStatus,
5
12
  isTerminalWorkflowStatus,
6
- isWorkflowRunPersistenceActive
7
- } from "./chunk-HJ5UJQQL.js";
13
+ isWorkflowRunPersistenceActive,
14
+ rebuildToolRegistryOnOverride,
15
+ resolveExternalWorktreeDir,
16
+ toModelVisibleSubagentResult
17
+ } from "./chunk-N7VWZDWW.js";
18
+ import {
19
+ GitWorktreeService,
20
+ generateAgentWorktreeSlug,
21
+ writeWorktreeSessionMarker
22
+ } from "./chunk-36HCNKDS.js";
23
+ import {
24
+ parsePositiveIntegerEnv
25
+ } from "./chunk-6PVPNMXU.js";
26
+ import {
27
+ SUBAGENT_PLAN_LIFECYCLE_TOOLS
28
+ } from "./chunk-PLLIWEM3.js";
29
+ import {
30
+ runWithAgentContext
31
+ } from "./chunk-U7O65WKL.js";
32
+ import {
33
+ read,
34
+ writeLine
35
+ } from "./chunk-HBU7EKY4.js";
8
36
  import {
9
37
  atomicWriteFile
10
38
  } from "./chunk-XFFRI3WM.js";
11
39
  import {
12
40
  stripAnsiAndControl
13
- } from "./chunk-7VEYUF3N.js";
41
+ } from "./chunk-W5ZQMAEM.js";
42
+ import {
43
+ SyntheticOutputTool
44
+ } from "./chunk-HUXPEUFL.js";
45
+ import {
46
+ ToolNames
47
+ } from "./chunk-TP6FYVQT.js";
14
48
  import {
15
49
  Storage,
16
50
  createDebugLogger
@@ -1612,11 +1646,271 @@ function createWorkflowSandbox(opts) {
1612
1646
  }
1613
1647
  __name(createWorkflowSandbox, "createWorkflowSandbox");
1614
1648
 
1649
+ // packages/core/src/agents/runtime/workflow-budget.ts
1650
+ init_esbuild_shims();
1651
+ var debugLogger2 = createDebugLogger("WORKFLOW_BUDGET");
1652
+ var MAX_TOKENS_PER_WORKFLOW_ENV = "QWEN_CODE_MAX_TOKENS_PER_WORKFLOW";
1653
+ var HARD_MAX_TOKENS_CEILING = 1e8;
1654
+ function resolveMaxTokensPerWorkflow(env = process.env) {
1655
+ const raw = env[MAX_TOKENS_PER_WORKFLOW_ENV];
1656
+ if (raw === void 0 || raw.trim() === "") {
1657
+ return null;
1658
+ }
1659
+ const parsed = parsePositiveIntegerEnv(raw, 0);
1660
+ if (parsed < 1) {
1661
+ debugLogger2.warn(
1662
+ `Invalid ${MAX_TOKENS_PER_WORKFLOW_ENV}=${JSON.stringify(raw)}, treating as unset (no cap)`
1663
+ );
1664
+ return null;
1665
+ }
1666
+ if (parsed > HARD_MAX_TOKENS_CEILING) {
1667
+ debugLogger2.warn(
1668
+ `${MAX_TOKENS_PER_WORKFLOW_ENV}=${parsed} exceeds hard ceiling (${HARD_MAX_TOKENS_CEILING}); clamping.`
1669
+ );
1670
+ return HARD_MAX_TOKENS_CEILING;
1671
+ }
1672
+ return parsed;
1673
+ }
1674
+ __name(resolveMaxTokensPerWorkflow, "resolveMaxTokensPerWorkflow");
1675
+ var WorkflowBudgetImpl = class _WorkflowBudgetImpl {
1676
+ static {
1677
+ __name(this, "WorkflowBudgetImpl");
1678
+ }
1679
+ total;
1680
+ _spent;
1681
+ constructor(total) {
1682
+ this.total = total;
1683
+ this._spent = 0;
1684
+ }
1685
+ spent() {
1686
+ return this._spent;
1687
+ }
1688
+ remaining() {
1689
+ if (this.total === null) return Infinity;
1690
+ return Math.max(0, this.total - this._spent);
1691
+ }
1692
+ /**
1693
+ * Host-side increment. NOT exposed to the script — the
1694
+ * `WorkflowBudget` interface deliberately omits any setter so a
1695
+ * malicious workflow cannot inflate / deflate the budget. Only the
1696
+ * orchestrator (in `countedDispatch`) calls this after a dispatch
1697
+ * resolves with the agent's output token count.
1698
+ *
1699
+ * Non-positive deltas are silently dropped (some dispatches return
1700
+ * `output_tokens: 0` on early failures); negative deltas would be a
1701
+ * caller bug and are also dropped rather than silently rewinding
1702
+ * the counter.
1703
+ */
1704
+ recordSpent(deltaTokens) {
1705
+ if (!Number.isFinite(deltaTokens) || deltaTokens <= 0) return;
1706
+ this._spent += deltaTokens;
1707
+ }
1708
+ /**
1709
+ * Factory: build a budget from the current environment. Convenience
1710
+ * over `new WorkflowBudgetImpl(resolveMaxTokensPerWorkflow(env))`.
1711
+ */
1712
+ static fromEnv(env = process.env) {
1713
+ return new _WorkflowBudgetImpl(resolveMaxTokensPerWorkflow(env));
1714
+ }
1715
+ };
1716
+ var WorkflowBudgetExceededError = class extends Error {
1717
+ static {
1718
+ __name(this, "WorkflowBudgetExceededError");
1719
+ }
1720
+ name = "WorkflowBudgetExceededError";
1721
+ runId;
1722
+ budgetTotal;
1723
+ spent;
1724
+ constructor(runId, budgetTotal, spent) {
1725
+ super(
1726
+ `Workflow ${runId} exceeded the token budget (${spent} / ${budgetTotal} output tokens spent).`
1727
+ );
1728
+ this.runId = runId;
1729
+ this.budgetTotal = budgetTotal;
1730
+ this.spent = spent;
1731
+ }
1732
+ };
1733
+
1734
+ // packages/core/src/agents/runtime/workflow-stall.ts
1735
+ init_esbuild_shims();
1736
+
1737
+ // packages/core/src/agents/runtime/workflow-agent-failure.ts
1738
+ init_esbuild_shims();
1739
+ var WorkflowAgentFailedError = class extends Error {
1740
+ static {
1741
+ __name(this, "WorkflowAgentFailedError");
1742
+ }
1743
+ name = "WorkflowAgentFailedError";
1744
+ kind;
1745
+ terminateMode;
1746
+ constructor(message, kind, terminateMode) {
1747
+ super(message);
1748
+ this.kind = kind;
1749
+ this.terminateMode = terminateMode;
1750
+ }
1751
+ };
1752
+ function isWorkflowAgentFailedError(error) {
1753
+ return typeof error === "object" && error !== null && error.name === "WorkflowAgentFailedError";
1754
+ }
1755
+ __name(isWorkflowAgentFailedError, "isWorkflowAgentFailedError");
1756
+ var WorkflowAgentCapExceededError = class extends Error {
1757
+ static {
1758
+ __name(this, "WorkflowAgentCapExceededError");
1759
+ }
1760
+ name = "WorkflowAgentCapExceededError";
1761
+ constructor(maxAgents) {
1762
+ super(
1763
+ `Workflow exceeded the maximum of ${maxAgents} agent() calls per run.`
1764
+ );
1765
+ }
1766
+ };
1767
+ function isWorkflowRunLevelError(error) {
1768
+ if (typeof error !== "object" || error === null) return false;
1769
+ const name = error.name;
1770
+ return name === "WorkflowBudgetExceededError" || name === "WorkflowAgentCapExceededError";
1771
+ }
1772
+ __name(isWorkflowRunLevelError, "isWorkflowRunLevelError");
1773
+ var WORKFLOW_ABORT_REASON_STALLED = "stalled";
1774
+
1775
+ // packages/core/src/agents/runtime/workflow-stall.ts
1776
+ var DEFAULT_STALL_MS = 18e4;
1777
+ var MAX_STALL_ATTEMPTS = 3;
1778
+ var MAX_WORKFLOW_STALL_MS_ENV = "QWEN_CODE_WORKFLOW_STALL_SECONDS";
1779
+ function resolveStallMs(perCall, env = process.env) {
1780
+ if (typeof perCall === "number" && Number.isFinite(perCall)) {
1781
+ if (perCall === 0) return 0;
1782
+ if (perCall > 0) return perCall;
1783
+ }
1784
+ const raw = env[MAX_WORKFLOW_STALL_MS_ENV];
1785
+ const trimmed = raw?.trim();
1786
+ if (trimmed) {
1787
+ if (trimmed === "0") return 0;
1788
+ const sec = parsePositiveIntegerEnv(trimmed, 0);
1789
+ if (sec > 0) return sec * 1e3;
1790
+ }
1791
+ return DEFAULT_STALL_MS;
1792
+ }
1793
+ __name(resolveStallMs, "resolveStallMs");
1794
+ var debugLogger3 = createDebugLogger("WORKFLOW_STALL");
1795
+ function attachStallWatchdog(emitter, controller, stallMs) {
1796
+ if (stallMs <= 0) {
1797
+ return { stalled: /* @__PURE__ */ __name(() => false, "stalled"), dispose: /* @__PURE__ */ __name(() => {
1798
+ }, "dispose") };
1799
+ }
1800
+ let inFlightTools = 0;
1801
+ let fired = false;
1802
+ let timer;
1803
+ let disposed = false;
1804
+ const clear = /* @__PURE__ */ __name(() => {
1805
+ if (timer) {
1806
+ clearTimeout(timer);
1807
+ timer = void 0;
1808
+ }
1809
+ }, "clear");
1810
+ const arm = /* @__PURE__ */ __name(() => {
1811
+ clear();
1812
+ if (disposed || fired) return;
1813
+ if (inFlightTools > 0) return;
1814
+ timer = setTimeout(() => {
1815
+ if (disposed || fired) return;
1816
+ fired = true;
1817
+ debugLogger3.warn(
1818
+ `[Workflow] agent dispatch stalled \u2014 no progress for ${stallMs}ms; aborting.`
1819
+ );
1820
+ try {
1821
+ controller.abort(WORKFLOW_ABORT_REASON_STALLED);
1822
+ } catch (e) {
1823
+ debugLogger3.warn("stall watchdog abort threw:", e);
1824
+ }
1825
+ }, stallMs);
1826
+ if (typeof timer.unref === "function") {
1827
+ timer.unref();
1828
+ }
1829
+ }, "arm");
1830
+ const onActivity = /* @__PURE__ */ __name(() => arm(), "onActivity");
1831
+ const onToolCall = /* @__PURE__ */ __name(() => {
1832
+ inFlightTools += 1;
1833
+ clear();
1834
+ }, "onToolCall");
1835
+ const onToolResult = /* @__PURE__ */ __name(() => {
1836
+ inFlightTools = Math.max(0, inFlightTools - 1);
1837
+ arm();
1838
+ }, "onToolResult");
1839
+ emitter.on("round_start" /* ROUND_START */, onActivity);
1840
+ emitter.on("round_end" /* ROUND_END */, onActivity);
1841
+ emitter.on("stream_text" /* STREAM_TEXT */, onActivity);
1842
+ emitter.on("usage_metadata" /* USAGE_METADATA */, onActivity);
1843
+ emitter.on("tool_call" /* TOOL_CALL */, onToolCall);
1844
+ emitter.on("tool_result" /* TOOL_RESULT */, onToolResult);
1845
+ return {
1846
+ stalled: /* @__PURE__ */ __name(() => fired, "stalled"),
1847
+ dispose: /* @__PURE__ */ __name(() => {
1848
+ if (disposed) return;
1849
+ disposed = true;
1850
+ clear();
1851
+ emitter.off("round_start" /* ROUND_START */, onActivity);
1852
+ emitter.off("round_end" /* ROUND_END */, onActivity);
1853
+ emitter.off("stream_text" /* STREAM_TEXT */, onActivity);
1854
+ emitter.off("usage_metadata" /* USAGE_METADATA */, onActivity);
1855
+ emitter.off("tool_call" /* TOOL_CALL */, onToolCall);
1856
+ emitter.off("tool_result" /* TOOL_RESULT */, onToolResult);
1857
+ }, "dispose")
1858
+ };
1859
+ }
1860
+ __name(attachStallWatchdog, "attachStallWatchdog");
1861
+ async function runStallResilient(attemptFn, opts) {
1862
+ const { stallMs, signal, label } = opts;
1863
+ if (stallMs <= 0) {
1864
+ const emitter = new AgentEventEmitter();
1865
+ return attemptFn(signal ?? new AbortController().signal, emitter);
1866
+ }
1867
+ let attempt = 0;
1868
+ for (; ; ) {
1869
+ attempt += 1;
1870
+ const controller = new AbortController();
1871
+ let onParentAbort;
1872
+ if (signal) {
1873
+ if (signal.aborted) {
1874
+ controller.abort(signal.reason);
1875
+ } else {
1876
+ onParentAbort = /* @__PURE__ */ __name(() => controller.abort(signal.reason), "onParentAbort");
1877
+ signal.addEventListener("abort", onParentAbort);
1878
+ }
1879
+ }
1880
+ const emitter = new AgentEventEmitter();
1881
+ const watchdog = attachStallWatchdog(emitter, controller, stallMs);
1882
+ try {
1883
+ return await attemptFn(controller.signal, emitter);
1884
+ } catch (err) {
1885
+ if (signal?.aborted) throw err;
1886
+ if (watchdog.stalled() && attempt < MAX_STALL_ATTEMPTS) {
1887
+ debugLogger3.warn(
1888
+ `[Workflow] agent "${label ?? "workflow-agent"}" stalled (attempt ${attempt}/${MAX_STALL_ATTEMPTS}) \u2014 retrying.`
1889
+ );
1890
+ continue;
1891
+ }
1892
+ if (watchdog.stalled()) {
1893
+ throw new WorkflowAgentFailedError(
1894
+ `agent "${label ?? "workflow-agent"}" stalled on all ${MAX_STALL_ATTEMPTS} attempts (no progress for ${stallMs}ms each).`,
1895
+ "stalled"
1896
+ );
1897
+ }
1898
+ throw err;
1899
+ } finally {
1900
+ watchdog.dispose();
1901
+ if (onParentAbort && signal) {
1902
+ signal.removeEventListener("abort", onParentAbort);
1903
+ }
1904
+ }
1905
+ }
1906
+ }
1907
+ __name(runStallResilient, "runStallResilient");
1908
+
1615
1909
  // packages/core/src/agents/runtime/workflow-saved.ts
1616
1910
  init_esbuild_shims();
1617
1911
  import { promises as fs } from "node:fs";
1618
1912
  import * as path from "node:path";
1619
- var debugLogger2 = createDebugLogger("WORKFLOW_SAVED");
1913
+ var debugLogger4 = createDebugLogger("WORKFLOW_SAVED");
1620
1914
  var WORKFLOW_NAME_PATTERN = /^[a-z][a-z0-9-]{0,40}$/;
1621
1915
  function validateWorkflowName(name) {
1622
1916
  if (!name) return "Workflow name is required.";
@@ -1646,7 +1940,7 @@ async function isSymlinkedRoot(dir) {
1646
1940
  __name(isSymlinkedRoot, "isSymlinkedRoot");
1647
1941
  async function listJsFiles(dir) {
1648
1942
  if (await isSymlinkedRoot(dir)) {
1649
- debugLogger2.warn(`refusing symlinked saved-workflow dir: ${dir}`);
1943
+ debugLogger4.warn(`refusing symlinked saved-workflow dir: ${dir}`);
1650
1944
  return [];
1651
1945
  }
1652
1946
  try {
@@ -1662,7 +1956,7 @@ async function listJsFiles(dir) {
1662
1956
  } catch (e) {
1663
1957
  const code = e?.code;
1664
1958
  if (code !== "ENOENT") {
1665
- debugLogger2.warn(`listJsFiles failed for ${dir}: ${e}`);
1959
+ debugLogger4.warn(`listJsFiles failed for ${dir}: ${e}`);
1666
1960
  }
1667
1961
  return [];
1668
1962
  }
@@ -1809,7 +2103,7 @@ __name(saveWorkflowScript, "saveWorkflowScript");
1809
2103
  var INLINE_RUN_ID_PATTERN = /^wf_[0-9a-f]+$/;
1810
2104
  async function persistInlineWorkflowScript(config, runId, script) {
1811
2105
  if (!INLINE_RUN_ID_PATTERN.test(runId)) {
1812
- debugLogger2.warn(`refusing to persist a script for run id: ${runId}`);
2106
+ debugLogger4.warn(`refusing to persist a script for run id: ${runId}`);
1813
2107
  return null;
1814
2108
  }
1815
2109
  const storage = config.storage;
@@ -1818,7 +2112,7 @@ async function persistInlineWorkflowScript(config, runId, script) {
1818
2112
  const filePath = storage.getInlineWorkflowScriptPath(runId);
1819
2113
  const dir = path.dirname(filePath);
1820
2114
  if (await isSymlinkedRoot(storage.getGeneratedWorkflowsDir()) || await isSymlinkedRoot(dir)) {
1821
- debugLogger2.warn(
2115
+ debugLogger4.warn(
1822
2116
  `refusing to persist an inline workflow script into a symlinked root: '${dir}'.`
1823
2117
  );
1824
2118
  return null;
@@ -1832,7 +2126,7 @@ async function persistInlineWorkflowScript(config, runId, script) {
1832
2126
  });
1833
2127
  return filePath;
1834
2128
  } catch (error) {
1835
- debugLogger2.warn(
2129
+ debugLogger4.warn(
1836
2130
  `failed to persist inline workflow script for ${runId}: ${error}`
1837
2131
  );
1838
2132
  return null;
@@ -1847,7 +2141,7 @@ async function deleteInlineWorkflowScript(config, runId) {
1847
2141
  await fs.rm(storage.getInlineWorkflowScriptPath(runId), { force: true });
1848
2142
  return true;
1849
2143
  } catch (error) {
1850
- debugLogger2.warn(
2144
+ debugLogger4.warn(
1851
2145
  `failed to delete inline workflow script for ${runId}: ${error}`
1852
2146
  );
1853
2147
  return false;
@@ -1855,11 +2149,1452 @@ async function deleteInlineWorkflowScript(config, runId) {
1855
2149
  }
1856
2150
  __name(deleteInlineWorkflowScript, "deleteInlineWorkflowScript");
1857
2151
 
1858
- // packages/core/src/agents/workflow-snapshot.ts
2152
+ // packages/core/src/agents/runtime/workflow-orchestrator.ts
2153
+ init_esbuild_shims();
2154
+ import { randomBytes } from "node:crypto";
2155
+ import { AsyncLocalStorage } from "node:async_hooks";
2156
+ import * as os from "node:os";
2157
+
2158
+ // packages/core/src/agents/runtime/workflow-journal.ts
1859
2159
  init_esbuild_shims();
1860
- import { promises as fs2 } from "node:fs";
2160
+ import { createHash } from "node:crypto";
2161
+ import { constants, promises as fs2 } from "node:fs";
1861
2162
  import path2 from "node:path";
1862
- var debugLogger3 = createDebugLogger("WORKFLOW_SNAPSHOT");
2163
+ var debugLogger5 = createDebugLogger("WORKFLOW_JOURNAL");
2164
+ var JOURNAL_KEY_VERSION = "v2";
2165
+ function canonicalizeAgentOpts(opts) {
2166
+ const projected = {};
2167
+ for (const k of [
2168
+ "schema",
2169
+ "model",
2170
+ "isolation",
2171
+ "agentType",
2172
+ "workingDir"
2173
+ ]) {
2174
+ const v = opts[k];
2175
+ if (v === void 0 || typeof v === "function") continue;
2176
+ projected[k] = v;
2177
+ }
2178
+ const sortDeep = /* @__PURE__ */ __name((val) => {
2179
+ if (typeof val === "function") return void 0;
2180
+ if (Array.isArray(val)) return val.map(sortDeep);
2181
+ if (val && typeof val === "object") {
2182
+ const out = {};
2183
+ for (const key of Object.keys(val).sort()) {
2184
+ if (key === "__proto__") continue;
2185
+ out[key] = sortDeep(val[key]);
2186
+ }
2187
+ return out;
2188
+ }
2189
+ return val;
2190
+ }, "sortDeep");
2191
+ try {
2192
+ return JSON.stringify(sortDeep(projected));
2193
+ } catch {
2194
+ return "{}";
2195
+ }
2196
+ }
2197
+ __name(canonicalizeAgentOpts, "canonicalizeAgentOpts");
2198
+ function deriveAgentKey(prefixHash, prompt, opts) {
2199
+ const hash = createHash("sha256");
2200
+ hash.update(prefixHash);
2201
+ hash.update("\0");
2202
+ hash.update(prompt);
2203
+ hash.update("\0");
2204
+ hash.update(canonicalizeAgentOpts(opts));
2205
+ return `${JOURNAL_KEY_VERSION}:${hash.digest("hex")}`;
2206
+ }
2207
+ __name(deriveAgentKey, "deriveAgentKey");
2208
+ function deriveArgsSeed(args) {
2209
+ const hash = createHash("sha256");
2210
+ let serialized;
2211
+ try {
2212
+ serialized = JSON.stringify(args ?? null) ?? "null";
2213
+ } catch {
2214
+ serialized = "non-serializable-args";
2215
+ }
2216
+ hash.update(serialized);
2217
+ return `${JOURNAL_KEY_VERSION}:${hash.digest("hex")}`;
2218
+ }
2219
+ __name(deriveArgsSeed, "deriveArgsSeed");
2220
+ function buildReplay(entries) {
2221
+ const results = /* @__PURE__ */ new Map();
2222
+ const started = /* @__PURE__ */ new Map();
2223
+ const failed = /* @__PURE__ */ new Set();
2224
+ for (const e of entries) {
2225
+ if (e.type === "result") {
2226
+ results.set(e.key, e);
2227
+ } else if (e.type === "started") {
2228
+ failed.delete(e.key);
2229
+ const list = started.get(e.key);
2230
+ if (list) list.push(e);
2231
+ else started.set(e.key, [e]);
2232
+ } else if (e.type === "failed") {
2233
+ failed.add(e.key);
2234
+ }
2235
+ }
2236
+ return { results, started, failed };
2237
+ }
2238
+ __name(buildReplay, "buildReplay");
2239
+ var WorkflowJournal = class {
2240
+ constructor(journalPath, root = path2.dirname(path2.dirname(journalPath))) {
2241
+ this.root = root;
2242
+ this.path = journalPath;
2243
+ }
2244
+ static {
2245
+ __name(this, "WorkflowJournal");
2246
+ }
2247
+ pending = Promise.resolve();
2248
+ path;
2249
+ async hasSymlinkedPath() {
2250
+ if (await isSymlinkedRoot(this.root) || await isSymlinkedRoot(path2.dirname(this.path))) {
2251
+ return true;
2252
+ }
2253
+ return fs2.lstat(this.path).then((stat) => stat.isSymbolicLink()).catch(() => false);
2254
+ }
2255
+ /** Ensure the advertised journal path exists without affecting the run. */
2256
+ async ensureExists() {
2257
+ try {
2258
+ if (await this.hasSymlinkedPath()) return false;
2259
+ await fs2.mkdir(path2.dirname(this.path), { recursive: true });
2260
+ if (await this.hasSymlinkedPath()) return false;
2261
+ const noFollow = process.platform === "win32" ? 0 : constants.O_NOFOLLOW;
2262
+ const file = await fs2.open(
2263
+ this.path,
2264
+ constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | noFollow,
2265
+ 384
2266
+ );
2267
+ try {
2268
+ await file.chmod(384);
2269
+ } finally {
2270
+ await file.close();
2271
+ }
2272
+ return true;
2273
+ } catch (error) {
2274
+ debugLogger5.warn(
2275
+ `WorkflowJournal.ensureExists failed for ${this.path}: ${error}`
2276
+ );
2277
+ return false;
2278
+ }
2279
+ }
2280
+ /** Remove a never-registered run's journal file, best-effort. */
2281
+ async remove() {
2282
+ try {
2283
+ if (await this.hasSymlinkedPath()) return;
2284
+ await fs2.rm(this.path, { force: true });
2285
+ await fs2.rmdir(path2.dirname(this.path)).catch((error) => {
2286
+ const code = error.code;
2287
+ if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
2288
+ });
2289
+ } catch (error) {
2290
+ debugLogger5.warn(
2291
+ `WorkflowJournal.remove failed for ${this.path}: ${error}`
2292
+ );
2293
+ }
2294
+ }
2295
+ /** Load + parse all entries into replay maps. Empty maps if no file. */
2296
+ async load() {
2297
+ try {
2298
+ const entries = await read(this.path);
2299
+ return buildReplay(entries);
2300
+ } catch (e) {
2301
+ debugLogger5.warn(`WorkflowJournal.load failed for ${this.path}: ${e}`);
2302
+ return { results: /* @__PURE__ */ new Map(), started: /* @__PURE__ */ new Map(), failed: /* @__PURE__ */ new Set() };
2303
+ }
2304
+ }
2305
+ /** Append one entry. Rejects only on I/O error (callers `.catch`). */
2306
+ append(entry) {
2307
+ const operation = this.pending.then(() => writeLine(this.path, entry));
2308
+ this.pending = operation.catch(() => void 0);
2309
+ return operation;
2310
+ }
2311
+ /** Wait until every append issued so far has settled. */
2312
+ drain() {
2313
+ return this.pending;
2314
+ }
2315
+ };
2316
+
2317
+ // packages/core/src/agents/runtime/workflow-prompts.ts
2318
+ init_esbuild_shims();
2319
+ var WORKFLOW_SUBAGENT_SYSTEM_PROMPT = 'You are a subagent spawned by a workflow orchestration script. Use the tools available to complete the task.\nCRITICAL: Your final text response is returned **verbatim** as a string to the calling script \u2014 it is your return value, not a message to a human.\n- Output the literal result (data, JSON, text). Do NOT output confirmations like "Done." or "Sent."\n- If asked for JSON, return ONLY the raw JSON \u2014 no code fences, no prose, no markdown.\n- Do NOT use SendUserMessage to deliver your answer. Put your answer in your final text response.\n- Be concise. The script will parse your output.';
2320
+ var WORKFLOW_SUBAGENT_SYSTEM_PROMPT_WITH_SCHEMA = "You are a subagent spawned by a workflow orchestration script. Use the tools available to complete the task.\nCRITICAL: You MUST deliver your final answer by calling the `structured_output` tool with arguments that conform to its parameter schema. Plain-text final answers are DISCARDED \u2014 only a valid `structured_output` call returns a result to the calling script.\n- Use other tools (Read, Grep, etc.) to gather information first.\n- When ready, call `structured_output` ONCE with the conforming JSON object.\n- If validation fails, the error tells you what to fix. Try again with corrected fields.\n- After two failed attempts, the run terminates \u2014 get the arguments right.\n- Do NOT use SendUserMessage to deliver your answer.\n- Be concise; the script reads only the structured payload, not your prose.";
2321
+
2322
+ // packages/core/src/agents/runtime/workflow-dispatch-scheduler.ts
2323
+ init_esbuild_shims();
2324
+ function abortError() {
2325
+ return new DOMException("Workflow dispatch scheduler aborted.", "AbortError");
2326
+ }
2327
+ __name(abortError, "abortError");
2328
+ var WorkflowDispatchScheduler = class {
2329
+ constructor(limit, signal, onStateChange) {
2330
+ this.limit = limit;
2331
+ this.signal = signal;
2332
+ if (!Number.isInteger(limit) || limit < 1) {
2333
+ throw new Error(
2334
+ `Workflow dispatch limit must be a positive integer, got ${String(limit)}.`
2335
+ );
2336
+ }
2337
+ if (onStateChange) this.stateListeners.add(onStateChange);
2338
+ if (signal && !signal.aborted) {
2339
+ signal.addEventListener("abort", () => this.abortPending(), {
2340
+ once: true
2341
+ });
2342
+ }
2343
+ }
2344
+ static {
2345
+ __name(this, "WorkflowDispatchScheduler");
2346
+ }
2347
+ state = "running";
2348
+ inFlight = 0;
2349
+ queue = [];
2350
+ gateWaiters = [];
2351
+ stateListeners = /* @__PURE__ */ new Set();
2352
+ /**
2353
+ * Subscribe to state transitions. Returns an unsubscribe function.
2354
+ * The constructor callback (when given) is registered as the first
2355
+ * listener; this method lets additional observers — e.g. the sandbox's
2356
+ * pause-aware wall-clock watchdog — hook the same transitions.
2357
+ */
2358
+ onStateChange(listener) {
2359
+ this.stateListeners.add(listener);
2360
+ return () => {
2361
+ this.stateListeners.delete(listener);
2362
+ };
2363
+ }
2364
+ run(thunk) {
2365
+ return new Promise((resolve2, reject) => {
2366
+ if (this.signal?.aborted) {
2367
+ reject(abortError());
2368
+ return;
2369
+ }
2370
+ this.queue.push({
2371
+ thunk,
2372
+ resolve: resolve2,
2373
+ reject
2374
+ });
2375
+ this.pump();
2376
+ });
2377
+ }
2378
+ pause() {
2379
+ if (this.state !== "running" || this.signal?.aborted) return false;
2380
+ this.setState("pausing");
2381
+ if (this.inFlight === 0) this.setState("paused");
2382
+ return true;
2383
+ }
2384
+ resume() {
2385
+ if (this.state !== "paused" || this.signal?.aborted) return false;
2386
+ this.setState("running");
2387
+ while (this.gateWaiters.length > 0) {
2388
+ this.gateWaiters.shift().resolve();
2389
+ }
2390
+ this.pump();
2391
+ return true;
2392
+ }
2393
+ waitUntilRunning() {
2394
+ if (this.signal?.aborted) return Promise.reject(abortError());
2395
+ if (this.state === "running") return Promise.resolve();
2396
+ return new Promise((resolve2, reject) => {
2397
+ this.gateWaiters.push({ resolve: resolve2, reject });
2398
+ });
2399
+ }
2400
+ snapshot() {
2401
+ return {
2402
+ state: this.state,
2403
+ queued: this.queue.length,
2404
+ inFlight: this.inFlight
2405
+ };
2406
+ }
2407
+ pump() {
2408
+ while (this.state === "running" && this.inFlight < this.limit && this.queue.length > 0) {
2409
+ const job = this.queue.shift();
2410
+ if (this.signal?.aborted) {
2411
+ job.reject(abortError());
2412
+ continue;
2413
+ }
2414
+ this.inFlight++;
2415
+ Promise.resolve().then(job.thunk).then(job.resolve, job.reject).finally(() => {
2416
+ this.inFlight--;
2417
+ if (this.state === "pausing" && this.inFlight === 0) {
2418
+ this.setState("paused");
2419
+ }
2420
+ this.pump();
2421
+ });
2422
+ }
2423
+ }
2424
+ setState(state) {
2425
+ if (this.state === state) return;
2426
+ this.state = state;
2427
+ const snapshot = this.snapshot();
2428
+ for (const listener of [...this.stateListeners]) listener(snapshot);
2429
+ }
2430
+ abortPending() {
2431
+ const error = abortError();
2432
+ while (this.queue.length > 0) this.queue.shift().reject(error);
2433
+ while (this.gateWaiters.length > 0) {
2434
+ this.gateWaiters.shift().reject(error);
2435
+ }
2436
+ }
2437
+ };
2438
+
2439
+ // packages/core/src/agents/runtime/workflow-orchestrator.ts
2440
+ var DEFAULT_MAX_AGENTS_PER_RUN = 1e3;
2441
+ var MAX_WORKFLOW_AGENTS_ENV = "QWEN_CODE_MAX_WORKFLOW_AGENTS";
2442
+ var HARD_MAX_AGENTS_PER_RUN_CEILING = 1e4;
2443
+ function resolveMaxAgentsPerRun(env = process.env) {
2444
+ const raw = env[MAX_WORKFLOW_AGENTS_ENV];
2445
+ if (raw === void 0 || raw.trim() === "") {
2446
+ return DEFAULT_MAX_AGENTS_PER_RUN;
2447
+ }
2448
+ const parsed = parsePositiveIntegerEnv(raw, 0);
2449
+ if (parsed < 1) {
2450
+ debugLogger.warn(
2451
+ `Invalid ${MAX_WORKFLOW_AGENTS_ENV}=${JSON.stringify(raw)}, using default (${DEFAULT_MAX_AGENTS_PER_RUN})`
2452
+ );
2453
+ return DEFAULT_MAX_AGENTS_PER_RUN;
2454
+ }
2455
+ if (parsed > HARD_MAX_AGENTS_PER_RUN_CEILING) {
2456
+ debugLogger.warn(
2457
+ `${MAX_WORKFLOW_AGENTS_ENV}=${parsed} exceeds hard ceiling (${HARD_MAX_AGENTS_PER_RUN_CEILING}); clamping.`
2458
+ );
2459
+ return HARD_MAX_AGENTS_PER_RUN_CEILING;
2460
+ }
2461
+ return parsed;
2462
+ }
2463
+ __name(resolveMaxAgentsPerRun, "resolveMaxAgentsPerRun");
2464
+ var MAX_WORKFLOW_CONCURRENCY_ENV = "QWEN_CODE_MAX_WORKFLOW_CONCURRENCY";
2465
+ var HARD_MAX_CONCURRENCY_CEILING = 64;
2466
+ function resolveConcurrencyLimit(env = process.env, availableParallelism2 = os.availableParallelism) {
2467
+ const raw = env[MAX_WORKFLOW_CONCURRENCY_ENV];
2468
+ if (raw !== void 0 && raw.trim() !== "") {
2469
+ const parsed = parsePositiveIntegerEnv(raw, 0);
2470
+ if (parsed >= 1) {
2471
+ if (parsed > HARD_MAX_CONCURRENCY_CEILING) {
2472
+ debugLogger.warn(
2473
+ `${MAX_WORKFLOW_CONCURRENCY_ENV}=${parsed} exceeds hard ceiling (${HARD_MAX_CONCURRENCY_CEILING}); clamping.`
2474
+ );
2475
+ return HARD_MAX_CONCURRENCY_CEILING;
2476
+ }
2477
+ return parsed;
2478
+ }
2479
+ debugLogger.warn(
2480
+ `Invalid ${MAX_WORKFLOW_CONCURRENCY_ENV}=${JSON.stringify(raw)}, using cpu-derived default`
2481
+ );
2482
+ }
2483
+ return Math.max(2, Math.min(16, availableParallelism2() - 2));
2484
+ }
2485
+ __name(resolveConcurrencyLimit, "resolveConcurrencyLimit");
2486
+ var DEFAULT_WORKFLOW_SUBAGENT_MAX_TURNS = 50;
2487
+ var DEFAULT_WORKFLOW_SUBAGENT_MAX_TIME_MINUTES = 10;
2488
+ var WORKFLOW_SUBAGENT_MAX_TURNS_ENV = "QWEN_CODE_WORKFLOW_AGENT_MAX_TURNS";
2489
+ var WORKFLOW_SUBAGENT_MAX_MINUTES_ENV = "QWEN_CODE_WORKFLOW_AGENT_MAX_MINUTES";
2490
+ var HARD_WORKFLOW_SUBAGENT_MAX_TURNS_CEILING = 500;
2491
+ var HARD_WORKFLOW_SUBAGENT_MAX_MINUTES_CEILING = 100;
2492
+ function resolveSubagentBound(envName, defaultValue, ceiling, env) {
2493
+ const raw = env[envName];
2494
+ if (raw === void 0 || raw.trim() === "") return defaultValue;
2495
+ const parsed = parsePositiveIntegerEnv(raw, 0);
2496
+ if (parsed < 1) {
2497
+ debugLogger.warn(
2498
+ `Invalid ${envName}=${JSON.stringify(raw)}, using default (${defaultValue})`
2499
+ );
2500
+ return defaultValue;
2501
+ }
2502
+ if (parsed > ceiling) {
2503
+ debugLogger.warn(
2504
+ `${envName}=${parsed} exceeds hard ceiling (${ceiling}); clamping.`
2505
+ );
2506
+ return ceiling;
2507
+ }
2508
+ return parsed;
2509
+ }
2510
+ __name(resolveSubagentBound, "resolveSubagentBound");
2511
+ function resolveSubagentMaxTurns(env = process.env, defaultValue = DEFAULT_WORKFLOW_SUBAGENT_MAX_TURNS) {
2512
+ return resolveSubagentBound(
2513
+ WORKFLOW_SUBAGENT_MAX_TURNS_ENV,
2514
+ defaultValue,
2515
+ HARD_WORKFLOW_SUBAGENT_MAX_TURNS_CEILING,
2516
+ env
2517
+ );
2518
+ }
2519
+ __name(resolveSubagentMaxTurns, "resolveSubagentMaxTurns");
2520
+ function resolveSubagentMaxTimeMinutes(env = process.env, defaultValue = DEFAULT_WORKFLOW_SUBAGENT_MAX_TIME_MINUTES) {
2521
+ return resolveSubagentBound(
2522
+ WORKFLOW_SUBAGENT_MAX_MINUTES_ENV,
2523
+ defaultValue,
2524
+ HARD_WORKFLOW_SUBAGENT_MAX_MINUTES_CEILING,
2525
+ env
2526
+ );
2527
+ }
2528
+ __name(resolveSubagentMaxTimeMinutes, "resolveSubagentMaxTimeMinutes");
2529
+ var WORKFLOW_SUBAGENT_DISALLOWED_TOOLS = [
2530
+ ToolNames.ASK_USER_QUESTION,
2531
+ ToolNames.SEND_MESSAGE,
2532
+ ToolNames.MONITOR,
2533
+ ...SUBAGENT_PLAN_LIFECYCLE_TOOLS,
2534
+ // AgentTool: workflow subagents must not spawn sub-agents even where
2535
+ // maxSubagentDepth would permit nesting — a leaf-spawned agent would run
2536
+ // outside the orchestrator's concurrency cap, agent counter, and token
2537
+ // budget, and its result would bypass the script's return-value contract.
2538
+ // The WorkflowTool itself is already excluded from every subagent; this
2539
+ // closes the same loop for plain `agent` calls (review #6189).
2540
+ ToolNames.AGENT
2541
+ ];
2542
+ var WorkflowExecutionError = class extends Error {
2543
+ constructor(message, phases, logs, meta = null) {
2544
+ super(message);
2545
+ this.phases = phases;
2546
+ this.logs = logs;
2547
+ this.meta = meta;
2548
+ }
2549
+ static {
2550
+ __name(this, "WorkflowExecutionError");
2551
+ }
2552
+ name = "WorkflowExecutionError";
2553
+ };
2554
+ function generateRunId() {
2555
+ return `wf_${randomBytes(8).toString("hex")}`;
2556
+ }
2557
+ __name(generateRunId, "generateRunId");
2558
+ function sanitizeForErrorMessage(value) {
2559
+ return stripAnsiAndControl(value);
2560
+ }
2561
+ __name(sanitizeForErrorMessage, "sanitizeForErrorMessage");
2562
+ function createProductionDispatch(config, signal, onTokens, bridgeApprovalEvents, subagentBounds) {
2563
+ return async (prompt, opts, dispatchId) => {
2564
+ if (typeof prompt !== "string" || prompt.length === 0) {
2565
+ throw new Error("agent() requires a non-empty string prompt.");
2566
+ }
2567
+ const stallMs = resolveStallMs(
2568
+ typeof opts.stallMs === "number" ? opts.stallMs : void 0
2569
+ );
2570
+ const workflowAgentId = `workflow-agent-${randomBytes(8).toString("hex")}`;
2571
+ const agentIdentity = await resolveWorkflowAgentIdentity(config, opts);
2572
+ if (agentIdentity.resolvedAgentType?.executor !== void 0) {
2573
+ throw new Error(
2574
+ "Workflow agent() does not support external-executor agents: token budgets, schema output, and workflow tool restrictions cannot be enforced. Use an in-process agent definition instead."
2575
+ );
2576
+ }
2577
+ let attempt = 0;
2578
+ return runStallResilient(
2579
+ async (attemptSignal, emitter) => {
2580
+ attempt += 1;
2581
+ const cleanupApprovalBridge = bridgeApprovalEvents?.(
2582
+ emitter,
2583
+ dispatchId
2584
+ );
2585
+ const cleanupTranscript = attachDispatchTranscript(
2586
+ config,
2587
+ workflowAgentId,
2588
+ prompt,
2589
+ agentIdentity.name,
2590
+ emitter,
2591
+ attempt
2592
+ );
2593
+ try {
2594
+ return await runSingleDispatch(
2595
+ config,
2596
+ prompt,
2597
+ opts,
2598
+ attemptSignal,
2599
+ emitter,
2600
+ workflowAgentId,
2601
+ agentIdentity,
2602
+ onTokens,
2603
+ subagentBounds
2604
+ );
2605
+ } finally {
2606
+ cleanupTranscript();
2607
+ cleanupApprovalBridge?.();
2608
+ }
2609
+ },
2610
+ {
2611
+ stallMs,
2612
+ signal,
2613
+ // The name can carry a model-authored agentType spelling — keep
2614
+ // the stall log / abandoned error single-line the same way the
2615
+ // "not found" throw site sanitizes it.
2616
+ label: sanitizeForErrorMessage(agentIdentity.name)
2617
+ }
2618
+ );
2619
+ };
2620
+ }
2621
+ __name(createProductionDispatch, "createProductionDispatch");
2622
+ async function resolveWorkflowAgentIdentity(config, opts) {
2623
+ if (opts.agentType) {
2624
+ const resolved = await config.getSubagentManager().findSubagentByName(opts.agentType);
2625
+ if (resolved) {
2626
+ return { name: resolved.name, resolvedAgentType: resolved };
2627
+ }
2628
+ }
2629
+ if (typeof opts.label === "string" && opts.label) {
2630
+ return { name: opts.label };
2631
+ }
2632
+ return { name: opts.agentType || "workflow-agent" };
2633
+ }
2634
+ __name(resolveWorkflowAgentIdentity, "resolveWorkflowAgentIdentity");
2635
+ function attachDispatchTranscript(config, agentId, prompt, agentName, emitter, attempt) {
2636
+ const append = attempt > 1;
2637
+ try {
2638
+ const { jsonlPath, options } = buildAgentTranscriptAttach(config, agentId, {
2639
+ agentName,
2640
+ // The prompt the SCRIPT dispatched, seeded as the transcript's first
2641
+ // user record — the same shape AgentTool writes, so a reader that
2642
+ // recovers a launch prompt from a transcript needs no workflow-
2643
+ // specific branch. A retry re-uses the first attempt's record rather
2644
+ // than seeding a second one.
2645
+ initialUserPrompt: append ? void 0 : prompt,
2646
+ appendToExisting: append,
2647
+ retryAttempt: append ? attempt : void 0
2648
+ });
2649
+ return attachJsonlTranscriptWriter(emitter, jsonlPath, options).cleanup;
2650
+ } catch (error) {
2651
+ debugLogger.warn(
2652
+ `[Workflow] failed to attach transcript for ${agentId}: ${error}`
2653
+ );
2654
+ return () => {
2655
+ };
2656
+ }
2657
+ }
2658
+ __name(attachDispatchTranscript, "attachDispatchTranscript");
2659
+ function terminalDispatchError(workflowAgentId, mode) {
2660
+ const message = `Workflow subagent ${workflowAgentId} did not complete (terminate mode: ${mode}).`;
2661
+ switch (mode) {
2662
+ case "MAX_TURNS" /* MAX_TURNS */:
2663
+ return new WorkflowAgentFailedError(message, "max_turns", mode);
2664
+ case "TIMEOUT" /* TIMEOUT */:
2665
+ return new WorkflowAgentFailedError(message, "timeout", mode);
2666
+ case "ERROR" /* ERROR */:
2667
+ return new WorkflowAgentFailedError(message, "error", mode);
2668
+ default:
2669
+ return new Error(message);
2670
+ }
2671
+ }
2672
+ __name(terminalDispatchError, "terminalDispatchError");
2673
+ async function runSingleDispatch(config, prompt, opts, attemptSignal, emitter, workflowAgentId, agentIdentity, onTokens, subagentBounds) {
2674
+ const { AgentHeadless, ContextState } = await import("./agent-headless-RI2THRQ7.js");
2675
+ const ctx = new ContextState();
2676
+ ctx.set("task_prompt", prompt);
2677
+ debugLogger.debug(`[workflow] Dispatch ${workflowAgentId}`);
2678
+ if (opts.agentType === void 0 && opts.model === void 0 && opts.isolation === void 0 && opts.schema === void 0 && opts.workingDir === void 0) {
2679
+ const subagent = await AgentHeadless.create(
2680
+ agentIdentity.name,
2681
+ config,
2682
+ {
2683
+ systemPrompt: WORKFLOW_SUBAGENT_SYSTEM_PROMPT
2684
+ },
2685
+ {},
2686
+ // T11 (PR #4732 R1): bound resource ceiling so a single agent() call
2687
+ // cannot loop the model indefinitely. Without this, runConfig was {}
2688
+ // and the loop guards never tripped — combined with the cancellation
2689
+ // bug below, workflows were effectively unkillable.
2690
+ subagentBounds ?? {
2691
+ max_turns: resolveSubagentMaxTurns(),
2692
+ max_time_minutes: resolveSubagentMaxTimeMinutes()
2693
+ },
2694
+ // T11 (PR #4732 R1): disallow SendMessage / ExitPlanMode to align with
2695
+ // upstream Tg8 — closes the back-channel that would let a subagent
2696
+ // deliver its answer via user message instead of the script's read.
2697
+ { tools: ["*"], disallowedTools: WORKFLOW_SUBAGENT_DISALLOWED_TOOLS },
2698
+ // P-stall: the stall-watchdog emitter observes reasoning-loop events
2699
+ // (round/tool/usage) to detect a hang and abort `attemptSignal`.
2700
+ emitter,
2701
+ void 0,
2702
+ void 0,
2703
+ prompt,
2704
+ workflowAgentId
2705
+ );
2706
+ try {
2707
+ await runWithAgentContext(
2708
+ workflowAgentId,
2709
+ () => subagent.execute(ctx, attemptSignal)
2710
+ );
2711
+ } finally {
2712
+ reportTokens(subagent, opts, onTokens);
2713
+ }
2714
+ const mode = subagent.getTerminateMode();
2715
+ if (mode !== "GOAL" /* GOAL */) {
2716
+ throw terminalDispatchError(workflowAgentId, mode);
2717
+ }
2718
+ return toModelVisibleSubagentResult(subagent.getFinalText(), mode);
2719
+ }
2720
+ return runOverridePath(
2721
+ config,
2722
+ ctx,
2723
+ opts,
2724
+ attemptSignal,
2725
+ workflowAgentId,
2726
+ agentIdentity,
2727
+ onTokens,
2728
+ emitter,
2729
+ subagentBounds
2730
+ );
2731
+ }
2732
+ __name(runSingleDispatch, "runSingleDispatch");
2733
+ function reportTokens(subagent, opts, onTokens) {
2734
+ if (!onTokens) return;
2735
+ try {
2736
+ const summary = subagent.getExecutionSummary();
2737
+ onTokens(summary.outputTokens, opts);
2738
+ } catch (e) {
2739
+ debugLogger.warn("onTokens callback threw:", e);
2740
+ }
2741
+ }
2742
+ __name(reportTokens, "reportTokens");
2743
+ async function runOverridePath(config, ctx, opts, signal, workflowAgentId, agentIdentity, onTokens, emitter, subagentBounds) {
2744
+ if (opts.isolation === "remote") {
2745
+ throw new Error(
2746
+ "agent({isolation:'remote'}) is not available in this build."
2747
+ );
2748
+ }
2749
+ const subagentMgr = config.getSubagentManager();
2750
+ let baseConfig;
2751
+ if (opts.agentType !== void 0) {
2752
+ const resolved = agentIdentity.resolvedAgentType;
2753
+ if (!resolved) {
2754
+ const safeAgentType = sanitizeForErrorMessage(opts.agentType);
2755
+ throw new Error(
2756
+ `agent({agentType}): agent type '${safeAgentType}' not found.`
2757
+ );
2758
+ }
2759
+ baseConfig = resolved;
2760
+ } else {
2761
+ baseConfig = {
2762
+ name: agentIdentity.name,
2763
+ description: "Default workflow subagent (per-call overrides).",
2764
+ systemPrompt: WORKFLOW_SUBAGENT_SYSTEM_PROMPT,
2765
+ level: "session",
2766
+ isBuiltin: false
2767
+ };
2768
+ }
2769
+ let schemaSystemPrompt;
2770
+ if (opts.schema !== void 0) {
2771
+ schemaSystemPrompt = opts.agentType !== void 0 && baseConfig.systemPrompt ? `${baseConfig.systemPrompt}
2772
+
2773
+ ${WORKFLOW_SUBAGENT_SYSTEM_PROMPT_WITH_SCHEMA}` : WORKFLOW_SUBAGENT_SYSTEM_PROMPT_WITH_SCHEMA;
2774
+ }
2775
+ let schemaTools;
2776
+ if (opts.schema !== void 0 && baseConfig.tools && baseConfig.tools.length > 0 && !baseConfig.tools.includes("*") && !baseConfig.tools.includes(ToolNames.STRUCTURED_OUTPUT)) {
2777
+ schemaTools = [...baseConfig.tools, ToolNames.STRUCTURED_OUTPUT];
2778
+ }
2779
+ const augmented = {
2780
+ ...baseConfig,
2781
+ ...opts.model !== void 0 ? { model: opts.model } : {},
2782
+ ...schemaSystemPrompt !== void 0 ? { systemPrompt: schemaSystemPrompt } : {},
2783
+ ...schemaTools !== void 0 ? { tools: schemaTools } : {},
2784
+ disallowedTools: Array.from(
2785
+ /* @__PURE__ */ new Set([
2786
+ ...baseConfig.disallowedTools ?? [],
2787
+ ...WORKFLOW_SUBAGENT_DISALLOWED_TOOLS
2788
+ ])
2789
+ )
2790
+ };
2791
+ let worktreeIsolation = null;
2792
+ let effectiveContext = config;
2793
+ let approvalCleanup;
2794
+ if (opts.isolation !== void 0 && opts.workingDir !== void 0) {
2795
+ throw new Error(
2796
+ "agent({workingDir, isolation}): incompatible options. workingDir pins the agent to a worktree you already own; isolation creates a fresh one and removes it afterwards. Pass one."
2797
+ );
2798
+ }
2799
+ if (opts.isolation === "worktree") {
2800
+ worktreeIsolation = await provisionWorkflowWorktree(config);
2801
+ effectiveContext = deriveWorktreeConfig(config, worktreeIsolation.path, {
2802
+ customIgnoreFiles: config.getFileFilteringOptions().customIgnoreFiles
2803
+ });
2804
+ installSessionWorkflowRevisionWriteThrough(effectiveContext, config);
2805
+ } else if (opts.workingDir !== void 0) {
2806
+ if (typeof opts.workingDir !== "string" || opts.workingDir.trim().length === 0) {
2807
+ throw new Error(
2808
+ "agent({workingDir}): must be a non-empty string naming an existing git worktree of this repository."
2809
+ );
2810
+ }
2811
+ const resolved = await resolveExternalWorktreeDir(
2812
+ config,
2813
+ opts.workingDir,
2814
+ "workingDir"
2815
+ );
2816
+ if ("error" in resolved) {
2817
+ throw new Error(
2818
+ `agent({workingDir: ${sanitizeForErrorMessage(JSON.stringify(opts.workingDir))}}): ${sanitizeForErrorMessage(resolved.error)}`
2819
+ );
2820
+ }
2821
+ effectiveContext = deriveWorktreeConfig(config, resolved.path, {
2822
+ customIgnoreFiles: config.getFileFilteringOptions().customIgnoreFiles
2823
+ });
2824
+ installSessionWorkflowRevisionWriteThrough(effectiveContext, config);
2825
+ }
2826
+ if (effectiveContext !== config) {
2827
+ const approvalHandle = deriveApprovalModeConfig(
2828
+ effectiveContext,
2829
+ config.getApprovalMode()
2830
+ );
2831
+ approvalCleanup = approvalHandle.cleanup;
2832
+ effectiveContext = approvalHandle.config;
2833
+ }
2834
+ let onParentAbort;
2835
+ try {
2836
+ let schemaState = null;
2837
+ if (opts.schema !== void 0) {
2838
+ effectiveContext = await createSchemaConfigOverride(
2839
+ effectiveContext,
2840
+ opts.schema
2841
+ );
2842
+ schemaState = createSchemaModeState();
2843
+ }
2844
+ let dispatchSignal = signal;
2845
+ if (schemaState) {
2846
+ const child = new AbortController();
2847
+ if (signal) {
2848
+ if (signal.aborted) {
2849
+ child.abort(signal.reason);
2850
+ } else {
2851
+ onParentAbort = /* @__PURE__ */ __name(() => child.abort(signal.reason), "onParentAbort");
2852
+ signal.addEventListener("abort", onParentAbort);
2853
+ }
2854
+ }
2855
+ schemaState.abortController = child;
2856
+ dispatchSignal = child.signal;
2857
+ }
2858
+ const eventEmitter = emitter ?? (schemaState ? new AgentEventEmitter() : void 0);
2859
+ if (schemaState && eventEmitter) {
2860
+ attachSchemaListeners(eventEmitter, schemaState);
2861
+ }
2862
+ const { subagent, dispose } = await subagentMgr.createAgentHeadless(
2863
+ augmented,
2864
+ effectiveContext,
2865
+ {
2866
+ // Workflow always bounds resource ceiling regardless of agentType's
2867
+ // own runConfig / maxTurns — these are workflow-level safety bounds,
2868
+ // not subagent-level preferences. P5 will refine via budget.
2869
+ runConfigOverrides: subagentBounds ?? {
2870
+ max_turns: resolveSubagentMaxTurns(),
2871
+ max_time_minutes: resolveSubagentMaxTimeMinutes()
2872
+ },
2873
+ eventEmitter,
2874
+ taskName: String(ctx.get("task_prompt")),
2875
+ subagentId: workflowAgentId
2876
+ }
2877
+ );
2878
+ try {
2879
+ try {
2880
+ await runWithAgentContext(
2881
+ workflowAgentId,
2882
+ () => subagent.execute(ctx, dispatchSignal)
2883
+ );
2884
+ } finally {
2885
+ reportTokens(subagent, opts, onTokens);
2886
+ }
2887
+ if (schemaState) {
2888
+ if (schemaState.result !== null) {
2889
+ if (worktreeIsolation) {
2890
+ const isolation = worktreeIsolation;
2891
+ worktreeIsolation = null;
2892
+ const preserved = await cleanupWorkflowWorktree(isolation);
2893
+ if (preserved) {
2894
+ debugLogger.info(
2895
+ `[Workflow] Schema-mode subagent preserved worktree at ${preserved.path ?? "(directory removed)"} on branch ${preserved.branch}. The structured payload is returned verbatim; recover the work from the preserved path / branch.`
2896
+ );
2897
+ }
2898
+ }
2899
+ return schemaState.result;
2900
+ }
2901
+ if (signal?.aborted) {
2902
+ throw new DOMException("Workflow aborted.", "AbortError");
2903
+ }
2904
+ const mode2 = subagent.getTerminateMode();
2905
+ if (mode2 !== "GOAL" /* GOAL */ && mode2 !== "CANCELLED" /* CANCELLED */) {
2906
+ throw terminalDispatchError(workflowAgentId, mode2);
2907
+ }
2908
+ if (schemaState.attempts > 2) {
2909
+ throw new WorkflowAgentFailedError(
2910
+ "subagent completed without calling StructuredOutput (after 2 in-conversation nudges).",
2911
+ "no_structured_output"
2912
+ );
2913
+ }
2914
+ throw new WorkflowAgentFailedError(
2915
+ "subagent completed without calling structured_output (no validation attempt \u2014 model produced plain-text content).",
2916
+ "no_structured_output"
2917
+ );
2918
+ }
2919
+ const mode = subagent.getTerminateMode();
2920
+ if (mode !== "GOAL" /* GOAL */) {
2921
+ throw terminalDispatchError(workflowAgentId, mode);
2922
+ }
2923
+ let finalText = toModelVisibleSubagentResult(
2924
+ subagent.getFinalText(),
2925
+ mode
2926
+ );
2927
+ if (worktreeIsolation) {
2928
+ const isolation = worktreeIsolation;
2929
+ worktreeIsolation = null;
2930
+ const preserved = await cleanupWorkflowWorktree(isolation);
2931
+ if (preserved && typeof finalText === "string") {
2932
+ finalText = appendWorktreePreservedSuffix(finalText, preserved);
2933
+ }
2934
+ }
2935
+ return finalText;
2936
+ } finally {
2937
+ await dispose();
2938
+ }
2939
+ } finally {
2940
+ if (onParentAbort && signal) {
2941
+ signal.removeEventListener("abort", onParentAbort);
2942
+ }
2943
+ approvalCleanup?.();
2944
+ if (worktreeIsolation) {
2945
+ try {
2946
+ await cleanupWorkflowWorktree(worktreeIsolation);
2947
+ } catch (error) {
2948
+ debugLogger.warn(
2949
+ `Workflow worktree cleanup in fallback finally failed for ${worktreeIsolation.path}: ${error instanceof Error ? error.message : String(error)}`
2950
+ );
2951
+ }
2952
+ }
2953
+ }
2954
+ }
2955
+ __name(runOverridePath, "runOverridePath");
2956
+ async function provisionWorkflowWorktree(config) {
2957
+ const cwd = config.getTargetDir();
2958
+ if (/\.qwen[\\/]worktrees[\\/]/.test(cwd)) {
2959
+ throw new Error(
2960
+ `agent({isolation:'worktree'}): parent is already inside a worktree (${cwd}). Nested isolation worktrees are not supported \u2014 the subagent's inherited paths would still reference the outer worktree.`
2961
+ );
2962
+ }
2963
+ const probe = new GitWorktreeService(cwd);
2964
+ const gitCheck = await probe.checkGitAvailable();
2965
+ if (!gitCheck.available) {
2966
+ throw new Error(
2967
+ `agent({isolation:'worktree'}): ${gitCheck.error ?? "git is not available"}.`
2968
+ );
2969
+ }
2970
+ if (!await probe.isGitRepository()) {
2971
+ throw new Error(
2972
+ `agent({isolation:'worktree'}): ${cwd} is not a git repository.`
2973
+ );
2974
+ }
2975
+ const projectRoot = await probe.getRepoTopLevel() ?? cwd;
2976
+ const wtService = projectRoot === cwd ? probe : new GitWorktreeService(projectRoot);
2977
+ let parentDirty = false;
2978
+ try {
2979
+ parentDirty = await wtService.hasWorktreeChanges(projectRoot);
2980
+ } catch (error) {
2981
+ debugLogger.warn(
2982
+ `[Workflow] hasWorktreeChanges failed at ${projectRoot}: ${error}`
2983
+ );
2984
+ parentDirty = true;
2985
+ }
2986
+ if (parentDirty) {
2987
+ throw new Error(
2988
+ `agent({isolation:'worktree'}): parent working tree at ${projectRoot} has uncommitted changes that would not propagate into the isolated worktree. The subagent would see the prior HEAD instead of the current state. Commit or stash the changes, then re-run.`
2989
+ );
2990
+ }
2991
+ const slug = generateAgentWorktreeSlug();
2992
+ let parentBranch;
2993
+ try {
2994
+ parentBranch = await wtService.getCurrentBranch();
2995
+ } catch (error) {
2996
+ debugLogger.warn(
2997
+ `[Workflow] getCurrentBranch failed at ${projectRoot}: ${error}`
2998
+ );
2999
+ }
3000
+ const created = await wtService.createUserWorktree(slug, parentBranch, {
3001
+ symlinkDirectories: config.getWorktreeSymlinkDirectories()
3002
+ });
3003
+ if (!created.success || !created.worktree) {
3004
+ throw new Error(
3005
+ `agent({isolation:'worktree'}): failed to create worktree: ${created.error ?? "unknown error"}.`
3006
+ );
3007
+ }
3008
+ try {
3009
+ await writeWorktreeSessionMarker(
3010
+ created.worktree.path,
3011
+ config.getSessionId()
3012
+ );
3013
+ } catch (error) {
3014
+ debugLogger.warn(
3015
+ `[Workflow] failed to write session marker at ${created.worktree.path}: ${error}`
3016
+ );
3017
+ }
3018
+ return {
3019
+ slug,
3020
+ path: created.worktree.path,
3021
+ branch: created.worktree.branch,
3022
+ repoRoot: projectRoot
3023
+ };
3024
+ }
3025
+ __name(provisionWorkflowWorktree, "provisionWorkflowWorktree");
3026
+ async function cleanupWorkflowWorktree(isolation) {
3027
+ const wtService = new GitWorktreeService(isolation.repoRoot);
3028
+ const [hasChanges, hasUnmerged] = await Promise.all([
3029
+ wtService.hasWorktreeChanges(isolation.path).catch((error) => {
3030
+ debugLogger.warn(
3031
+ `[Workflow] hasWorktreeChanges failed for ${isolation.path}: ${error}`
3032
+ );
3033
+ return true;
3034
+ }),
3035
+ wtService.hasUnmergedWorktreeCommits(isolation.slug).catch((error) => {
3036
+ debugLogger.warn(
3037
+ `[Workflow] hasUnmergedWorktreeCommits failed for ${isolation.slug}: ${error}`
3038
+ );
3039
+ return true;
3040
+ })
3041
+ ]);
3042
+ if (hasChanges || hasUnmerged) {
3043
+ debugLogger.info(
3044
+ `[Workflow] Preserving isolation worktree ${isolation.path} (branch ${isolation.branch}, hasChanges=${hasChanges}, hasUnmerged=${hasUnmerged})`
3045
+ );
3046
+ return { path: isolation.path, branch: isolation.branch };
3047
+ }
3048
+ try {
3049
+ const result = await wtService.removeUserWorktree(isolation.slug, {
3050
+ deleteBranch: true
3051
+ });
3052
+ if (!result.success) {
3053
+ debugLogger.warn(
3054
+ `[Workflow] Failed to remove ephemeral worktree ${isolation.path}: ${result.error}`
3055
+ );
3056
+ return { path: isolation.path, branch: isolation.branch };
3057
+ }
3058
+ if (result.branchPreserved) {
3059
+ debugLogger.warn(
3060
+ `[Workflow] Removed worktree directory ${isolation.path} but kept branch ${isolation.branch} (unmerged commits at delete time)`
3061
+ );
3062
+ return { branch: isolation.branch };
3063
+ }
3064
+ } catch (error) {
3065
+ debugLogger.warn(
3066
+ `[Workflow] Failed to remove ephemeral worktree ${isolation.path}: ${error}`
3067
+ );
3068
+ return { path: isolation.path, branch: isolation.branch };
3069
+ }
3070
+ return null;
3071
+ }
3072
+ __name(cleanupWorkflowWorktree, "cleanupWorkflowWorktree");
3073
+ function appendWorktreePreservedSuffix(finalText, preserved) {
3074
+ const sep2 = finalText.endsWith("\n") ? "\n" : "\n\n";
3075
+ if (preserved.path) {
3076
+ return `${finalText}${sep2}[worktree preserved: ${preserved.path} (branch ${preserved.branch})]`;
3077
+ }
3078
+ return `${finalText}${sep2}[worktree directory removed; branch ${preserved.branch} preserved \u2014 recover with \`git worktree add <path> ${preserved.branch}\`]`;
3079
+ }
3080
+ __name(appendWorktreePreservedSuffix, "appendWorktreePreservedSuffix");
3081
+ function createSchemaModeState() {
3082
+ return {
3083
+ result: null,
3084
+ attempts: 0,
3085
+ pendingArgs: /* @__PURE__ */ new Map(),
3086
+ abortController: new AbortController()
3087
+ };
3088
+ }
3089
+ __name(createSchemaModeState, "createSchemaModeState");
3090
+ function attachSchemaListeners(emitter, state) {
3091
+ const targetTool = ToolNames.STRUCTURED_OUTPUT;
3092
+ emitter.on("tool_call" /* TOOL_CALL */, (evt) => {
3093
+ if (evt.name !== targetTool) return;
3094
+ state.pendingArgs.set(evt.callId, evt.args);
3095
+ });
3096
+ emitter.on("tool_result" /* TOOL_RESULT */, (evt) => {
3097
+ if (evt.name !== targetTool) return;
3098
+ const args = state.pendingArgs.get(evt.callId);
3099
+ state.pendingArgs.delete(evt.callId);
3100
+ if (evt.success) {
3101
+ if (args !== void 0 && state.result === null) {
3102
+ state.result = args;
3103
+ state.abortController.abort();
3104
+ }
3105
+ return;
3106
+ }
3107
+ state.attempts += 1;
3108
+ if (state.attempts > 2 && state.result === null) {
3109
+ state.abortController.abort();
3110
+ }
3111
+ });
3112
+ }
3113
+ __name(attachSchemaListeners, "attachSchemaListeners");
3114
+ async function createSchemaConfigOverride(base, schema) {
3115
+ const override = deriveConfig(base);
3116
+ installSessionWorkflowRevisionWriteThrough(override, base);
3117
+ await rebuildToolRegistryOnOverride(override, base);
3118
+ const registry = override.getToolRegistry();
3119
+ registry.registerTool(new SyntheticOutputTool(schema));
3120
+ return override;
3121
+ }
3122
+ __name(createSchemaConfigOverride, "createSchemaConfigOverride");
3123
+ var WorkflowOrchestrator = class {
3124
+ constructor(dispatch) {
3125
+ this.dispatch = dispatch;
3126
+ }
3127
+ static {
3128
+ __name(this, "WorkflowOrchestrator");
3129
+ }
3130
+ async run(req) {
3131
+ const runId = req.runId ?? generateRunId();
3132
+ const maxAgents = resolveMaxAgentsPerRun();
3133
+ const signal = req.abortOnTimeout?.signal;
3134
+ const scheduler = req.scheduler ?? new WorkflowDispatchScheduler(resolveConcurrencyLimit(), signal);
3135
+ const rejectThroughPauseGate = /* @__PURE__ */ __name((error) => scheduler.waitUntilRunning().then(
3136
+ () => {
3137
+ throw error;
3138
+ },
3139
+ () => {
3140
+ throw error;
3141
+ }
3142
+ ), "rejectThroughPauseGate");
3143
+ let agentCount = 0;
3144
+ let dispatchTraceCount = 0;
3145
+ const emitter = req.emitter;
3146
+ const budget = req.budget;
3147
+ const dependencyContext = new AsyncLocalStorage();
3148
+ const issueDispatchTrace = /* @__PURE__ */ __name((prompt, opts, cached = false) => {
3149
+ const id = `dispatch-${dispatchTraceCount += 1}`;
3150
+ const store = dependencyContext.getStore();
3151
+ const dependsOn = Array.from(new Set(store?.tails ?? []));
3152
+ if (store) store.tails = [id];
3153
+ try {
3154
+ emitter?.dispatchQueued?.({
3155
+ id,
3156
+ ...typeof opts.label === "string" ? { label: opts.label } : {},
3157
+ prompt,
3158
+ dependsOn,
3159
+ queuedAt: Date.now(),
3160
+ ...cached ? { cached: true } : {}
3161
+ });
3162
+ } catch (e) {
3163
+ debugLogger.warn("emitter.dispatchQueued threw:", e);
3164
+ }
3165
+ return id;
3166
+ }, "issueDispatchTrace");
3167
+ const journal = req.journal;
3168
+ const replay = req.resumeReplay;
3169
+ let prefixHash = deriveArgsSeed(req.args);
3170
+ let hadMiss = false;
3171
+ let journalAgentId = 0;
3172
+ const parentSandboxRef = {
3173
+ current: void 0
3174
+ };
3175
+ const countedDispatch = /* @__PURE__ */ __name((prompt, opts) => {
3176
+ if (typeof prompt !== "string" || prompt.length === 0) {
3177
+ return rejectThroughPauseGate(
3178
+ new Error("agent() requires a non-empty string prompt.")
3179
+ );
3180
+ }
3181
+ let journalKey;
3182
+ let journalEntryId;
3183
+ let respawnLine;
3184
+ if (journal) {
3185
+ journalKey = deriveAgentKey(prefixHash, prompt, opts);
3186
+ prefixHash = journalKey;
3187
+ if (!hadMiss && replay) {
3188
+ const cached = replay.results.get(journalKey);
3189
+ if (cached !== void 0) {
3190
+ const respawns = replay.started.get(journalKey);
3191
+ if (respawns && respawns.length > 0) {
3192
+ debugLogger.info(
3193
+ `[Workflow] resume cache hit after ${respawns.length} prior respawn(s) for runId=${runId}.`
3194
+ );
3195
+ }
3196
+ const label2 = typeof opts.label === "string" ? opts.label : void 0;
3197
+ const dispatchId2 = issueDispatchTrace(prompt, opts, true);
3198
+ try {
3199
+ emitter?.agentDispatched?.(label2);
3200
+ } catch (e) {
3201
+ debugLogger.warn("emitter.agentDispatched threw:", e);
3202
+ }
3203
+ try {
3204
+ emitter?.agentCompleted?.(label2);
3205
+ } catch (e) {
3206
+ debugLogger.warn("emitter.agentCompleted threw:", e);
3207
+ }
3208
+ try {
3209
+ emitter?.dispatchSettled?.(dispatchId2, void 0, Date.now());
3210
+ } catch (e) {
3211
+ debugLogger.warn("emitter.dispatchSettled threw:", e);
3212
+ }
3213
+ return scheduler.waitUntilRunning().then(
3214
+ () => cached.result,
3215
+ () => cached.result
3216
+ );
3217
+ }
3218
+ }
3219
+ const priorStarts = replay?.started.get(journalKey);
3220
+ if (priorStarts && priorStarts.length > 0 && !replay?.results.has(journalKey)) {
3221
+ const name = typeof opts.label === "string" ? `"${stripAnsiAndControl(opts.label)}"` : "an agent";
3222
+ respawnLine = replay?.failed.has(journalKey) ? `[resume] re-running ${name}: it failed in the previous run` : `[resume] respawning ${name}: interrupted in a previous run (${priorStarts.length} prior attempt${priorStarts.length === 1 ? "" : "s"})`;
3223
+ }
3224
+ hadMiss = true;
3225
+ }
3226
+ if (budget && budget.total !== null && budget.remaining() <= 0) {
3227
+ debugLogger.warn(
3228
+ `[Workflow] budget gate refused dispatch at entry: runId=${runId} spent=${budget.spent()} total=${budget.total}`
3229
+ );
3230
+ return rejectThroughPauseGate(
3231
+ new WorkflowBudgetExceededError(runId, budget.total, budget.spent())
3232
+ );
3233
+ }
3234
+ if (agentCount >= maxAgents) {
3235
+ return rejectThroughPauseGate(
3236
+ new WorkflowAgentCapExceededError(maxAgents)
3237
+ );
3238
+ }
3239
+ agentCount += 1;
3240
+ if (journal && journalKey !== void 0) {
3241
+ journalEntryId = String(journalAgentId += 1);
3242
+ }
3243
+ const label = typeof opts.label === "string" ? opts.label : void 0;
3244
+ const dispatchId = issueDispatchTrace(prompt, opts);
3245
+ try {
3246
+ emitter?.agentDispatched?.(label);
3247
+ } catch (e) {
3248
+ debugLogger.warn("emitter.agentDispatched threw:", e);
3249
+ }
3250
+ let completionEmitted = false;
3251
+ const emitCompletion = /* @__PURE__ */ __name((error) => {
3252
+ if (completionEmitted) return;
3253
+ completionEmitted = true;
3254
+ const message = error === void 0 ? void 0 : error instanceof Error ? error.message : String(error);
3255
+ try {
3256
+ emitter?.agentCompleted?.(label, message);
3257
+ } catch (e) {
3258
+ debugLogger.warn("emitter.agentCompleted threw:", e);
3259
+ }
3260
+ try {
3261
+ emitter?.dispatchSettled?.(dispatchId, message, Date.now());
3262
+ } catch (e) {
3263
+ debugLogger.warn("emitter.dispatchSettled threw:", e);
3264
+ }
3265
+ }, "emitCompletion");
3266
+ return scheduler.run(async () => {
3267
+ try {
3268
+ try {
3269
+ emitter?.dispatchStarted?.(dispatchId, Date.now());
3270
+ } catch (e) {
3271
+ debugLogger.warn("emitter.dispatchStarted threw:", e);
3272
+ }
3273
+ if (budget && budget.total !== null && budget.remaining() <= 0) {
3274
+ debugLogger.warn(
3275
+ `[Workflow] budget gate refused dispatch at slot-acquire: runId=${runId} spent=${budget.spent()} total=${budget.total}`
3276
+ );
3277
+ throw new WorkflowBudgetExceededError(
3278
+ runId,
3279
+ budget.total,
3280
+ budget.spent()
3281
+ );
3282
+ }
3283
+ if (journal && journalKey !== void 0 && journalEntryId !== void 0) {
3284
+ journal.append({
3285
+ type: "started",
3286
+ key: journalKey,
3287
+ agentId: journalEntryId
3288
+ }).catch(
3289
+ (e) => debugLogger.warn(`journal started-append failed: ${e}`)
3290
+ );
3291
+ }
3292
+ if (respawnLine) {
3293
+ parentSandboxRef.current?.appendLog(respawnLine);
3294
+ try {
3295
+ emitter?.resumeRespawn?.(respawnLine);
3296
+ } catch (e) {
3297
+ debugLogger.warn("emitter.resumeRespawn threw:", e);
3298
+ }
3299
+ }
3300
+ const result = await this.dispatch(prompt, opts, dispatchId);
3301
+ emitCompletion();
3302
+ if (journal && journalKey !== void 0) {
3303
+ journal.append({
3304
+ type: "result",
3305
+ key: journalKey,
3306
+ agentId: journalEntryId ?? "",
3307
+ result
3308
+ }).catch(
3309
+ (e) => debugLogger.warn(`journal result-append failed: ${e}`)
3310
+ );
3311
+ }
3312
+ if (budget) {
3313
+ try {
3314
+ emitter?.budgetUpdated?.(budget.spent(), budget.total);
3315
+ } catch (e) {
3316
+ debugLogger.warn("emitter.budgetUpdated threw:", e);
3317
+ }
3318
+ }
3319
+ return result;
3320
+ } catch (err) {
3321
+ emitCompletion(err);
3322
+ if (budget) {
3323
+ try {
3324
+ emitter?.budgetUpdated?.(budget.spent(), budget.total);
3325
+ } catch (e) {
3326
+ debugLogger.warn("emitter.budgetUpdated threw:", e);
3327
+ }
3328
+ }
3329
+ if (journal && journalKey !== void 0 && !signal?.aborted && !isWorkflowRunLevelError(err)) {
3330
+ journal.append({
3331
+ type: "failed",
3332
+ key: journalKey,
3333
+ agentId: journalEntryId ?? ""
3334
+ }).catch(
3335
+ (e) => debugLogger.warn(`journal failed-append failed: ${e}`)
3336
+ );
3337
+ }
3338
+ if (signal?.aborted || isWorkflowRunLevelError(err)) throw err;
3339
+ if (isWorkflowAgentFailedError(err)) {
3340
+ debugLogger.warn(
3341
+ `[Workflow] agent settled to null (${err.kind}): ${err.message}`
3342
+ );
3343
+ } else {
3344
+ debugLogger.warn(
3345
+ `[Workflow] agent settled to null: ${extractErrorMessage(err)}`
3346
+ );
3347
+ }
3348
+ return null;
3349
+ }
3350
+ }).then(
3351
+ // Resolve even if the gate aborts: a successful dispatch must not
3352
+ // turn into a teardown rejection — for a fire-and-forget call the
3353
+ // script never attached a handler, so the rejection would surface
3354
+ // as a spurious process-level unhandledRejection alarm on a
3355
+ // correctly-cancelled run.
3356
+ (result) => scheduler.waitUntilRunning().then(
3357
+ () => result,
3358
+ () => result
3359
+ ),
3360
+ (error) => {
3361
+ emitCompletion(error);
3362
+ return scheduler.waitUntilRunning().then(
3363
+ () => {
3364
+ throw error;
3365
+ },
3366
+ () => {
3367
+ throw error;
3368
+ }
3369
+ );
3370
+ }
3371
+ );
3372
+ }, "countedDispatch");
3373
+ const parallelImpl = makeParallelImpl(signal, dependencyContext);
3374
+ const pipelineImpl = makePipelineImpl(signal, dependencyContext);
3375
+ const resolveSavedWorkflow = req.resolveSavedWorkflow;
3376
+ const workflowImpl = resolveSavedWorkflow ? async (nameOrRef, nestedArgs) => {
3377
+ const resolved = await resolveSavedWorkflow(nameOrRef);
3378
+ const nestedSandbox = createWorkflowSandbox({
3379
+ args: nestedArgs,
3380
+ runId,
3381
+ dispatch: countedDispatch,
3382
+ parallel: parallelImpl,
3383
+ pipeline: pipelineImpl,
3384
+ abortOnTimeout: req.abortOnTimeout,
3385
+ emitter,
3386
+ budget,
3387
+ scheduler
3388
+ // No `workflow` — single-level nesting limit.
3389
+ });
3390
+ try {
3391
+ return await nestedSandbox.run(resolved.script);
3392
+ } finally {
3393
+ for (const line of nestedSandbox.getLogs()) {
3394
+ parentSandboxRef.current?.appendLog(line);
3395
+ }
3396
+ }
3397
+ } : void 0;
3398
+ const sandbox = createWorkflowSandbox({
3399
+ args: req.args,
3400
+ maxWallClockMs: req.maxWallClockMs,
3401
+ runId,
3402
+ dispatch: countedDispatch,
3403
+ parallel: parallelImpl,
3404
+ pipeline: pipelineImpl,
3405
+ workflow: workflowImpl,
3406
+ abortOnTimeout: req.abortOnTimeout,
3407
+ emitter,
3408
+ budget,
3409
+ scheduler
3410
+ });
3411
+ parentSandboxRef.current = sandbox;
3412
+ try {
3413
+ const result = await dependencyContext.run(
3414
+ { tails: [] },
3415
+ () => sandbox.run(req.script)
3416
+ );
3417
+ return {
3418
+ runId,
3419
+ result,
3420
+ phases: sandbox.getPhases(),
3421
+ logs: sandbox.getLogs(),
3422
+ meta: sandbox.getMeta()
3423
+ };
3424
+ } catch (err) {
3425
+ throw new WorkflowExecutionError(
3426
+ extractErrorMessage(err),
3427
+ sandbox.getPhases(),
3428
+ sandbox.getLogs(),
3429
+ sandbox.getMeta()
3430
+ );
3431
+ }
3432
+ }
3433
+ };
3434
+ async function settleToNullArray(thunks, signal) {
3435
+ const settled = await Promise.allSettled(
3436
+ thunks.map((t) => Promise.resolve().then(t))
3437
+ );
3438
+ if (signal?.aborted)
3439
+ throw new DOMException("Workflow run aborted.", "AbortError");
3440
+ const visitedReasons = /* @__PURE__ */ new WeakSet();
3441
+ const findRunFailureReason = /* @__PURE__ */ __name((reason) => {
3442
+ if (reason === null || typeof reason !== "object") return void 0;
3443
+ if (visitedReasons.has(reason)) return void 0;
3444
+ visitedReasons.add(reason);
3445
+ try {
3446
+ if (reason.__wfRunFailure === true) {
3447
+ return reason;
3448
+ }
3449
+ const errors = reason?.errors;
3450
+ if (!Array.isArray(errors)) return void 0;
3451
+ for (const error of errors) {
3452
+ const runFailure = findRunFailureReason(error);
3453
+ if (runFailure !== void 0) return runFailure;
3454
+ }
3455
+ } catch {
3456
+ return void 0;
3457
+ }
3458
+ return void 0;
3459
+ }, "findRunFailureReason");
3460
+ for (const result of settled) {
3461
+ if (result.status !== "rejected") continue;
3462
+ const runFailure = findRunFailureReason(result.reason);
3463
+ if (runFailure !== void 0) throw runFailure;
3464
+ }
3465
+ return settled.map((r, i) => {
3466
+ if (r.status === "fulfilled") return r.value;
3467
+ const reason = r.reason;
3468
+ debugLogger.warn(
3469
+ `Workflow thunk at index ${i} rejected: ${String(reason?.message ?? r.reason)}`
3470
+ );
3471
+ return null;
3472
+ });
3473
+ }
3474
+ __name(settleToNullArray, "settleToNullArray");
3475
+ function makeParallelImpl(signal, dependencyContext) {
3476
+ return (thunks) => {
3477
+ if (!Array.isArray(thunks)) {
3478
+ return Promise.reject(
3479
+ new Error(
3480
+ "parallel() expects an array of thunks (functions returning promises)."
3481
+ )
3482
+ );
3483
+ }
3484
+ for (const t of thunks) {
3485
+ if (typeof t !== "function") {
3486
+ return Promise.reject(
3487
+ new Error(
3488
+ "parallel() expects an array of functions, not values \u2014 wrap each call: parallel([() => agent(...), () => agent(...)])."
3489
+ )
3490
+ );
3491
+ }
3492
+ }
3493
+ const parent = dependencyContext.getStore();
3494
+ const inheritedTails = parent?.tails ?? [];
3495
+ const branches = thunks.map((thunk) => {
3496
+ const store = { tails: [...inheritedTails] };
3497
+ return {
3498
+ store,
3499
+ thunk: /* @__PURE__ */ __name(() => dependencyContext.run(store, thunk), "thunk")
3500
+ };
3501
+ });
3502
+ return settleToNullArray(
3503
+ branches.map(({ thunk }) => thunk),
3504
+ signal
3505
+ ).then((result) => {
3506
+ if (parent && branches.length > 0) {
3507
+ parent.tails = mergeFanoutTails(
3508
+ parent.tails,
3509
+ inheritedTails,
3510
+ branches.flatMap(({ store }) => store.tails)
3511
+ );
3512
+ }
3513
+ return result;
3514
+ });
3515
+ };
3516
+ }
3517
+ __name(makeParallelImpl, "makeParallelImpl");
3518
+ function makePipelineImpl(signal, dependencyContext) {
3519
+ return (items, ...stages) => {
3520
+ if (!Array.isArray(items)) {
3521
+ return Promise.reject(
3522
+ new Error(
3523
+ "pipeline() expects an array of items as its first argument."
3524
+ )
3525
+ );
3526
+ }
3527
+ for (const s of stages) {
3528
+ if (typeof s !== "function") {
3529
+ return Promise.reject(
3530
+ new Error(
3531
+ "pipeline() stages must be functions: pipeline(items, item => ..., result => ...)."
3532
+ )
3533
+ );
3534
+ }
3535
+ }
3536
+ const parent = dependencyContext.getStore();
3537
+ const inheritedTails = parent?.tails ?? [];
3538
+ const branches = items.map((item, idx) => {
3539
+ const store = { tails: [...inheritedTails] };
3540
+ return {
3541
+ store,
3542
+ thunk: /* @__PURE__ */ __name(() => dependencyContext.run(
3543
+ store,
3544
+ () => runPipelineChain(item, idx, stages)
3545
+ ), "thunk")
3546
+ };
3547
+ });
3548
+ return settleToNullArray(
3549
+ branches.map(({ thunk }) => thunk),
3550
+ signal
3551
+ ).then((result) => {
3552
+ if (parent && branches.length > 0) {
3553
+ parent.tails = mergeFanoutTails(
3554
+ parent.tails,
3555
+ inheritedTails,
3556
+ branches.flatMap(({ store }) => store.tails)
3557
+ );
3558
+ }
3559
+ return result;
3560
+ });
3561
+ };
3562
+ }
3563
+ __name(makePipelineImpl, "makePipelineImpl");
3564
+ function mergeFanoutTails(currentParentTails, inheritedTails, branchTails) {
3565
+ const inherited = new Set(inheritedTails);
3566
+ const newBranchTails = branchTails.filter((tail) => !inherited.has(tail));
3567
+ const merged = newBranchTails.length > 0 ? [
3568
+ ...newBranchTails,
3569
+ ...currentParentTails.filter((tail) => !inherited.has(tail))
3570
+ ] : currentParentTails;
3571
+ return Array.from(new Set(merged));
3572
+ }
3573
+ __name(mergeFanoutTails, "mergeFanoutTails");
3574
+ async function runPipelineChain(item, idx, stages) {
3575
+ let prev = item;
3576
+ for (const stage of stages) {
3577
+ if (prev === null) break;
3578
+ prev = await stage(prev, item, idx);
3579
+ }
3580
+ return prev;
3581
+ }
3582
+ __name(runPipelineChain, "runPipelineChain");
3583
+ function extractErrorMessage(err) {
3584
+ if (err && typeof err === "object" && "message" in err) {
3585
+ const m = err.message;
3586
+ if (typeof m === "string") return m;
3587
+ return String(m);
3588
+ }
3589
+ return String(err);
3590
+ }
3591
+ __name(extractErrorMessage, "extractErrorMessage");
3592
+
3593
+ // packages/core/src/agents/workflow-snapshot.ts
3594
+ init_esbuild_shims();
3595
+ import { promises as fs3 } from "node:fs";
3596
+ import path3 from "node:path";
3597
+ var debugLogger6 = createDebugLogger("WORKFLOW_SNAPSHOT");
1863
3598
  var MAX_RETAINED_SNAPSHOTS = 30;
1864
3599
  function toSnapshot(task) {
1865
3600
  if (!isTerminalWorkflowStatus(task.status)) {
@@ -1913,8 +3648,8 @@ async function writeWorkflowSnapshot(config, task) {
1913
3648
  try {
1914
3649
  const snapshot = toSnapshot(task);
1915
3650
  const dir = storage.getWorkflowRunsDir();
1916
- await fs2.mkdir(dir, { recursive: true });
1917
- await fs2.writeFile(
3651
+ await fs3.mkdir(dir, { recursive: true });
3652
+ await fs3.writeFile(
1918
3653
  storage.getWorkflowRunSnapshotPath(task.runId),
1919
3654
  JSON.stringify(snapshot, null, 2),
1920
3655
  "utf8"
@@ -1922,7 +3657,7 @@ async function writeWorkflowSnapshot(config, task) {
1922
3657
  await pruneSnapshots(config, dir);
1923
3658
  return true;
1924
3659
  } catch (e) {
1925
- debugLogger3.warn(`writeWorkflowSnapshot failed for ${task.runId}: ${e}`);
3660
+ debugLogger6.warn(`writeWorkflowSnapshot failed for ${task.runId}: ${e}`);
1926
3661
  return false;
1927
3662
  }
1928
3663
  }
@@ -1933,22 +3668,22 @@ async function listWorkflowSnapshots(config) {
1933
3668
  const dir = storage.getWorkflowRunsDir();
1934
3669
  let files;
1935
3670
  try {
1936
- files = (await fs2.readdir(dir)).filter((f) => f.endsWith(".json"));
3671
+ files = (await fs3.readdir(dir)).filter((f) => f.endsWith(".json"));
1937
3672
  } catch {
1938
3673
  return [];
1939
3674
  }
1940
3675
  const snapshots = [];
1941
3676
  for (const file of files) {
1942
3677
  try {
1943
- const raw = await fs2.readFile(`${dir}/${file}`, "utf8");
3678
+ const raw = await fs3.readFile(`${dir}/${file}`, "utf8");
1944
3679
  const parsed = JSON.parse(raw);
1945
3680
  if (!isWorkflowSnapshot(parsed)) {
1946
- debugLogger3.warn(`skipping invalid workflow snapshot ${file}`);
3681
+ debugLogger6.warn(`skipping invalid workflow snapshot ${file}`);
1947
3682
  continue;
1948
3683
  }
1949
3684
  snapshots.push(parsed);
1950
3685
  } catch (e) {
1951
- debugLogger3.warn(`skipping unparseable snapshot ${file}: ${e}`);
3686
+ debugLogger6.warn(`skipping unparseable snapshot ${file}: ${e}`);
1952
3687
  }
1953
3688
  }
1954
3689
  snapshots.sort((a, b) => (b.startTime ?? 0) - (a.startTime ?? 0));
@@ -1959,20 +3694,20 @@ async function deleteWorkflowSnapshot(config, runId) {
1959
3694
  const storage = config.storage;
1960
3695
  if (!storage || !/^wf_[0-9a-f]+$/.test(runId)) return false;
1961
3696
  try {
1962
- await fs2.rm(path2.dirname(storage.getWorkflowRunJournalPath(runId)), {
3697
+ await fs3.rm(path3.dirname(storage.getWorkflowRunJournalPath(runId)), {
1963
3698
  recursive: true,
1964
3699
  force: true
1965
3700
  });
1966
3701
  } catch (error) {
1967
- debugLogger3.warn(`delete workflow journal failed for ${runId}: ${error}`);
3702
+ debugLogger6.warn(`delete workflow journal failed for ${runId}: ${error}`);
1968
3703
  return false;
1969
3704
  }
1970
3705
  if (!await deleteInlineWorkflowScript(config, runId)) return false;
1971
3706
  try {
1972
- await fs2.unlink(storage.getWorkflowRunSnapshotPath(runId));
3707
+ await fs3.unlink(storage.getWorkflowRunSnapshotPath(runId));
1973
3708
  } catch (error) {
1974
3709
  if (error.code !== "ENOENT") {
1975
- debugLogger3.warn(`deleteWorkflowSnapshot failed for ${runId}: ${error}`);
3710
+ debugLogger6.warn(`deleteWorkflowSnapshot failed for ${runId}: ${error}`);
1976
3711
  return false;
1977
3712
  }
1978
3713
  }
@@ -2070,7 +3805,7 @@ __name(isWorkflowSnapshot, "isWorkflowSnapshot");
2070
3805
  async function pruneSnapshots(config, dir) {
2071
3806
  let files;
2072
3807
  try {
2073
- files = (await fs2.readdir(dir)).filter((f) => f.endsWith(".json"));
3808
+ files = (await fs3.readdir(dir)).filter((f) => f.endsWith(".json"));
2074
3809
  } catch {
2075
3810
  return;
2076
3811
  }
@@ -2078,7 +3813,7 @@ async function pruneSnapshots(config, dir) {
2078
3813
  const stats = await Promise.all(
2079
3814
  files.map(async (f) => {
2080
3815
  try {
2081
- const s = await fs2.stat(`${dir}/${f}`);
3816
+ const s = await fs3.stat(`${dir}/${f}`);
2082
3817
  return { f, mtime: s.mtimeMs };
2083
3818
  } catch {
2084
3819
  return { f, mtime: 0 };
@@ -2098,15 +3833,15 @@ async function pruneSnapshots(config, dir) {
2098
3833
  const isRunDir = /^wf_[0-9a-f]+$/.test(runId);
2099
3834
  const deleteArtifacts = isRunDir && !protectedRunIds.has(runId) && !isWorkflowRunPersistenceActive(config, runId);
2100
3835
  return Promise.all([
2101
- fs2.unlink(`${dir}/${s.f}`).catch(
2102
- (e) => debugLogger3.warn(`prune unlink failed for ${s.f}: ${e}`)
3836
+ fs3.unlink(`${dir}/${s.f}`).catch(
3837
+ (e) => debugLogger6.warn(`prune unlink failed for ${s.f}: ${e}`)
2103
3838
  ),
2104
3839
  ...deleteArtifacts ? [
2105
- fs2.rm(
2106
- path2.dirname(config.storage.getWorkflowRunJournalPath(runId)),
3840
+ fs3.rm(
3841
+ path3.dirname(config.storage.getWorkflowRunJournalPath(runId)),
2107
3842
  { recursive: true, force: true }
2108
3843
  ).catch(
2109
- (e) => debugLogger3.warn(
3844
+ (e) => debugLogger6.warn(
2110
3845
  `prune journal dir failed for ${runId}: ${e}`
2111
3846
  )
2112
3847
  ),
@@ -2118,12 +3853,79 @@ async function pruneSnapshots(config, dir) {
2118
3853
  }
2119
3854
  __name(pruneSnapshots, "pruneSnapshots");
2120
3855
 
3856
+ // packages/core/src/agents/runtime/review-workflow.ts
3857
+ init_esbuild_shims();
3858
+ import { createHash as createHash2 } from "node:crypto";
3859
+ import { promises as fs4 } from "node:fs";
3860
+ import path4 from "node:path";
3861
+ var debugLogger7 = createDebugLogger("REVIEW_WORKFLOW");
3862
+ function resolveReviewWorkflowConcurrency(env = process.env) {
3863
+ const configured = parsePositiveIntegerEnv(env[MAX_WORKFLOW_CONCURRENCY_ENV], 0) || parsePositiveIntegerEnv(env["QWEN_CODE_MAX_TOOL_CONCURRENCY"], 10);
3864
+ return resolveConcurrencyLimit({
3865
+ [MAX_WORKFLOW_CONCURRENCY_ENV]: String(configured)
3866
+ });
3867
+ }
3868
+ __name(resolveReviewWorkflowConcurrency, "resolveReviewWorkflowConcurrency");
3869
+ async function resolveReviewWorkflowLimits(scriptPath, generatedDir, scriptContent, env = process.env, nowMs = Date.now()) {
3870
+ let canonicalScript;
3871
+ try {
3872
+ if ((await fs4.lstat(generatedDir)).isSymbolicLink()) return void 0;
3873
+ const generatedRoot = await fs4.realpath(generatedDir);
3874
+ canonicalScript = await fs4.realpath(scriptPath);
3875
+ if (!canonicalScript.startsWith(path4.join(generatedRoot, "review") + path4.sep)) {
3876
+ return void 0;
3877
+ }
3878
+ } catch (error) {
3879
+ if (error.code !== "ENOENT") {
3880
+ debugLogger7.warn(
3881
+ "Cannot classify review workflow; using generic limits:",
3882
+ error
3883
+ );
3884
+ }
3885
+ return void 0;
3886
+ }
3887
+ const digest = /^qwen-review-[a-f0-9]{10}-([a-f0-9]{64})\.js$/.exec(
3888
+ path4.basename(canonicalScript)
3889
+ )?.[1];
3890
+ if (!digest || createHash2("sha256").update(scriptContent).digest("hex") !== digest) {
3891
+ return void 0;
3892
+ }
3893
+ const seconds = Number(env["QWEN_CODE_MAX_WORKFLOW_SECONDS"]);
3894
+ let maxWallClockMs = (Number.isFinite(seconds) && seconds > 0 ? seconds : 6 * 60 * 60) * 1e3;
3895
+ const deadline = Number(env["QWEN_REVIEW_DEADLINE_EPOCH"]);
3896
+ if (Number.isFinite(deadline) && deadline > 0) {
3897
+ const rawFloor = env["QWEN_REVIEW_DEADLINE_COMPOSE_FLOOR_SECONDS"];
3898
+ const floor = Number(rawFloor);
3899
+ const floorSeconds = rawFloor?.trim() && Number.isFinite(floor) && floor >= 0 ? floor : 1200;
3900
+ const remainingMs = deadline * 1e3 - nowMs - floorSeconds * 1e3;
3901
+ if (remainingMs <= 0) {
3902
+ throw new Error(
3903
+ "Review workflow was not launched: the review deadline has reached the compose reserve floor. Recover completed findings and compose now."
3904
+ );
3905
+ }
3906
+ maxWallClockMs = Math.min(maxWallClockMs, remainingMs);
3907
+ }
3908
+ return {
3909
+ subagent: {
3910
+ max_turns: resolveSubagentMaxTurns(env, 500),
3911
+ max_time_minutes: resolveSubagentMaxTimeMinutes(env, 100)
3912
+ },
3913
+ concurrency: resolveReviewWorkflowConcurrency(env),
3914
+ maxWallClockMs
3915
+ };
3916
+ }
3917
+ __name(resolveReviewWorkflowLimits, "resolveReviewWorkflowLimits");
3918
+
2121
3919
  export {
2122
3920
  extractAndStripMeta,
2123
3921
  compileWorkflowScript,
2124
3922
  describeWorkflowCompileError,
2125
- debugLogger,
2126
- createWorkflowSandbox,
3923
+ MAX_TOKENS_PER_WORKFLOW_ENV,
3924
+ resolveMaxTokensPerWorkflow,
3925
+ WorkflowBudgetImpl,
3926
+ DEFAULT_STALL_MS,
3927
+ MAX_STALL_ATTEMPTS,
3928
+ MAX_WORKFLOW_STALL_MS_ENV,
2127
3929
  validateWorkflowName,
2128
3930
  isSymlinkedRoot,
2129
3931
  listSavedWorkflows,
@@ -2131,11 +3933,26 @@ export {
2131
3933
  saveWorkflowScript,
2132
3934
  persistInlineWorkflowScript,
2133
3935
  deleteInlineWorkflowScript,
3936
+ WorkflowJournal,
3937
+ WorkflowDispatchScheduler,
3938
+ DEFAULT_MAX_AGENTS_PER_RUN,
3939
+ MAX_WORKFLOW_AGENTS_ENV,
3940
+ MAX_WORKFLOW_CONCURRENCY_ENV,
3941
+ resolveConcurrencyLimit,
3942
+ DEFAULT_WORKFLOW_SUBAGENT_MAX_TURNS,
3943
+ DEFAULT_WORKFLOW_SUBAGENT_MAX_TIME_MINUTES,
3944
+ WORKFLOW_SUBAGENT_MAX_TURNS_ENV,
3945
+ WORKFLOW_SUBAGENT_MAX_MINUTES_ENV,
3946
+ WorkflowExecutionError,
3947
+ createProductionDispatch,
3948
+ WorkflowOrchestrator,
2134
3949
  MAX_RETAINED_SNAPSHOTS,
2135
3950
  toSnapshot,
2136
3951
  writeWorkflowSnapshot,
2137
3952
  listWorkflowSnapshots,
2138
- deleteWorkflowSnapshot
3953
+ deleteWorkflowSnapshot,
3954
+ resolveReviewWorkflowConcurrency,
3955
+ resolveReviewWorkflowLimits
2139
3956
  };
2140
3957
  /**
2141
3958
  * @license