gerege-cli 0.26.6 → 0.26.8

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 (247) hide show
  1. package/bundled/gerege-video/SKILL.md +22 -0
  2. package/bundled/gerege-video/scripts/video.js +137 -0
  3. package/chunks/{MaxSizedBox-QCIXIS4P.js → MaxSizedBox-LUINLOQW.js} +1 -1
  4. package/chunks/{StandaloneSessionPicker-BAFAIRT7.js → StandaloneSessionPicker-B7N4QO5D.js} +1 -1
  5. package/chunks/{acp-subagent-executor-TPVXURLW.js → acp-subagent-executor-J6H6FKUT.js} +1 -1
  6. package/chunks/{acpAgent-67UN66PB.js → acpAgent-XG6SM2VU.js} +3 -3
  7. package/chunks/{advisor-SAXMI4QZ.js → advisor-SZVPQNPA.js} +1 -1
  8. package/chunks/{agent-KV7BXY6C.js → agent-N7QF7BJS.js} +1 -1
  9. package/chunks/{agent-headless-FQX3JGG6.js → agent-headless-GLP5GUEX.js} +1 -1
  10. package/chunks/{agent-host-client-L5EHC4AC.js → agent-host-client-H4VOB3M6.js} +1 -1
  11. package/chunks/{agent-host-connections-EDBMCVQF.js → agent-host-connections-E4C3OC4M.js} +1 -1
  12. package/chunks/{anthropicContentGenerator-V7TX2NXP.js → anthropicContentGenerator-5VTWQLT5.js} +1 -1
  13. package/chunks/{autofix-pr-WP34NYHL.js → autofix-pr-HDYQDJS4.js} +1 -1
  14. package/chunks/{batch-XFVQ4BLM.js → batch-3CRVN5VJ.js} +1 -1
  15. package/chunks/{bridge-AE7AFEXB.js → bridge-NZ6WVBLQ.js} +1 -1
  16. package/chunks/{channel-settings-store-X63P5OVT.js → channel-settings-store-Z7I2JI6M.js} +1 -1
  17. package/chunks/{chunk-BCI62WSL.js → chunk-236DHGNH.js} +1 -1
  18. package/chunks/{chunk-JRTOPEM3.js → chunk-2M3ND5WN.js} +1 -1
  19. package/chunks/{chunk-LBLLWAKK.js → chunk-36A6EXHB.js} +1 -1
  20. package/chunks/{chunk-H3IR3GIE.js → chunk-3ANIQTDT.js} +1 -1
  21. package/chunks/{chunk-GSPGIGO5.js → chunk-3QTR2HAE.js} +3 -3
  22. package/chunks/{chunk-32XHDDIA.js → chunk-3TTHYXT3.js} +1 -1
  23. package/chunks/{chunk-MTDBCIDA.js → chunk-4CE4GMDL.js} +1 -1
  24. package/chunks/{chunk-T2YTHAJW.js → chunk-4FVT657Y.js} +1 -1
  25. package/chunks/{chunk-CGDFZEER.js → chunk-4HSISRRA.js} +1 -1
  26. package/chunks/{chunk-7453BHJO.js → chunk-4SZUJ5RT.js} +1 -1
  27. package/chunks/{chunk-B37YY4XU.js → chunk-57D2OB3I.js} +1 -1
  28. package/chunks/{chunk-WGFX3EL3.js → chunk-5FGBLIXB.js} +1 -1
  29. package/chunks/{chunk-I6PUY2T3.js → chunk-5HX2QGVR.js} +1 -1
  30. package/chunks/{chunk-BPFFRPWE.js → chunk-5ZNXAWOG.js} +6 -6
  31. package/chunks/{chunk-BHIDG6VZ.js → chunk-6CKX56LJ.js} +1 -1
  32. package/chunks/{chunk-GRAECADD.js → chunk-6NIQFWXP.js} +1 -1
  33. package/chunks/{chunk-ELDZ4MNL.js → chunk-6PC6MZHL.js} +1 -1
  34. package/chunks/{chunk-FEP6W4NJ.js → chunk-6VQKGKMJ.js} +1 -1
  35. package/chunks/{chunk-GBSRWT7J.js → chunk-6ZEMLEK2.js} +1 -1
  36. package/chunks/{chunk-4NDJKNN6.js → chunk-72VY2PJA.js} +1 -1
  37. package/chunks/{chunk-BAUMVH4Q.js → chunk-75I3NYBD.js} +1 -1
  38. package/chunks/{chunk-YH2XRWRF.js → chunk-76L7ZDEK.js} +1 -1
  39. package/chunks/{chunk-2JGTWRZJ.js → chunk-7XQ5D34E.js} +6 -6
  40. package/chunks/{chunk-DA6LOBSB.js → chunk-AYX75VXG.js} +1 -1
  41. package/chunks/{chunk-G6DALGGS.js → chunk-BBDFEMCF.js} +1 -1
  42. package/chunks/{chunk-VD2GSW64.js → chunk-BOTX7S66.js} +1 -1
  43. package/chunks/{chunk-M6KB5RVD.js → chunk-CY2QKKZA.js} +1 -1
  44. package/chunks/{chunk-HTAUIJB4.js → chunk-D5JWQUID.js} +1 -1
  45. package/chunks/{chunk-P3JEEDQZ.js → chunk-DMIPB7RZ.js} +1 -1
  46. package/chunks/{chunk-CF6SZJNP.js → chunk-DSKA3P2C.js} +1 -1
  47. package/chunks/{chunk-LTE4N6L3.js → chunk-DVC65H4X.js} +1 -1
  48. package/chunks/{chunk-W5Z4BWWA.js → chunk-DVJSDCMX.js} +1 -1
  49. package/chunks/{chunk-65ME4BOH.js → chunk-E6CPFQX2.js} +1 -1
  50. package/chunks/{chunk-JEDL4IKF.js → chunk-EIFBGEXJ.js} +1 -1
  51. package/chunks/{chunk-AYVCT5FF.js → chunk-EQOHDAYU.js} +1 -1
  52. package/chunks/{chunk-2TAJ5STJ.js → chunk-EZPM4DLR.js} +1 -1
  53. package/chunks/{chunk-JWNKPINR.js → chunk-F6U6T7QD.js} +1 -1
  54. package/chunks/{chunk-ET5M5WFN.js → chunk-FCGFBUHS.js} +1 -1
  55. package/chunks/{chunk-OU7CEG7Q.js → chunk-G2LTZU67.js} +1 -1
  56. package/chunks/{chunk-2N3NBTYJ.js → chunk-GMJSEK4V.js} +1 -1
  57. package/chunks/{chunk-NA4ZF2FE.js → chunk-HJMUBVXZ.js} +2 -2
  58. package/chunks/{chunk-AFO5ER23.js → chunk-HQZTAA2U.js} +1 -1
  59. package/chunks/{chunk-OK7LBM5G.js → chunk-I63TIQOI.js} +1 -1
  60. package/chunks/{chunk-OJ4K62S2.js → chunk-I65LBJN7.js} +1 -1
  61. package/chunks/{chunk-GHIFIXNX.js → chunk-IBDOC27R.js} +1 -1
  62. package/chunks/{chunk-2LWJGXTW.js → chunk-IKF2HWEV.js} +1 -1
  63. package/chunks/{chunk-AEZYXPFS.js → chunk-K6NS2HXT.js} +1 -1
  64. package/chunks/{chunk-T5DKF33F.js → chunk-KTRNYPQP.js} +1 -1
  65. package/chunks/{chunk-SKGJ26HQ.js → chunk-L3ANU5JZ.js} +1 -1
  66. package/chunks/{chunk-U3Q72OGV.js → chunk-LKPMADUO.js} +1 -1
  67. package/chunks/{chunk-MYV7GY3H.js → chunk-M56Y2B6N.js} +1 -1
  68. package/chunks/{chunk-34HC2AXI.js → chunk-N5KRBAK5.js} +2 -2
  69. package/chunks/{chunk-EXIFPXMB.js → chunk-NA2WJPOU.js} +1 -1
  70. package/chunks/{chunk-7RNOS7R4.js → chunk-NGOWLXYK.js} +1 -1
  71. package/chunks/{chunk-IZ5MWA6E.js → chunk-NL7P73ZP.js} +1 -1
  72. package/chunks/{chunk-FYBJGRX7.js → chunk-NS3QR7D3.js} +1 -1
  73. package/chunks/{chunk-XISR37DQ.js → chunk-O5JCCBMQ.js} +1 -1
  74. package/chunks/{chunk-FKL3V5BO.js → chunk-OOKFFZHF.js} +1 -1
  75. package/chunks/{chunk-VRKYBH5G.js → chunk-OTYPLLMT.js} +5 -5
  76. package/chunks/{chunk-W66WWTOP.js → chunk-P7NHWX27.js} +1 -1
  77. package/chunks/{chunk-AEKEZRIU.js → chunk-PC5QZUKR.js} +1 -1
  78. package/chunks/{chunk-NEKPQLFY.js → chunk-PS7MQL57.js} +2 -2
  79. package/chunks/{chunk-TB4AUC2L.js → chunk-PXWHOFAA.js} +1 -1
  80. package/chunks/{chunk-OOJ2AQT3.js → chunk-Q65LVCDR.js} +1 -1
  81. package/chunks/{chunk-EFIRES46.js → chunk-QDUDLELH.js} +1 -1
  82. package/chunks/{chunk-KZNYALFU.js → chunk-QF22ILPV.js} +1 -1
  83. package/chunks/{chunk-MGATL4OA.js → chunk-QW7MAG2E.js} +1 -1
  84. package/chunks/{chunk-KJGRCIVY.js → chunk-RXK6XD6F.js} +1 -1
  85. package/chunks/{chunk-W2RQIZ6B.js → chunk-SVDFCWS7.js} +1 -1
  86. package/chunks/{chunk-P62S5JGM.js → chunk-TKP3GAUI.js} +1 -1
  87. package/chunks/{chunk-BQZF3UKI.js → chunk-TUS74LFI.js} +1 -1
  88. package/chunks/{chunk-JH3V5SPA.js → chunk-U7YGHPSL.js} +1 -1
  89. package/chunks/{chunk-NONBHCXP.js → chunk-UB37RBSK.js} +1 -1
  90. package/chunks/{chunk-T53VMDXH.js → chunk-UK5SIRH4.js} +1 -1
  91. package/chunks/{chunk-3W32X2DH.js → chunk-UTTSBCFR.js} +1 -1
  92. package/chunks/{chunk-RSLTOIG5.js → chunk-UYV4ZVXY.js} +2 -2
  93. package/chunks/{chunk-FKZ46GKL.js → chunk-VC3JJL7E.js} +1 -1
  94. package/chunks/{chunk-SP6CQ3MO.js → chunk-VKWVIWLK.js} +1 -1
  95. package/chunks/{chunk-N7PWZBXV.js → chunk-VUI6STKU.js} +1 -1
  96. package/chunks/{chunk-5EXL4TKQ.js → chunk-W3YXE55M.js} +1 -1
  97. package/chunks/{chunk-NVOI6UDQ.js → chunk-WAIPC47V.js} +1 -1
  98. package/chunks/{chunk-QDCUR3JB.js → chunk-WMJ6UHDP.js} +1 -1
  99. package/chunks/{chunk-CBE6ZIHU.js → chunk-WZU2ECUD.js} +1 -1
  100. package/chunks/{chunk-ZENMAISJ.js → chunk-XAGIZY2Y.js} +1 -1
  101. package/chunks/{chunk-RXN7DUMP.js → chunk-XGZYVULJ.js} +2 -2
  102. package/chunks/{chunk-HOG66S6K.js → chunk-XJIHDVPX.js} +1 -1
  103. package/chunks/{chunk-UKLXKJKL.js → chunk-XVDIHFRH.js} +1 -1
  104. package/chunks/{chunk-76FSYQTG.js → chunk-YMEW4TTT.js} +1 -1
  105. package/chunks/{chunk-EYPLBTMI.js → chunk-Z32URWBG.js} +1 -1
  106. package/chunks/{chunk-CUP2TNJK.js → chunk-Z6HRXHJP.js} +1 -1
  107. package/chunks/{chunk-MPVQDYPH.js → chunk-ZO4F6ZWR.js} +1 -1
  108. package/chunks/{codex-subagent-executor-OLMGVPVS.js → codex-subagent-executor-DDKYNU42.js} +1 -1
  109. package/chunks/{config-utils-OWY5G5Y2.js → config-utils-S7Z2ZZ2E.js} +1 -1
  110. package/chunks/{contextCommand-IXFUZH65.js → contextCommand-7F4PGV2A.js} +1 -1
  111. package/chunks/{core-runtime-O4LC4NY3.js → core-runtime-LBH3U7ZF.js} +1 -1
  112. package/chunks/{create-sub-session-6F7C3TMT.js → create-sub-session-56DS2T6L.js} +1 -1
  113. package/chunks/{cron-create-2422NBSJ.js → cron-create-PBP3C46Q.js} +1 -1
  114. package/chunks/{daemon-git-worktree-guard-EWPQA6NO.js → daemon-git-worktree-guard-WJS6FBDA.js} +1 -1
  115. package/chunks/{daemon-status-provider-FAHOXNFW.js → daemon-status-provider-UPPAEHJ6.js} +1 -1
  116. package/chunks/{daemon-trust-policy-L3DM6AI5.js → daemon-trust-policy-4Z5HSNUX.js} +1 -1
  117. package/chunks/{daemon-trust-policy-monitor-HNPY5KJ4.js → daemon-trust-policy-monitor-WFWDOYX3.js} +1 -1
  118. package/chunks/{deferred-core-runtime-JF42NQJK.js → deferred-core-runtime-MJYNEA4N.js} +1 -1
  119. package/chunks/{edit-E5LEI2LL.js → edit-U7TGKKK3.js} +1 -1
  120. package/chunks/{enterPlanMode-3COTUV5V.js → enterPlanMode-27HC5AXN.js} +1 -1
  121. package/chunks/{environment-XBBIB3VA.js → environment-PHWY6C4P.js} +1 -1
  122. package/chunks/{errors-LNMQ7TUK.js → errors-F2EYYFI3.js} +1 -1
  123. package/chunks/{execution-tool-QDDKJD2K.js → execution-tool-O4KJ5SMM.js} +1 -1
  124. package/chunks/{execution-worker-TXGZRZXE.js → execution-worker-AMFXZ7JD.js} +1 -1
  125. package/chunks/{exitPlanMode-Z7QEMWPE.js → exitPlanMode-LDYL43PB.js} +1 -1
  126. package/chunks/{fast-path-M6K2RACY.js → fast-path-HTODEVOR.js} +1 -1
  127. package/chunks/{glob-N2QT4U7U.js → glob-NKQJJZND.js} +1 -1
  128. package/chunks/{goal-tools-CUSQD3DG.js → goal-tools-47I455VV.js} +1 -1
  129. package/chunks/{handleAutoUpdate-QF2YQHF6.js → handleAutoUpdate-MJKTDJUO.js} +1 -1
  130. package/chunks/{i18n-AGOA6MUI.js → i18n-TCOB4TC5.js} +1 -1
  131. package/chunks/{initializer-FRKYDUSX.js → initializer-NLYOGZZS.js} +1 -1
  132. package/chunks/{installationInfo-OKA4WXAS.js → installationInfo-TF2RSJOG.js} +1 -1
  133. package/chunks/{interactive-mod-session-MWYN5IFK.js → interactive-mod-session-5F7R3KSA.js} +1 -1
  134. package/chunks/{list-DE7VUIR2.js → list-U2AEVLFP.js} +1 -1
  135. package/chunks/{llm-N3JGJHYC.js → llm-EV2QTQBU.js} +4 -4
  136. package/chunks/{llm-content-generator-VMUBA7OJ.js → llm-content-generator-ZXUSPPG2.js} +1 -1
  137. package/chunks/{loadedSettingsAdapter-5C36OZ7N.js → loadedSettingsAdapter-TLRI22X7.js} +1 -1
  138. package/chunks/{local-BE624O3A.js → local-ZTSBSKWV.js} +1 -1
  139. package/chunks/{local-execution-environment-OPGM7Y6L.js → local-execution-environment-F263PSIM.js} +1 -1
  140. package/chunks/{loggingContentGenerator-2MHAI6JR.js → loggingContentGenerator-2XHSIJQD.js} +1 -1
  141. package/chunks/{loop-wakeup-BDLATBXH.js → loop-wakeup-5ET3JHUT.js} +1 -1
  142. package/chunks/{manage-memory-BBCEIIWB.js → manage-memory-MJEQ47H2.js} +1 -1
  143. package/chunks/{managed-execution-engine-SRFALTCX.js → managed-execution-engine-ODPR5OEH.js} +1 -1
  144. package/chunks/{managed-local-serve-ICNAS3E6.js → managed-local-serve-S5R4Z5OL.js} +1 -1
  145. package/chunks/managed-npm-update-BUI5APGY.js +8 -0
  146. package/chunks/{managed-runtime-attestation-worker-ZRDWKXCI.js → managed-runtime-attestation-worker-BQP4E7LQ.js} +1 -1
  147. package/chunks/{managed-runtime-bootstrap-6NTGZXQL.js → managed-runtime-bootstrap-SRBDFSKK.js} +1 -1
  148. package/chunks/{managed-runtime-session-worker-RKQBBFR6.js → managed-runtime-session-worker-UI23BTYJ.js} +1 -1
  149. package/chunks/{managed-runtime-ssh-worker-FCGV6FSW.js → managed-runtime-ssh-worker-HU4CIJRK.js} +1 -1
  150. package/chunks/{managed-session-authority-C7IW6TJX.js → managed-session-authority-XSSTLAEY.js} +1 -1
  151. package/chunks/{mcp-VC4CJPE5.js → mcp-WLHDOKP7.js} +1 -1
  152. package/chunks/{memory-S6OJA3ZD.js → memory-OUUHPSDD.js} +1 -1
  153. package/chunks/{model-call-collection-MJZWRQSU.js → model-call-collection-4A2EB76B.js} +1 -1
  154. package/chunks/{model-configuration-SKU6L3QI.js → model-configuration-4CGUFKEP.js} +1 -1
  155. package/chunks/{modelConfigUtils-TJCB6NXT.js → modelConfigUtils-HUEERWBA.js} +1 -1
  156. package/chunks/{monitor-M3PNLCYP.js → monitor-FXL5UNMP.js} +1 -1
  157. package/chunks/{nonInteractiveCli-MR7JLAWU.js → nonInteractiveCli-W7M2O43W.js} +1 -1
  158. package/chunks/{nonInteractiveToolExecutor-YKA6JMTY.js → nonInteractiveToolExecutor-EMLI363Q.js} +1 -1
  159. package/chunks/{notebook-edit-ENTFB5D7.js → notebook-edit-R5RSLSSH.js} +1 -1
  160. package/chunks/{omni-6YBX4R6K.js → omni-DNZGITTE.js} +1 -1
  161. package/chunks/{openaiContentGenerator-XRXX33FY.js → openaiContentGenerator-PKOPYMHR.js} +1 -1
  162. package/chunks/{openaiResponsesContentGenerator-L6ONEHMR.js → openaiResponsesContentGenerator-MHH2MF3V.js} +1 -1
  163. package/chunks/{pidfile-XR4JF2Z6.js → pidfile-5ZNJWMKG.js} +1 -1
  164. package/chunks/{processUtils-GQYNJRBJ.js → processUtils-JIHQDASW.js} +1 -1
  165. package/chunks/{prompt-terminal-ledger-7BM7YDLG.js → prompt-terminal-ledger-L3LZ5SLR.js} +1 -1
  166. package/chunks/{qwenContentGenerator-QSA32XEL.js → qwenContentGenerator-QCZL7HJJ.js} +1 -1
  167. package/chunks/{reactive-degrade-TFNBAAPZ.js → reactive-degrade-YUXOUQG4.js} +1 -1
  168. package/chunks/{read-file-VD7OFO2E.js → read-file-FBNU3AVX.js} +1 -1
  169. package/chunks/{resumeHistoryUtils-2B4KPI7G.js → resumeHistoryUtils-5FPRTI4A.js} +1 -1
  170. package/chunks/{review-C365WGCW.js → review-NLFYSNM3.js} +1 -1
  171. package/chunks/{ripGrep-D7WPMBXR.js → ripGrep-JUAPC5LD.js} +1 -1
  172. package/chunks/{run-qwen-serve-NZWQHWQA.js → run-qwen-serve-JP64UQ3Y.js} +1 -1
  173. package/chunks/{runtime-J6SPBSCS.js → runtime-D2QUYM6U.js} +1 -1
  174. package/chunks/{sandboxConfig-QS2XBPZG.js → sandboxConfig-7VZJQV6H.js} +1 -1
  175. package/chunks/{scheduled-tasks-YNNIOOPM.js → scheduled-tasks-PC6EH75E.js} +1 -1
  176. package/chunks/{scheduler-KCMSPHON.js → scheduler-RUV2FNDR.js} +1 -1
  177. package/chunks/{search-memory-EUBJ7IAV.js → search-memory-YJTJ7BRU.js} +1 -1
  178. package/chunks/{send-message-CWWZUPSK.js → send-message-EEEFFTHX.js} +1 -1
  179. package/chunks/{serve-4CB4BWJ5.js → serve-KMIZDYON.js} +1 -1
  180. package/chunks/{server-JNANUIGC.js → server-DUPK3V7B.js} +3 -3
  181. package/chunks/{session-3LQLXPUA.js → session-CW5YMFMP.js} +1 -1
  182. package/chunks/{session-attachments-root-BWIVWFHJ.js → session-attachments-root-5H5GFHLI.js} +1 -1
  183. package/chunks/{session-execution-engine-selector-5OLRX57L.js → session-execution-engine-selector-MVXM2HZW.js} +1 -1
  184. package/chunks/{session-pr-refresh-RLF3EXS3.js → session-pr-refresh-4UPONX4L.js} +1 -1
  185. package/chunks/{sessionService-U7ACD2HP.js → sessionService-GGCYISSL.js} +1 -1
  186. package/chunks/{settings-FTGWYTUH.js → settings-AASJCESS.js} +1 -1
  187. package/chunks/{shell-E4RENYQC.js → shell-V4WWLW3Q.js} +1 -1
  188. package/chunks/{skill-OLNPHRWB.js → skill-NDEBB7VX.js} +1 -1
  189. package/chunks/{skill-settings-R2BV2GEK.js → skill-settings-YAI3GYU5.js} +1 -1
  190. package/chunks/{spawnChannel-LOPAR5T2.js → spawnChannel-6JKVJAXZ.js} +1 -1
  191. package/chunks/{standalone-update-IGDX2RGN.js → standalone-update-NJP5OCKJ.js} +1 -1
  192. package/chunks/{start-opentui-ui-33QLBNRC.js → start-opentui-ui-M4B4SXRM.js} +1 -1
  193. package/chunks/{startInteractiveUI-RQKHD7MM.js → startInteractiveUI-O4JUDEAU.js} +1 -1
  194. package/chunks/{team-create-HAVKHNU5.js → team-create-NLJ7QBLD.js} +1 -1
  195. package/chunks/{team-plan-approval-7MCQX67C.js → team-plan-approval-XKYPVWNG.js} +1 -1
  196. package/chunks/{terminal-image-renderer-XT5JVEO6.js → terminal-image-renderer-47TD747D.js} +1 -1
  197. package/chunks/{theme-manager-DR5EYGLT.js → theme-manager-AANEBPLJ.js} +1 -1
  198. package/chunks/{tool-call-LZHZ5RVH.js → tool-call-ETH3LS7Y.js} +1 -1
  199. package/chunks/{tool-result-media-XCXCF4YC.js → tool-result-media-EFOEPAF2.js} +1 -1
  200. package/chunks/{tool-search-K6S3ON7M.js → tool-search-J3CF5PRN.js} +1 -1
  201. package/chunks/{total-session-admission-LGSS2VWS.js → total-session-admission-3DC52PLQ.js} +1 -1
  202. package/chunks/{trustedFolders-IIR2UZRL.js → trustedFolders-4KPWZZKB.js} +1 -1
  203. package/chunks/{update-relaunch-WVIFX5CN.js → update-relaunch-A67BS7QS.js} +1 -1
  204. package/chunks/{updateCheck-CMEWLLZJ.js → updateCheck-X623JRSY.js} +1 -1
  205. package/chunks/{upload-config-TCCFCNCD.js → upload-config-X2CR3F26.js} +1 -1
  206. package/chunks/{useAutoAcceptIndicator-5RTTH3OW.js → useAutoAcceptIndicator-INIOQGJH.js} +1 -1
  207. package/chunks/{validateNonInterActiveAuth-AO336KDX.js → validateNonInterActiveAuth-XJ2U5CLB.js} +1 -1
  208. package/chunks/{version-JYWKKMNP.js → version-MFHRMM7W.js} +1 -1
  209. package/chunks/{web-fetch-HWTAWXFM.js → web-fetch-3GEJ62DH.js} +1 -1
  210. package/chunks/{web-search-HAI5LW3G.js → web-search-WJZO3Q3A.js} +1 -1
  211. package/chunks/{workflow-BZ2YFGF6.js → workflow-ML7ITCMH.js} +1 -1
  212. package/chunks/{workflow-ancestor-trust-26TFXFPO.js → workflow-ancestor-trust-M3VFMS73.js} +1 -1
  213. package/chunks/{workspace-agents-DLI4JQJZ.js → workspace-agents-YFZMV7EF.js} +1 -1
  214. package/chunks/{workspace-providers-status-64C7DJZU.js → workspace-providers-status-3COKLBCI.js} +1 -1
  215. package/chunks/{workspace-recovery-worker-IFRT3KKP.js → workspace-recovery-worker-QURA3WFZ.js} +1 -1
  216. package/chunks/{workspace-registration-store-MYKJM2SK.js → workspace-registration-store-F3AGIOBW.js} +1 -1
  217. package/chunks/{workspace-registry-GZJRONAY.js → workspace-registry-QUBL3RW6.js} +1 -1
  218. package/chunks/{workspace-runtime-coordinator-44KW6HSN.js → workspace-runtime-coordinator-22TSDHXX.js} +1 -1
  219. package/chunks/{workspace-service-YHTSZYYD.js → workspace-service-UUENTHNO.js} +1 -1
  220. package/chunks/{workspace-skills-status-NEB62X24.js → workspace-skills-status-NNQQBBCJ.js} +1 -1
  221. package/chunks/{workspace-trust-reconciler-HZLOOZWM.js → workspace-trust-reconciler-3CMMNCGG.js} +1 -1
  222. package/chunks/{write-file-HD5LHXGL.js → write-file-DEAFIK4C.js} +1 -1
  223. package/chunks/{zoom-image-W4BMRC5T.js → zoom-image-YYO22PQG.js} +1 -1
  224. package/cli-entry.js +2 -3
  225. package/cli.js +2 -2
  226. package/execution-worker.js +1 -1
  227. package/export-transcript-document.js +1 -1
  228. package/gerege.mjs +11 -0
  229. package/package.json +2 -12
  230. package/chunks/managed-npm-update-CTL6LH5Z.js +0 -8
  231. package/opentui-assets/@opentui/core/assets/javascript/highlights.scm +0 -205
  232. package/opentui-assets/@opentui/core/assets/javascript/tree-sitter-javascript.wasm +0 -0
  233. package/opentui-assets/@opentui/core/assets/markdown/highlights.scm +0 -150
  234. package/opentui-assets/@opentui/core/assets/markdown/injections.scm +0 -27
  235. package/opentui-assets/@opentui/core/assets/markdown/tree-sitter-markdown.wasm +0 -0
  236. package/opentui-assets/@opentui/core/assets/markdown_inline/highlights.scm +0 -115
  237. package/opentui-assets/@opentui/core/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
  238. package/opentui-assets/@opentui/core/assets/typescript/highlights.scm +0 -604
  239. package/opentui-assets/@opentui/core/assets/typescript/tree-sitter-typescript.wasm +0 -0
  240. package/opentui-assets/@opentui/core/assets/zig/highlights.scm +0 -284
  241. package/opentui-assets/@opentui/core/assets/zig/tree-sitter-zig.wasm +0 -0
  242. package/opentui-assets/@opentui/core/parser.worker.js +0 -4566
  243. package/opentui-assets/@opentui/core-darwin-arm64/libopentui.dylib +0 -0
  244. package/opentui-assets/@opentui/core-darwin-x64/libopentui.dylib +0 -0
  245. package/opentui-assets/@opentui/core-linux-arm64/libopentui.so +0 -0
  246. package/opentui-assets/@opentui/core-linux-x64/libopentui.so +0 -0
  247. package/opentui-assets/web-tree-sitter/tree-sitter.wasm +0 -0
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{AgentEventEmitter,MAX_FAILURE_LINE_CHARS,MAX_TURN_BUDGET_TOKENS,MAX_WORKFLOW_CALL_TRACES,REPORTED_FAILURE_KEYS,WORKFLOW_BATCH_LIMIT,attachJsonlTranscriptWriter,buildAgentTranscriptAttach,canonicalAgentToolName,createWorkflowSandbox,debugLogger,deleteInlineWorkflowScript,deriveApprovalModeConfig,deriveConfig,deriveWorktreeConfig,describeAgentToolAllowEntryProblem,describeOversizedBatch,evaluateWorkflowSize,getAgentMetaPath,getWorkflowTaskMutationKey,installSessionWorkflowRevisionWriteThrough,isActiveWorkflowStatus,isSymlinkedRoot,isTerminalWorkflowStatus,isWorkflowRunId,isWorkflowRunPersistenceActive,isWorkflowSizeWarning,isWorkflowSourceRef,listAgentToolNames,markWorkflowRunPersistenceActive,narrowAgentTools,persistInlineWorkflowScript,readAgentMeta,readWorkflowSourceRef,readWorkflowStepId,rebuildToolRegistryOnOverride,reportedFailureLines,resolveAgentExecutionBackend,resolveExternalWorktreeDir,resolveSavedWorkflowScript,resolveWorkflowSizeCaps,resolveWorkflowSizeGuidelineSetting,sanitizeWorkflowText,stringifyWorkflowResult,toModelVisibleSubagentResult,truncateWorkflowText,tryWithWorkflowTaskMutation,workflowPreLaunchGate,writeAgentMeta}from"./chunk-2JGTWRZJ.js";import{backgroundFixAt,backgroundFixHolding,settleBackgroundFix}from"./chunk-YVD4O5ZB.js";import{GitWorktreeService,generateAgentWorktreeSlug,writeWorktreeSessionMarker}from"./chunk-ILECDNJX.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{SUBAGENT_PLAN_LIFECYCLE_TOOLS}from"./chunk-GOZYWU4B.js";import{getCurrentAgentId,runWithAgentContext}from"./chunk-YZFNBUKG.js";import{createAbortController,createChildAbortController}from"./chunk-476F6QIM.js";import{WorkflowRunEvent,WorkflowSizeWarningEvent,logWorkflowRun,logWorkflowSizeWarning,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{parseLineTolerantWithIntegrity,writeLine}from"./chunk-UQFTXKEB.js";import{REASONING_EFFORT_TIERS,normalizeReasoningEffort}from"./chunk-GOR7FFVE.js";import{atomicWriteFile,renameWithRetry}from"./chunk-BMHYEQTI.js";import{SyntheticOutputTool}from"./chunk-URNNJMIC.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{SchemaValidator}from"./chunk-SVAPAMMG.js";import{ToolNames,resolveBuiltinToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger2=createDebugLogger("WORKFLOW_BUDGET");var MAX_TOKENS_PER_WORKFLOW_ENV="QWEN_CODE_MAX_TOKENS_PER_WORKFLOW";var HARD_MAX_TOKENS_CEILING=MAX_TURN_BUDGET_TOKENS;function resolveMaxTokensPerWorkflow(env=process.env){const raw=env[MAX_TOKENS_PER_WORKFLOW_ENV];if(raw===void 0||raw.trim()===""){return null}const parsed=parsePositiveIntegerEnv(raw,0);if(parsed<1){debugLogger2.warn(`Invalid ${MAX_TOKENS_PER_WORKFLOW_ENV}=${JSON.stringify(raw)}, treating as unset (no cap)`);return null}if(parsed>HARD_MAX_TOKENS_CEILING){debugLogger2.warn(`${MAX_TOKENS_PER_WORKFLOW_ENV}=${parsed} exceeds hard ceiling (${HARD_MAX_TOKENS_CEILING}); clamping.`);return HARD_MAX_TOKENS_CEILING}return parsed}__name(resolveMaxTokensPerWorkflow,"resolveMaxTokensPerWorkflow");var WorkflowBudgetImpl=class _WorkflowBudgetImpl{static{__name(this,"WorkflowBudgetImpl")}total;source;directiveText;turnSpent;_runSpent;constructor(total,options={}){this.total=total;this.source=total===null?void 0:options.source??"env";this.directiveText=this.source==="directive"?options.directiveText:void 0;this.turnSpent=options.turnSpent;this._runSpent=0}spent(){if(this.source!=="env"&&this.turnSpent)return this.turnSpent();return this._runSpent}runSpent(){return this._runSpent}runCap(){return this.source==="env"?this.total:null}remaining(){if(this.total===null)return Infinity;return Math.max(0,this.total-this.spent())}recordSpent(deltaTokens){if(!Number.isFinite(deltaTokens)||deltaTokens<=0)return;this._runSpent+=deltaTokens}static fromEnv(env=process.env){return new _WorkflowBudgetImpl(resolveMaxTokensPerWorkflow(env))}static fromConfig(config,env=process.env){const sessionId=config.getSessionId?.();const turn=sessionId===void 0?null:config.getTurnBudget?.()?.current(sessionId)??null;const turnSpent=turn?()=>Math.max(0,uiTelemetryService.getTotalOutputTokens(turn.sessionId)-turn.outputTokensAtTurnStart):void 0;if(turn&&turn.budget!==null){return new _WorkflowBudgetImpl(turn.budget,{source:"directive",turnSpent,directiveText:turn.directiveText})}const envCap=resolveMaxTokensPerWorkflow(env);if(envCap!==null){return new _WorkflowBudgetImpl(envCap,{source:"env"})}return new _WorkflowBudgetImpl(null,{turnSpent})}};var WorkflowBudgetExceededError=class extends Error{static{__name(this,"WorkflowBudgetExceededError")}name="WorkflowBudgetExceededError";runId;budgetTotal;spent;constructor(runId,budgetTotal,spent){super(`Workflow ${runId}: token budget exceeded (${spent} / ${budgetTotal} output tokens). Stopping further agent() calls.`);this.runId=runId;this.budgetTotal=budgetTotal;this.spent=spent}};init_esbuild_shims();import{randomBytes}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import*as os from"node:os";init_esbuild_shims();var WorkflowAgentFailedError=class extends Error{static{__name(this,"WorkflowAgentFailedError")}name="WorkflowAgentFailedError";kind;terminateMode;constructor(message,kind,terminateMode){super(message);this.kind=kind;this.terminateMode=terminateMode}};function isWorkflowAgentFailedError(error){return typeof error==="object"&&error!==null&&error.name==="WorkflowAgentFailedError"}__name(isWorkflowAgentFailedError,"isWorkflowAgentFailedError");var WorkflowAgentCapExceededError=class extends Error{static{__name(this,"WorkflowAgentCapExceededError")}name="WorkflowAgentCapExceededError";constructor(maxAgents){super(`Workflow exceeded the maximum of ${maxAgents} agent() calls per run. This usually means a loop using budget.remaining() never terminates because no token budget was set \u2014 remaining() returns Infinity when budget.total is null. Add a hard iteration cap to the loop, or pass a token budget.`)}};function isWorkflowRunLevelError(error){if(typeof error!=="object"||error===null)return false;const name=error.name;return error.__wfRunFailure===true||name==="WorkflowBudgetExceededError"||name==="WorkflowAgentCapExceededError"}__name(isWorkflowRunLevelError,"isWorkflowRunLevelError");var WORKFLOW_ABORT_REASON_STALLED="stalled";init_esbuild_shims();var DEFAULT_STALL_MS=18e4;var MAX_TIMER_DELAY_MS=2147483647;var MAX_STALL_ATTEMPTS=3;var MAX_WORKFLOW_STALL_MS_ENV="QWEN_CODE_WORKFLOW_STALL_SECONDS";function resolveStallMs(perCall,env=process.env){if(typeof perCall==="number"&&Number.isFinite(perCall)){if(perCall===0)return 0;if(perCall>0)return perCall}const raw=env[MAX_WORKFLOW_STALL_MS_ENV];const trimmed=raw?.trim();if(trimmed){if(trimmed==="0")return 0;const sec=parsePositiveIntegerEnv(trimmed,0);if(sec>0)return sec*1e3}return DEFAULT_STALL_MS}__name(resolveStallMs,"resolveStallMs");var debugLogger3=createDebugLogger("WORKFLOW_STALL");function attachStallWatchdog(emitter,controller,stallMs){if(stallMs<=0){return{stalled:__name(()=>false,"stalled"),dispose:__name(()=>{},"dispose")}}let inFlightTools=0;let fired=false;let timer;let disposed=false;let lastActivity;const waits=new Map;const startedWaitIds=new Set;const clear=__name(()=>{if(timer){clearTimeout(timer);timer=void 0}},"clear");const markActivity=__name(()=>{lastActivity=Math.max(lastActivity??0,performance.now())},"markActivity");const arm=__name(()=>{clear();if(disposed||fired)return;if(inFlightTools>0)return;if(lastActivity===void 0&&waits.size===0)return;const now=performance.now();let base=lastActivity??now;for(const[waitId,until]of waits){if(until<=now){waits.delete(waitId);lastActivity=Math.max(lastActivity??until,until)}base=Math.max(base,until)}const due=base+stallMs;if(due>now){timer=setTimeout(arm,Math.min(due-now,MAX_TIMER_DELAY_MS));timer.unref?.();return}fired=true;debugLogger3.warn(`[Workflow] agent dispatch stalled \u2014 no progress for ${stallMs}ms; aborting.`);try{controller.abort(WORKFLOW_ABORT_REASON_STALLED)}catch(e){debugLogger3.warn("stall watchdog abort threw:",e)}},"arm");const onActivity=__name(()=>{markActivity();arm()},"onActivity");const onToolCall=__name(()=>{inFlightTools+=1;clear()},"onToolCall");const onToolResult=__name(()=>{inFlightTools=Math.max(0,inFlightTools-1);markActivity();arm()},"onToolResult");const onRetryWait=__name(event=>{if(event.phase==="start"){if(startedWaitIds.has(event.waitId))return;if(!Number.isFinite(event.delayMs)||event.delayMs<=0)return;startedWaitIds.add(event.waitId);const now=performance.now();waits.set(event.waitId,now+event.delayMs);lastActivity??=now}else{if(!waits.delete(event.waitId))return;markActivity()}arm()},"onRetryWait");emitter.on("round_start",onActivity);emitter.on("round_end",onActivity);emitter.on("stream_text",onActivity);emitter.on("usage_metadata",onActivity);emitter.on("tool_call",onToolCall);emitter.on("tool_result",onToolResult);emitter.on("retry_wait",onRetryWait);return{stalled:__name(()=>fired,"stalled"),dispose:__name(()=>{if(disposed)return;disposed=true;clear();waits.clear();emitter.off("round_start",onActivity);emitter.off("round_end",onActivity);emitter.off("stream_text",onActivity);emitter.off("usage_metadata",onActivity);emitter.off("tool_call",onToolCall);emitter.off("tool_result",onToolResult);emitter.off("retry_wait",onRetryWait)},"dispose")}}__name(attachStallWatchdog,"attachStallWatchdog");async function runStallResilient(attemptFn,opts){const{stallMs,signal,label}=opts;if(stallMs<=0){const emitter=new AgentEventEmitter;return attemptFn(signal??new AbortController().signal,emitter)}let attempt=0;for(;;){attempt+=1;const controller=new AbortController;let onParentAbort;if(signal){if(signal.aborted){controller.abort(signal.reason)}else{onParentAbort=__name(()=>controller.abort(signal.reason),"onParentAbort");signal.addEventListener("abort",onParentAbort)}}const emitter=new AgentEventEmitter;const watchdog=attachStallWatchdog(emitter,controller,stallMs);try{return await attemptFn(controller.signal,emitter)}catch(err){if(signal?.aborted)throw err;if(watchdog.stalled()&&attempt<MAX_STALL_ATTEMPTS){debugLogger3.warn(`[Workflow] agent "${label??"workflow-agent"}" stalled (attempt ${attempt}/${MAX_STALL_ATTEMPTS}) \u2014 retrying.`);continue}if(watchdog.stalled()){throw new WorkflowAgentFailedError(`agent "${label??"workflow-agent"}" stalled on all ${MAX_STALL_ATTEMPTS} attempts (no progress for ${stallMs}ms each).`,"stalled")}throw err}finally{watchdog.dispose();if(onParentAbort&&signal){signal.removeEventListener("abort",onParentAbort)}}}}__name(runStallResilient,"runStallResilient");init_esbuild_shims();var MAX_ERROR_DETAIL_LENGTH=500;var MAX_KEY_LENGTH=120;var MAX_WALK_DEPTH=32;var MAX_WALK_NODES=1e3;var COMPOUND_KEYWORDS=["$ref","$dynamicRef","$recursiveRef","allOf","anyOf","oneOf","not","if","then","else","dependencies","dependentSchemas","dependentRequired","unevaluatedProperties","propertyNames"];function prepareWorkflowSchema(schema){const shape=describeNonObject(schema);if(shape!==void 0){return fail(`must be a JSON Schema object, got ${shape}.`)}let copy;try{copy=JSON.parse(JSON.stringify(schema))}catch(error){return fail(`is not JSON: ${errorText(error)}`)}const strictError=SchemaValidator.compileStrict(copy,{allowMatchingProperties:true});if(strictError!==null){return fail(`is not a valid JSON Schema: ${strictError}`)}if(copy["$async"]===true){return fail("uses $async, which structured output does not support. Remove $async.")}const contradiction=findContradiction(copy);if(contradiction!==void 0){return fail(contradiction)}const compiled=SchemaValidator.compileIsolated(copy);if(compiled.error!==void 0){return fail(`could not be compiled: ${compiled.error}`)}return{ok:true,validate:compiled.validate}}__name(prepareWorkflowSchema,"prepareWorkflowSchema");function validateStructuredResult(value,validate){if(typeof value!=="object"||value===null||Array.isArray(value)){return{error:"the result is not a JSON object"}}let copy;try{copy=JSON.parse(JSON.stringify(value))}catch(error){return{error:`the result is not JSON: ${errorText(error)}`}}try{const error=validate(copy);return error===null?{value:copy}:{error}}catch(error){return{error:errorText(error)}}}__name(validateStructuredResult,"validateStructuredResult");function fail(detail){return{ok:false,error:`agent({schema}): ${boundedDetail(detail)}`}}__name(fail,"fail");function boundedDetail(detail){const clean=stripAnsiAndControl(detail);return clean.length>MAX_ERROR_DETAIL_LENGTH?`${clean.slice(0,MAX_ERROR_DETAIL_LENGTH)}\u2026`:clean}__name(boundedDetail,"boundedDetail");function errorText(error){return error instanceof Error?error.message:String(error)}__name(errorText,"errorText");function describeNonObject(value){if(value===null)return"null";if(Array.isArray(value))return"an array";if(typeof value!=="object")return`a ${typeof value}`;return void 0}__name(describeNonObject,"describeNonObject");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function pointerToken(key){return key.replace(/~/g,"~0").replace(/\//g,"~1")}__name(pointerToken,"pointerToken");function quoteKey(key){const quoted=JSON.stringify(key);return quoted.length>MAX_KEY_LENGTH?`${quoted.slice(0,MAX_KEY_LENGTH)}\u2026"`:quoted}__name(quoteKey,"quoteKey");function typeAllowsObject(type){if(typeof type==="string")return type==="object";if(Array.isArray(type))return type.includes("object");return void 0}__name(typeAllowsObject,"typeAllowsObject");function isObjectOnly(node){const type=node["type"];const onlyObject=type==="object"||Array.isArray(type)&&type.length===1&&type[0]==="object";return onlyObject&&node["nullable"]!==true}__name(isObjectOnly,"isObjectOnly");function rootExcludesObject(root){if(typeAllowsObject(root["type"])===false){return`# does not accept an object (type ${stripAnsiAndControl(JSON.stringify(root["type"]))}); structured output is always a JSON object.`}if("const"in root&&!isRecord(root["const"])){return"# does not accept an object (its const is not an object); structured output is always a JSON object."}if(Array.isArray(root["enum"])&&!root["enum"].some(isRecord)){return"# does not accept an object (its enum has no object member); structured output is always a JSON object."}return void 0}__name(rootExcludesObject,"rootExcludesObject");function findContradiction(root){const rootProblem=rootExcludesObject(root);if(rootProblem!==void 0)return rootProblem;let visited=0;const visit=__name((node,pointer,depth)=>{visited+=1;if(depth>MAX_WALK_DEPTH||visited>MAX_WALK_NODES)return void 0;if(COMPOUND_KEYWORDS.some(keyword=>keyword in node))return void 0;const required=node["required"];if(!Array.isArray(required)||required.length===0)return void 0;if(!required.every(key=>typeof key==="string")){return void 0}const properties=isRecord(node["properties"])?node["properties"]:{};const patterns=compilePatterns(node["patternProperties"]);if(patterns===void 0)return void 0;const maxProperties=node["maxProperties"];const distinct=new Set(required);if(typeof maxProperties==="number"&&distinct.size>maxProperties){return`${pointer}/required lists ${distinct.size} distinct properties, but ${pointer}/maxProperties allows at most ${maxProperties}.`}for(let index=0;index<required.length;index++){const key=required[index];const requiredAt=`${pointer}/required/${index}`;const declared=Object.hasOwn(properties,key);const matching=patterns.filter(entry=>entry.regex.test(key));if(declared&&properties[key]===false){return`${requiredAt} requires ${quoteKey(key)}, but ${pointer}/properties/${pointerToken(key)} is false, which forbids it.`}const forbiddingPattern=matching.find(entry=>entry.schema===false);if(forbiddingPattern!==void 0){return`${requiredAt} requires ${quoteKey(key)}, but ${pointer}/patternProperties/${pointerToken(forbiddingPattern.source)} is false, which forbids it.`}if(!declared&&matching.length===0&&node["additionalProperties"]===false){return`${requiredAt} requires ${quoteKey(key)}, but this object forbids it via additionalProperties:false (it is not in properties and matches no patternProperties).`}}for(const key of distinct){if(!Object.hasOwn(properties,key))continue;const child=properties[key];if(!isRecord(child)||!isObjectOnly(child))continue;const problem=visit(child,`${pointer}/properties/${pointerToken(key)}`,depth+1);if(problem!==void 0)return problem}return void 0},"visit");return visit(root,"#",0)}__name(findContradiction,"findContradiction");function compilePatterns(value){if(value===void 0)return[];if(!isRecord(value))return void 0;const entries=[];for(const[source,schema]of Object.entries(value)){try{entries.push({source,regex:new RegExp(source,"u"),schema})}catch{return void 0}}return entries}__name(compilePatterns,"compilePatterns");init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{constants,promises as fs}from"node:fs";import path from"node:path";var debugLogger4=createDebugLogger("WORKFLOW_JOURNAL");var JOURNAL_KEY_VERSION="v2";var DISPATCH_AFFECTING_AGENT_OPTS=["schema","model","effort","isolation","agentType","workingDir","disallowedTools","tools"];function canonicalizeAgentOpts(opts){const projected={};for(const k of DISPATCH_AFFECTING_AGENT_OPTS){const v=opts[k];if(v===void 0||typeof v==="function")continue;projected[k]=v}const sortDeep=__name(val=>{if(typeof val==="function")return void 0;if(Array.isArray(val))return val.map(sortDeep);if(val&&typeof val==="object"){const out={};for(const key of Object.keys(val).sort()){if(key==="__proto__")continue;out[key]=sortDeep(val[key])}return out}return val},"sortDeep");try{return JSON.stringify(sortDeep(projected))}catch{return"{}"}}__name(canonicalizeAgentOpts,"canonicalizeAgentOpts");function deriveAgentKey(prefixHash,prompt,opts){const hash=createHash("sha256");hash.update(prefixHash);hash.update("\0");hash.update(prompt);hash.update("\0");hash.update(canonicalizeAgentOpts(opts));return`${JOURNAL_KEY_VERSION}:${hash.digest("hex")}`}__name(deriveAgentKey,"deriveAgentKey");function deriveArgsSeed(args){const hash=createHash("sha256");let serialized;try{serialized=JSON.stringify(args??null)??"null"}catch{serialized="non-serializable-args"}hash.update(serialized);return`${JOURNAL_KEY_VERSION}:${hash.digest("hex")}`}__name(deriveArgsSeed,"deriveArgsSeed");function buildReplay(entries){let sourceRef;let sourceError;const results=new Map;const started=new Map;const failed=new Set;for(const e of entries){if(e.type==="result"){results.set(e.key,e);failed.delete(e.key)}else if(e.type==="started"){results.delete(e.key);failed.delete(e.key);const list=started.get(e.key);if(list)list.push(e);else started.set(e.key,[e])}else if(e.type==="failed"){results.delete(e.key);failed.add(e.key)}else if(e.type==="source"){try{const ref=readWorkflowSourceRef(e.sourceRef);if(e.version!==1||!ref||sourceRef&&(sourceRef.id!==ref.id||sourceRef.revision!==ref.revision)){throw new Error("Conflicting or unsupported workflow source record.")}sourceRef=ref}catch{sourceError="Workflow journal contains invalid source metadata."}}}return{results,started,failed,...sourceRef?{sourceRef}:{},...sourceError?{sourceError}:{}}}__name(buildReplay,"buildReplay");function describeError(error){return error instanceof Error?error.message:String(error)}__name(describeError,"describeError");var WorkflowJournalWriteError=class extends Error{static{__name(this,"WorkflowJournalWriteError")}__wfRunFailure=true;constructor(cause){super("Could not persist workflow replay invalidation; subsequent agents were not started. Check storage and retry.",{cause});this.name="WorkflowJournalWriteError"}};async function readEntries(journalPath){const contents=await fs.readFile(journalPath,"utf8");const entries=[];for(const line of contents.split("\n")){if(!line.trim())continue;const parsed=parseLineTolerantWithIntegrity(line,journalPath);if(!parsed.complete)throw new Error("Workflow journal contains incomplete records.");for(const entry of parsed.records){if(typeof entry["type"]!=="string"||["started","failed","result"].includes(entry["type"])&&(typeof entry["key"]!=="string"||typeof entry["agentId"]!=="string"||entry["type"]==="result"&&!Object.hasOwn(entry,"result"))||entry["type"]==="launched"&&entry["version"]!==1){throw new Error("Workflow journal contains invalid records.")}entries.push(entry)}}return entries}__name(readEntries,"readEntries");var WorkflowJournal=class{constructor(journalPath,root=path.dirname(path.dirname(journalPath))){this.root=root;this.path=journalPath}static{__name(this,"WorkflowJournal")}pending=Promise.resolve();writeError;path;async hasSymlinkedPath(){if(await isSymlinkedRoot(this.root)||await isSymlinkedRoot(path.dirname(this.path))){return true}return fs.lstat(this.path).then(stat=>stat.isSymbolicLink()).catch(()=>false)}async ensureExists(){try{if(await this.hasSymlinkedPath())return false;await fs.mkdir(path.dirname(this.path),{recursive:true});if(await this.hasSymlinkedPath())return false;const noFollow=process.platform==="win32"?0:constants.O_NOFOLLOW;const file=await fs.open(this.path,constants.O_APPEND|constants.O_CREAT|constants.O_WRONLY|noFollow,384);try{await file.chmod(384)}finally{await file.close()}return true}catch(error){debugLogger4.warn(`WorkflowJournal.ensureExists failed for ${this.path}: ${error}`);return false}}async remove(){await this.drain();try{if(await this.hasSymlinkedPath())return;await fs.rm(this.path,{force:true});await fs.rmdir(path.dirname(this.path)).catch(error=>{const code=error.code;if(code!=="ENOENT"&&code!=="ENOTEMPTY")throw error})}catch(error){debugLogger4.warn(`WorkflowJournal.remove failed for ${this.path}: ${error}`)}}async load(){try{if(await this.hasSymlinkedPath())throw new Error("Workflow journal path is symlinked.");await fs.stat(this.path)}catch(e){if(e.code==="ENOENT"){return{kind:"missing"}}debugLogger4.warn(`WorkflowJournal.load failed for ${this.path}: ${e}`);return{kind:"unreadable",reason:describeError(e)}}try{const entries=await readEntries(this.path);return{kind:"loaded",replay:buildReplay(entries)}}catch(e){debugLogger4.warn(`WorkflowJournal.load failed for ${this.path}: ${e}`);return{kind:"unreadable",reason:describeError(e)}}}async markLaunched(){await this.append({type:"launched",version:1}).catch(error=>debugLogger4.warn(`WorkflowJournal.markLaunched failed for ${this.path}: ${error}`))}retainReplayPrefix(keys){const prefix=new Set(keys);const operation=this.pending.then(async()=>{if(this.writeError)throw this.writeError;let temporaryPath;try{if(await this.hasSymlinkedPath())throw new Error("Workflow journal path is symlinked.");const stat=await fs.stat(this.path);if(process.geteuid&&stat.uid!==process.geteuid()){throw new Error("Workflow journal is owned by another user.")}const entries=await readEntries(this.path);const replay=buildReplay(entries);if(replay.sourceError)throw new Error(replay.sourceError);const retained=entries.filter(entry=>entry.type!=="result"||prefix.has(entry.key));const candidate=`${this.path}.${randomUUID()}.tmp`;const file=await fs.open(candidate,"wx",384);temporaryPath=candidate;try{await file.writeFile(retained.map(entry=>JSON.stringify(entry)+"\n").join(""),"utf8");await file.sync()}finally{await file.close()}if(await this.hasSymlinkedPath())throw new Error("Workflow journal path is symlinked.");await renameWithRetry(temporaryPath,this.path,3,10,fs.rename);temporaryPath=void 0}catch(cause){this.writeError=new WorkflowJournalWriteError(cause);throw this.writeError}finally{if(temporaryPath){await fs.unlink(temporaryPath).catch(error=>debugLogger4.warn(`Workflow journal temporary file cleanup failed: ${error}`))}}});this.pending=operation.catch(()=>void 0);return operation}append(entry){const operation=this.pending.then(()=>{if(this.writeError)throw this.writeError;return writeLine(this.path,entry)});this.pending=operation.catch(()=>void 0);return operation}drain(){return this.pending}};init_esbuild_shims();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.';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- The third failed attempt ends the run \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.";init_esbuild_shims();function abortError(){return new DOMException("Workflow dispatch scheduler aborted.","AbortError")}__name(abortError,"abortError");var WorkflowDispatchScheduler=class{constructor(limit,signal,onStateChange){this.limit=limit;this.signal=signal;if(!Number.isInteger(limit)||limit<1){throw new Error(`Workflow dispatch limit must be a positive integer, got ${String(limit)}.`)}if(onStateChange)this.stateListeners.add(onStateChange);if(signal&&!signal.aborted){signal.addEventListener("abort",()=>this.abortPending(),{once:true})}}static{__name(this,"WorkflowDispatchScheduler")}state="running";inFlight=0;queue=[];gateWaiters=[];stateListeners=new Set;onStateChange(listener){this.stateListeners.add(listener);return()=>{this.stateListeners.delete(listener)}}run(thunk){return new Promise((resolve2,reject)=>{if(this.signal?.aborted){reject(abortError());return}this.queue.push({thunk,resolve:resolve2,reject});this.pump()})}pause(){if(this.state!=="running"||this.signal?.aborted)return false;this.setState("pausing");if(this.inFlight===0)this.setState("paused");return true}resume(){if(this.state!=="paused"||this.signal?.aborted)return false;this.setState("running");while(this.gateWaiters.length>0){this.gateWaiters.shift().resolve()}this.pump();return true}waitUntilRunning(){if(this.signal?.aborted)return Promise.reject(abortError());if(this.state==="running")return Promise.resolve();return new Promise((resolve2,reject)=>{this.gateWaiters.push({resolve:resolve2,reject})})}snapshot(){return{state:this.state,queued:this.queue.length,inFlight:this.inFlight}}pump(){while(this.state==="running"&&this.inFlight<this.limit&&this.queue.length>0){const job=this.queue.shift();if(this.signal?.aborted){job.reject(abortError());continue}this.inFlight++;Promise.resolve().then(job.thunk).then(job.resolve,job.reject).finally(()=>{this.inFlight--;if(this.state==="pausing"&&this.inFlight===0){this.setState("paused")}this.pump()})}}setState(state){if(this.state===state)return;this.state=state;const snapshot=this.snapshot();for(const listener of[...this.stateListeners])listener(snapshot)}abortPending(){const error=abortError();while(this.queue.length>0)this.queue.shift().reject(error);while(this.gateWaiters.length>0){this.gateWaiters.shift().reject(error)}}};var DEFAULT_MAX_AGENTS_PER_RUN=1e3;var MAX_WORKFLOW_AGENTS_ENV="QWEN_CODE_MAX_WORKFLOW_AGENTS";var HARD_MAX_AGENTS_PER_RUN_CEILING=1e4;function resolveMaxAgentsPerRun(env=process.env){const raw=env[MAX_WORKFLOW_AGENTS_ENV];if(raw===void 0||raw.trim()===""){return DEFAULT_MAX_AGENTS_PER_RUN}const parsed=parsePositiveIntegerEnv(raw,0);if(parsed<1){debugLogger.warn(`Invalid ${MAX_WORKFLOW_AGENTS_ENV}=${JSON.stringify(raw)}, using default (${DEFAULT_MAX_AGENTS_PER_RUN})`);return DEFAULT_MAX_AGENTS_PER_RUN}if(parsed>HARD_MAX_AGENTS_PER_RUN_CEILING){debugLogger.warn(`${MAX_WORKFLOW_AGENTS_ENV}=${parsed} exceeds hard ceiling (${HARD_MAX_AGENTS_PER_RUN_CEILING}); clamping.`);return HARD_MAX_AGENTS_PER_RUN_CEILING}return parsed}__name(resolveMaxAgentsPerRun,"resolveMaxAgentsPerRun");var MAX_WORKFLOW_CONCURRENCY_ENV="QWEN_CODE_MAX_WORKFLOW_CONCURRENCY";var HARD_MAX_CONCURRENCY_CEILING=64;function resolveConcurrencyLimit(env=process.env,availableParallelism2=os.availableParallelism){const raw=env[MAX_WORKFLOW_CONCURRENCY_ENV];if(raw!==void 0&&raw.trim()!==""){const parsed=parsePositiveIntegerEnv(raw,0);if(parsed>=1){if(parsed>HARD_MAX_CONCURRENCY_CEILING){debugLogger.warn(`${MAX_WORKFLOW_CONCURRENCY_ENV}=${parsed} exceeds hard ceiling (${HARD_MAX_CONCURRENCY_CEILING}); clamping.`);return HARD_MAX_CONCURRENCY_CEILING}return parsed}debugLogger.warn(`Invalid ${MAX_WORKFLOW_CONCURRENCY_ENV}=${JSON.stringify(raw)}, using cpu-derived default`)}return Math.max(2,Math.min(16,availableParallelism2()-2))}__name(resolveConcurrencyLimit,"resolveConcurrencyLimit");var DEFAULT_WORKFLOW_SUBAGENT_MAX_TURNS=50;var DEFAULT_WORKFLOW_SUBAGENT_MAX_TIME_MINUTES=10;var WORKFLOW_SUBAGENT_MAX_TURNS_ENV="QWEN_CODE_WORKFLOW_AGENT_MAX_TURNS";var WORKFLOW_SUBAGENT_MAX_MINUTES_ENV="QWEN_CODE_WORKFLOW_AGENT_MAX_MINUTES";var HARD_WORKFLOW_SUBAGENT_MAX_TURNS_CEILING=500;var HARD_WORKFLOW_SUBAGENT_MAX_MINUTES_CEILING=100;function resolveSubagentBound(envName,defaultValue,ceiling,env){const raw=env[envName];if(raw===void 0||raw.trim()==="")return defaultValue;const parsed=parsePositiveIntegerEnv(raw,0);if(parsed<1){debugLogger.warn(`Invalid ${envName}=${JSON.stringify(raw)}, using default (${defaultValue})`);return defaultValue}if(parsed>ceiling){debugLogger.warn(`${envName}=${parsed} exceeds hard ceiling (${ceiling}); clamping.`);return ceiling}return parsed}__name(resolveSubagentBound,"resolveSubagentBound");function resolveSubagentMaxTurns(env=process.env,defaultValue=DEFAULT_WORKFLOW_SUBAGENT_MAX_TURNS){return resolveSubagentBound(WORKFLOW_SUBAGENT_MAX_TURNS_ENV,defaultValue,HARD_WORKFLOW_SUBAGENT_MAX_TURNS_CEILING,env)}__name(resolveSubagentMaxTurns,"resolveSubagentMaxTurns");function resolveSubagentMaxTimeMinutes(env=process.env,defaultValue=DEFAULT_WORKFLOW_SUBAGENT_MAX_TIME_MINUTES){return resolveSubagentBound(WORKFLOW_SUBAGENT_MAX_MINUTES_ENV,defaultValue,HARD_WORKFLOW_SUBAGENT_MAX_MINUTES_CEILING,env)}__name(resolveSubagentMaxTimeMinutes,"resolveSubagentMaxTimeMinutes");var WORKFLOW_SUBAGENT_DISALLOWED_TOOLS=[ToolNames.ASK_USER_QUESTION,ToolNames.SEND_MESSAGE,ToolNames.MONITOR,...SUBAGENT_PLAN_LIFECYCLE_TOOLS,ToolNames.AGENT];var WorkflowExecutionError=class extends Error{constructor(message,phases,logs,meta=null){super(message);this.phases=phases;this.logs=logs;this.meta=meta}static{__name(this,"WorkflowExecutionError")}name="WorkflowExecutionError"};function runBudgetFigures(budget){return[budget.runSpent?budget.runSpent():budget.spent(),budget.runCap?budget.runCap():budget.total]}__name(runBudgetFigures,"runBudgetFigures");function generateRunId(){return`wf_${randomBytes(8).toString("hex")}`}__name(generateRunId,"generateRunId");function sanitizeForErrorMessage(value){return stripAnsiAndControl(value)}__name(sanitizeForErrorMessage,"sanitizeForErrorMessage");function createProductionDispatch(config,signal,onTokens,bridgeApprovalEvents,subagentBounds,refuseSubagentTools,parentToolCallId){return async(prompt,opts,dispatchId)=>{if(typeof prompt!=="string"||prompt.length===0){throw new Error("agent() requires a non-empty string prompt.")}if(refuseSubagentTools===true){const hostBound=HOST_BOUND_AGENT_OPTS.filter(key=>opts[key]!==void 0);if(hostBound.length>0){throw new Error(`agent({${hostBound.join(", ")}}): unavailable in this workflow \u2014 its agents carry no tools and use nothing on this host, so only text-only agent() calls (optionally with model, effort or schema) can run.`)}}const stallMs=resolveStallMs(typeof opts.stallMs==="number"?opts.stallMs:void 0);const workflowAgentId=`workflow-agent-${randomBytes(8).toString("hex")}`+(parentToolCallId?`-${parentToolCallId}`:"");const agentIdentity=await resolveWorkflowAgentIdentity(config,opts);if(resolveAgentExecutionBackend(config,agentIdentity.resolvedAgentType)==="container"){throw Object.assign(new Error("Container execution is required; workflow agents are unsupported. Start a regular subagent instead."),{__wfRunFailure:true})}if(agentIdentity.resolvedAgentType?.executor!==void 0){throw new Error("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.")}let attempt=0;let finishTranscript=__name(()=>{},"finishTranscript");let status="failed";try{const result=await runStallResilient(async(attemptSignal,emitter)=>{attempt+=1;const cleanupApprovalBridge=bridgeApprovalEvents?.(emitter,dispatchId);const cleanupTranscript=attachDispatchTranscript(config,workflowAgentId,prompt,agentIdentity.name,emitter,attempt);finishTranscript=cleanupTranscript;try{return await runSingleDispatch(config,prompt,opts,attemptSignal,emitter,workflowAgentId,agentIdentity,onTokens,subagentBounds,refuseSubagentTools)}finally{cleanupTranscript("running");cleanupApprovalBridge?.()}},{stallMs,signal,label:sanitizeForErrorMessage(agentIdentity.name)});status="completed";return result}finally{finishTranscript(status==="failed"&&signal?.aborted?"cancelled":status)}}}__name(createProductionDispatch,"createProductionDispatch");var HOST_BOUND_AGENT_OPTS=["agentType","isolation","workingDir"];async function resolveWorkflowAgentIdentity(config,opts){if(opts.agentType){const resolved=await config.getSubagentManager().findSubagentByName(opts.agentType);if(resolved){return{name:resolved.name,resolvedAgentType:resolved}}}if(typeof opts.label==="string"&&opts.label){return{name:opts.label}}return{name:opts.agentType||"workflow-agent"}}__name(resolveWorkflowAgentIdentity,"resolveWorkflowAgentIdentity");function attachDispatchTranscript(config,agentId,prompt,agentName,emitter,attempt){const append=attempt>1;try{const{jsonlPath,options}=buildAgentTranscriptAttach(config,agentId,{agentName,initialUserPrompt:append?void 0:prompt,appendToExisting:append,retryAttempt:append?attempt:void 0});const writer=attachJsonlTranscriptWriter(emitter,jsonlPath,options);const metaPath=getAgentMetaPath(config.storage.getProjectDir(),options.sessionId,agentId);const now=new Date().toISOString();const meta={agentId,agentType:stripAnsiAndControl(agentName).slice(0,200)||"workflow-agent",description:stripAnsiAndControl(prompt).slice(0,4096),parentSessionId:options.sessionId,parentAgentId:getCurrentAgentId()??null,createdAt:(append?readAgentMeta(metaPath)?.createdAt:void 0)??now,lastUpdatedAt:now,status:"running",isBackgrounded:false,workflowOwner:{pid:process.pid,hostname:os.hostname()}};writeAgentMeta(metaPath,meta);return status=>{writer.cleanup();writeAgentMeta(metaPath,{...meta,status,lastUpdatedAt:new Date().toISOString()})}}catch(error){debugLogger.warn(`[Workflow] failed to attach transcript for ${agentId}: ${error}`);return()=>{}}}__name(attachDispatchTranscript,"attachDispatchTranscript");function terminalDispatchError(workflowAgentId,mode){const message=`Workflow subagent ${workflowAgentId} did not complete (terminate mode: ${mode}).`;switch(mode){case"MAX_TURNS":return new WorkflowAgentFailedError(message,"max_turns",mode);case"TIMEOUT":return new WorkflowAgentFailedError(message,"timeout",mode);case"ERROR":return new WorkflowAgentFailedError(message,"error",mode);default:return new Error(message)}}__name(terminalDispatchError,"terminalDispatchError");async function runSingleDispatch(config,prompt,opts,attemptSignal,emitter,workflowAgentId,agentIdentity,onTokens,subagentBounds,refuseSubagentTools){const{AgentHeadless,ContextState}=await import("./agent-headless-FQX3JGG6.js");const ctx=new ContextState;ctx.set("task_prompt",prompt);debugLogger.debug(`[workflow] Dispatch ${workflowAgentId}`);const ownDir=config.getTargetDir?.();if(opts.workingDir===void 0&&ownDir){await settleBackgroundFix({within:ownDir})}if(opts.workingDir===void 0&&ownDir&&backgroundFixHolding(ownDir,getCurrentAgentId())){throw new Error(`agent(): a background fix agent of /autofix-pr is working in ${ownDir}; its round goes on when it ends.`)}if(DISPATCH_AFFECTING_AGENT_OPTS.every(key=>opts[key]===void 0)){const subagent=await AgentHeadless.create(agentIdentity.name,config,{systemPrompt:WORKFLOW_SUBAGENT_SYSTEM_PROMPT},{},subagentBounds??{max_turns:resolveSubagentMaxTurns(),max_time_minutes:resolveSubagentMaxTimeMinutes()},refuseSubagentTools===true?{tools:[],disallowedTools:[]}:{tools:["*"],disallowedTools:WORKFLOW_SUBAGENT_DISALLOWED_TOOLS},emitter,void 0,void 0,prompt,workflowAgentId);try{await runWithAgentContext(workflowAgentId,()=>subagent.execute(ctx,attemptSignal,{enforceTimeLimitDuringRetryWait:true}))}finally{reportTokens(subagent,opts,onTokens)}const mode=subagent.getTerminateMode();if(mode!=="GOAL"){throw terminalDispatchError(workflowAgentId,mode)}return toModelVisibleSubagentResult(subagent.getFinalText(),mode)}return runOverridePath(config,ctx,opts,attemptSignal,workflowAgentId,agentIdentity,onTokens,emitter,subagentBounds,refuseSubagentTools)}__name(runSingleDispatch,"runSingleDispatch");function reportTokens(subagent,opts,onTokens){if(!onTokens)return;try{const summary=subagent.getExecutionSummary();onTokens(summary.outputTokens,opts)}catch(e){debugLogger.warn("onTokens callback threw:",e)}}__name(reportTokens,"reportTokens");function resolveDispatchEffort(raw){if(raw===void 0)return void 0;const tier=typeof raw==="string"?normalizeReasoningEffort(raw):void 0;if(tier===void 0){throw new Error(`agent({effort}): unknown effort tier ${sanitizeForErrorMessage(JSON.stringify(raw)??String(raw))}. Known tiers are: ${REASONING_EFFORT_TIERS.join(", ")}.`)}return tier}__name(resolveDispatchEffort,"resolveDispatchEffort");function resolveDispatchDenies(raw){if(raw===void 0)return[];if(!Array.isArray(raw)||raw.some(name=>typeof name!=="string"||name.length===0||name!==name.trim())){throw new Error("agent({disallowedTools}): must be an array of non-empty tool-name strings without surrounding whitespace, e.g. ['run_shell_command', 'write_file'].")}return raw.map(name=>resolveBuiltinToolName(name)??name)}__name(resolveDispatchDenies,"resolveDispatchDenies");function resolveDispatchAllows(raw){if(raw===void 0)return void 0;if(!Array.isArray(raw)||raw.length===0||raw.some(name=>typeof name!=="string"||name.length===0||name!==name.trim())){throw new Error("agent({tools}): must be a non-empty array of tool-name strings without surrounding whitespace, e.g. ['run_shell_command', 'read_file']. Omit tools to keep every tool.")}for(const name of raw){const problem=describeAgentToolAllowEntryProblem(name);if(problem!==null){throw new Error(`agent({tools}): ${sanitizeForErrorMessage(problem)}`)}}return[...new Set(raw.map(canonicalAgentToolName))]}__name(resolveDispatchAllows,"resolveDispatchAllows");async function runOverridePath(config,ctx,opts,signal,workflowAgentId,agentIdentity,onTokens,emitter,subagentBounds,refuseSubagentTools){if(opts.isolation==="remote"){throw new Error("agent({isolation:'remote'}) is not available in this build.")}let schemaValidate;if(opts.schema!==void 0){const prepared=prepareWorkflowSchema(opts.schema);if(!prepared.ok){throw new Error(prepared.error)}schemaValidate=prepared.validate}const effort=resolveDispatchEffort(opts.effort);const requestedDenies=resolveDispatchDenies(opts.disallowedTools);const requestedAllows=resolveDispatchAllows(opts.tools);const subagentMgr=config.getSubagentManager();let baseConfig;if(opts.agentType!==void 0){const resolved=agentIdentity.resolvedAgentType;if(!resolved){const safeAgentType=sanitizeForErrorMessage(opts.agentType);throw new Error(`agent({agentType}): agent type '${safeAgentType}' not found.`)}baseConfig=resolved}else{baseConfig={name:agentIdentity.name,description:"Default workflow subagent (per-call overrides).",systemPrompt:WORKFLOW_SUBAGENT_SYSTEM_PROMPT,level:"session",isBuiltin:false}}let schemaSystemPrompt;if(opts.schema!==void 0){schemaSystemPrompt=opts.agentType!==void 0&&baseConfig.systemPrompt?`${baseConfig.systemPrompt}
3
+ import{AgentEventEmitter,MAX_FAILURE_LINE_CHARS,MAX_TURN_BUDGET_TOKENS,MAX_WORKFLOW_CALL_TRACES,REPORTED_FAILURE_KEYS,WORKFLOW_BATCH_LIMIT,attachJsonlTranscriptWriter,buildAgentTranscriptAttach,canonicalAgentToolName,createWorkflowSandbox,debugLogger,deleteInlineWorkflowScript,deriveApprovalModeConfig,deriveConfig,deriveWorktreeConfig,describeAgentToolAllowEntryProblem,describeOversizedBatch,evaluateWorkflowSize,getAgentMetaPath,getWorkflowTaskMutationKey,installSessionWorkflowRevisionWriteThrough,isActiveWorkflowStatus,isSymlinkedRoot,isTerminalWorkflowStatus,isWorkflowRunId,isWorkflowRunPersistenceActive,isWorkflowSizeWarning,isWorkflowSourceRef,listAgentToolNames,markWorkflowRunPersistenceActive,narrowAgentTools,persistInlineWorkflowScript,readAgentMeta,readWorkflowSourceRef,readWorkflowStepId,rebuildToolRegistryOnOverride,reportedFailureLines,resolveAgentExecutionBackend,resolveExternalWorktreeDir,resolveSavedWorkflowScript,resolveWorkflowSizeCaps,resolveWorkflowSizeGuidelineSetting,sanitizeWorkflowText,stringifyWorkflowResult,toModelVisibleSubagentResult,truncateWorkflowText,tryWithWorkflowTaskMutation,workflowPreLaunchGate,writeAgentMeta}from"./chunk-7XQ5D34E.js";import{backgroundFixAt,backgroundFixHolding,settleBackgroundFix}from"./chunk-YVD4O5ZB.js";import{GitWorktreeService,generateAgentWorktreeSlug,writeWorktreeSessionMarker}from"./chunk-ILECDNJX.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{SUBAGENT_PLAN_LIFECYCLE_TOOLS}from"./chunk-GOZYWU4B.js";import{getCurrentAgentId,runWithAgentContext}from"./chunk-YZFNBUKG.js";import{createAbortController,createChildAbortController}from"./chunk-476F6QIM.js";import{WorkflowRunEvent,WorkflowSizeWarningEvent,logWorkflowRun,logWorkflowSizeWarning,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{parseLineTolerantWithIntegrity,writeLine}from"./chunk-UQFTXKEB.js";import{REASONING_EFFORT_TIERS,normalizeReasoningEffort}from"./chunk-GOR7FFVE.js";import{atomicWriteFile,renameWithRetry}from"./chunk-BMHYEQTI.js";import{SyntheticOutputTool}from"./chunk-URNNJMIC.js";import{stripAnsiAndControl}from"./chunk-DBRQGEEI.js";import{SchemaValidator}from"./chunk-SVAPAMMG.js";import{ToolNames,resolveBuiltinToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger2=createDebugLogger("WORKFLOW_BUDGET");var MAX_TOKENS_PER_WORKFLOW_ENV="QWEN_CODE_MAX_TOKENS_PER_WORKFLOW";var HARD_MAX_TOKENS_CEILING=MAX_TURN_BUDGET_TOKENS;function resolveMaxTokensPerWorkflow(env=process.env){const raw=env[MAX_TOKENS_PER_WORKFLOW_ENV];if(raw===void 0||raw.trim()===""){return null}const parsed=parsePositiveIntegerEnv(raw,0);if(parsed<1){debugLogger2.warn(`Invalid ${MAX_TOKENS_PER_WORKFLOW_ENV}=${JSON.stringify(raw)}, treating as unset (no cap)`);return null}if(parsed>HARD_MAX_TOKENS_CEILING){debugLogger2.warn(`${MAX_TOKENS_PER_WORKFLOW_ENV}=${parsed} exceeds hard ceiling (${HARD_MAX_TOKENS_CEILING}); clamping.`);return HARD_MAX_TOKENS_CEILING}return parsed}__name(resolveMaxTokensPerWorkflow,"resolveMaxTokensPerWorkflow");var WorkflowBudgetImpl=class _WorkflowBudgetImpl{static{__name(this,"WorkflowBudgetImpl")}total;source;directiveText;turnSpent;_runSpent;constructor(total,options={}){this.total=total;this.source=total===null?void 0:options.source??"env";this.directiveText=this.source==="directive"?options.directiveText:void 0;this.turnSpent=options.turnSpent;this._runSpent=0}spent(){if(this.source!=="env"&&this.turnSpent)return this.turnSpent();return this._runSpent}runSpent(){return this._runSpent}runCap(){return this.source==="env"?this.total:null}remaining(){if(this.total===null)return Infinity;return Math.max(0,this.total-this.spent())}recordSpent(deltaTokens){if(!Number.isFinite(deltaTokens)||deltaTokens<=0)return;this._runSpent+=deltaTokens}static fromEnv(env=process.env){return new _WorkflowBudgetImpl(resolveMaxTokensPerWorkflow(env))}static fromConfig(config,env=process.env){const sessionId=config.getSessionId?.();const turn=sessionId===void 0?null:config.getTurnBudget?.()?.current(sessionId)??null;const turnSpent=turn?()=>Math.max(0,uiTelemetryService.getTotalOutputTokens(turn.sessionId)-turn.outputTokensAtTurnStart):void 0;if(turn&&turn.budget!==null){return new _WorkflowBudgetImpl(turn.budget,{source:"directive",turnSpent,directiveText:turn.directiveText})}const envCap=resolveMaxTokensPerWorkflow(env);if(envCap!==null){return new _WorkflowBudgetImpl(envCap,{source:"env"})}return new _WorkflowBudgetImpl(null,{turnSpent})}};var WorkflowBudgetExceededError=class extends Error{static{__name(this,"WorkflowBudgetExceededError")}name="WorkflowBudgetExceededError";runId;budgetTotal;spent;constructor(runId,budgetTotal,spent){super(`Workflow ${runId}: token budget exceeded (${spent} / ${budgetTotal} output tokens). Stopping further agent() calls.`);this.runId=runId;this.budgetTotal=budgetTotal;this.spent=spent}};init_esbuild_shims();import{randomBytes}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import*as os from"node:os";init_esbuild_shims();var WorkflowAgentFailedError=class extends Error{static{__name(this,"WorkflowAgentFailedError")}name="WorkflowAgentFailedError";kind;terminateMode;constructor(message,kind,terminateMode){super(message);this.kind=kind;this.terminateMode=terminateMode}};function isWorkflowAgentFailedError(error){return typeof error==="object"&&error!==null&&error.name==="WorkflowAgentFailedError"}__name(isWorkflowAgentFailedError,"isWorkflowAgentFailedError");var WorkflowAgentCapExceededError=class extends Error{static{__name(this,"WorkflowAgentCapExceededError")}name="WorkflowAgentCapExceededError";constructor(maxAgents){super(`Workflow exceeded the maximum of ${maxAgents} agent() calls per run. This usually means a loop using budget.remaining() never terminates because no token budget was set \u2014 remaining() returns Infinity when budget.total is null. Add a hard iteration cap to the loop, or pass a token budget.`)}};function isWorkflowRunLevelError(error){if(typeof error!=="object"||error===null)return false;const name=error.name;return error.__wfRunFailure===true||name==="WorkflowBudgetExceededError"||name==="WorkflowAgentCapExceededError"}__name(isWorkflowRunLevelError,"isWorkflowRunLevelError");var WORKFLOW_ABORT_REASON_STALLED="stalled";init_esbuild_shims();var DEFAULT_STALL_MS=18e4;var MAX_TIMER_DELAY_MS=2147483647;var MAX_STALL_ATTEMPTS=3;var MAX_WORKFLOW_STALL_MS_ENV="QWEN_CODE_WORKFLOW_STALL_SECONDS";function resolveStallMs(perCall,env=process.env){if(typeof perCall==="number"&&Number.isFinite(perCall)){if(perCall===0)return 0;if(perCall>0)return perCall}const raw=env[MAX_WORKFLOW_STALL_MS_ENV];const trimmed=raw?.trim();if(trimmed){if(trimmed==="0")return 0;const sec=parsePositiveIntegerEnv(trimmed,0);if(sec>0)return sec*1e3}return DEFAULT_STALL_MS}__name(resolveStallMs,"resolveStallMs");var debugLogger3=createDebugLogger("WORKFLOW_STALL");function attachStallWatchdog(emitter,controller,stallMs){if(stallMs<=0){return{stalled:__name(()=>false,"stalled"),dispose:__name(()=>{},"dispose")}}let inFlightTools=0;let fired=false;let timer;let disposed=false;let lastActivity;const waits=new Map;const startedWaitIds=new Set;const clear=__name(()=>{if(timer){clearTimeout(timer);timer=void 0}},"clear");const markActivity=__name(()=>{lastActivity=Math.max(lastActivity??0,performance.now())},"markActivity");const arm=__name(()=>{clear();if(disposed||fired)return;if(inFlightTools>0)return;if(lastActivity===void 0&&waits.size===0)return;const now=performance.now();let base=lastActivity??now;for(const[waitId,until]of waits){if(until<=now){waits.delete(waitId);lastActivity=Math.max(lastActivity??until,until)}base=Math.max(base,until)}const due=base+stallMs;if(due>now){timer=setTimeout(arm,Math.min(due-now,MAX_TIMER_DELAY_MS));timer.unref?.();return}fired=true;debugLogger3.warn(`[Workflow] agent dispatch stalled \u2014 no progress for ${stallMs}ms; aborting.`);try{controller.abort(WORKFLOW_ABORT_REASON_STALLED)}catch(e){debugLogger3.warn("stall watchdog abort threw:",e)}},"arm");const onActivity=__name(()=>{markActivity();arm()},"onActivity");const onToolCall=__name(()=>{inFlightTools+=1;clear()},"onToolCall");const onToolResult=__name(()=>{inFlightTools=Math.max(0,inFlightTools-1);markActivity();arm()},"onToolResult");const onRetryWait=__name(event=>{if(event.phase==="start"){if(startedWaitIds.has(event.waitId))return;if(!Number.isFinite(event.delayMs)||event.delayMs<=0)return;startedWaitIds.add(event.waitId);const now=performance.now();waits.set(event.waitId,now+event.delayMs);lastActivity??=now}else{if(!waits.delete(event.waitId))return;markActivity()}arm()},"onRetryWait");emitter.on("round_start",onActivity);emitter.on("round_end",onActivity);emitter.on("stream_text",onActivity);emitter.on("usage_metadata",onActivity);emitter.on("tool_call",onToolCall);emitter.on("tool_result",onToolResult);emitter.on("retry_wait",onRetryWait);return{stalled:__name(()=>fired,"stalled"),dispose:__name(()=>{if(disposed)return;disposed=true;clear();waits.clear();emitter.off("round_start",onActivity);emitter.off("round_end",onActivity);emitter.off("stream_text",onActivity);emitter.off("usage_metadata",onActivity);emitter.off("tool_call",onToolCall);emitter.off("tool_result",onToolResult);emitter.off("retry_wait",onRetryWait)},"dispose")}}__name(attachStallWatchdog,"attachStallWatchdog");async function runStallResilient(attemptFn,opts){const{stallMs,signal,label}=opts;if(stallMs<=0){const emitter=new AgentEventEmitter;return attemptFn(signal??new AbortController().signal,emitter)}let attempt=0;for(;;){attempt+=1;const controller=new AbortController;let onParentAbort;if(signal){if(signal.aborted){controller.abort(signal.reason)}else{onParentAbort=__name(()=>controller.abort(signal.reason),"onParentAbort");signal.addEventListener("abort",onParentAbort)}}const emitter=new AgentEventEmitter;const watchdog=attachStallWatchdog(emitter,controller,stallMs);try{return await attemptFn(controller.signal,emitter)}catch(err){if(signal?.aborted)throw err;if(watchdog.stalled()&&attempt<MAX_STALL_ATTEMPTS){debugLogger3.warn(`[Workflow] agent "${label??"workflow-agent"}" stalled (attempt ${attempt}/${MAX_STALL_ATTEMPTS}) \u2014 retrying.`);continue}if(watchdog.stalled()){throw new WorkflowAgentFailedError(`agent "${label??"workflow-agent"}" stalled on all ${MAX_STALL_ATTEMPTS} attempts (no progress for ${stallMs}ms each).`,"stalled")}throw err}finally{watchdog.dispose();if(onParentAbort&&signal){signal.removeEventListener("abort",onParentAbort)}}}}__name(runStallResilient,"runStallResilient");init_esbuild_shims();var MAX_ERROR_DETAIL_LENGTH=500;var MAX_KEY_LENGTH=120;var MAX_WALK_DEPTH=32;var MAX_WALK_NODES=1e3;var COMPOUND_KEYWORDS=["$ref","$dynamicRef","$recursiveRef","allOf","anyOf","oneOf","not","if","then","else","dependencies","dependentSchemas","dependentRequired","unevaluatedProperties","propertyNames"];function prepareWorkflowSchema(schema){const shape=describeNonObject(schema);if(shape!==void 0){return fail(`must be a JSON Schema object, got ${shape}.`)}let copy;try{copy=JSON.parse(JSON.stringify(schema))}catch(error){return fail(`is not JSON: ${errorText(error)}`)}const strictError=SchemaValidator.compileStrict(copy,{allowMatchingProperties:true});if(strictError!==null){return fail(`is not a valid JSON Schema: ${strictError}`)}if(copy["$async"]===true){return fail("uses $async, which structured output does not support. Remove $async.")}const contradiction=findContradiction(copy);if(contradiction!==void 0){return fail(contradiction)}const compiled=SchemaValidator.compileIsolated(copy);if(compiled.error!==void 0){return fail(`could not be compiled: ${compiled.error}`)}return{ok:true,validate:compiled.validate}}__name(prepareWorkflowSchema,"prepareWorkflowSchema");function validateStructuredResult(value,validate){if(typeof value!=="object"||value===null||Array.isArray(value)){return{error:"the result is not a JSON object"}}let copy;try{copy=JSON.parse(JSON.stringify(value))}catch(error){return{error:`the result is not JSON: ${errorText(error)}`}}try{const error=validate(copy);return error===null?{value:copy}:{error}}catch(error){return{error:errorText(error)}}}__name(validateStructuredResult,"validateStructuredResult");function fail(detail){return{ok:false,error:`agent({schema}): ${boundedDetail(detail)}`}}__name(fail,"fail");function boundedDetail(detail){const clean=stripAnsiAndControl(detail);return clean.length>MAX_ERROR_DETAIL_LENGTH?`${clean.slice(0,MAX_ERROR_DETAIL_LENGTH)}\u2026`:clean}__name(boundedDetail,"boundedDetail");function errorText(error){return error instanceof Error?error.message:String(error)}__name(errorText,"errorText");function describeNonObject(value){if(value===null)return"null";if(Array.isArray(value))return"an array";if(typeof value!=="object")return`a ${typeof value}`;return void 0}__name(describeNonObject,"describeNonObject");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function pointerToken(key){return key.replace(/~/g,"~0").replace(/\//g,"~1")}__name(pointerToken,"pointerToken");function quoteKey(key){const quoted=JSON.stringify(key);return quoted.length>MAX_KEY_LENGTH?`${quoted.slice(0,MAX_KEY_LENGTH)}\u2026"`:quoted}__name(quoteKey,"quoteKey");function typeAllowsObject(type){if(typeof type==="string")return type==="object";if(Array.isArray(type))return type.includes("object");return void 0}__name(typeAllowsObject,"typeAllowsObject");function isObjectOnly(node){const type=node["type"];const onlyObject=type==="object"||Array.isArray(type)&&type.length===1&&type[0]==="object";return onlyObject&&node["nullable"]!==true}__name(isObjectOnly,"isObjectOnly");function rootExcludesObject(root){if(typeAllowsObject(root["type"])===false){return`# does not accept an object (type ${stripAnsiAndControl(JSON.stringify(root["type"]))}); structured output is always a JSON object.`}if("const"in root&&!isRecord(root["const"])){return"# does not accept an object (its const is not an object); structured output is always a JSON object."}if(Array.isArray(root["enum"])&&!root["enum"].some(isRecord)){return"# does not accept an object (its enum has no object member); structured output is always a JSON object."}return void 0}__name(rootExcludesObject,"rootExcludesObject");function findContradiction(root){const rootProblem=rootExcludesObject(root);if(rootProblem!==void 0)return rootProblem;let visited=0;const visit=__name((node,pointer,depth)=>{visited+=1;if(depth>MAX_WALK_DEPTH||visited>MAX_WALK_NODES)return void 0;if(COMPOUND_KEYWORDS.some(keyword=>keyword in node))return void 0;const required=node["required"];if(!Array.isArray(required)||required.length===0)return void 0;if(!required.every(key=>typeof key==="string")){return void 0}const properties=isRecord(node["properties"])?node["properties"]:{};const patterns=compilePatterns(node["patternProperties"]);if(patterns===void 0)return void 0;const maxProperties=node["maxProperties"];const distinct=new Set(required);if(typeof maxProperties==="number"&&distinct.size>maxProperties){return`${pointer}/required lists ${distinct.size} distinct properties, but ${pointer}/maxProperties allows at most ${maxProperties}.`}for(let index=0;index<required.length;index++){const key=required[index];const requiredAt=`${pointer}/required/${index}`;const declared=Object.hasOwn(properties,key);const matching=patterns.filter(entry=>entry.regex.test(key));if(declared&&properties[key]===false){return`${requiredAt} requires ${quoteKey(key)}, but ${pointer}/properties/${pointerToken(key)} is false, which forbids it.`}const forbiddingPattern=matching.find(entry=>entry.schema===false);if(forbiddingPattern!==void 0){return`${requiredAt} requires ${quoteKey(key)}, but ${pointer}/patternProperties/${pointerToken(forbiddingPattern.source)} is false, which forbids it.`}if(!declared&&matching.length===0&&node["additionalProperties"]===false){return`${requiredAt} requires ${quoteKey(key)}, but this object forbids it via additionalProperties:false (it is not in properties and matches no patternProperties).`}}for(const key of distinct){if(!Object.hasOwn(properties,key))continue;const child=properties[key];if(!isRecord(child)||!isObjectOnly(child))continue;const problem=visit(child,`${pointer}/properties/${pointerToken(key)}`,depth+1);if(problem!==void 0)return problem}return void 0},"visit");return visit(root,"#",0)}__name(findContradiction,"findContradiction");function compilePatterns(value){if(value===void 0)return[];if(!isRecord(value))return void 0;const entries=[];for(const[source,schema]of Object.entries(value)){try{entries.push({source,regex:new RegExp(source,"u"),schema})}catch{return void 0}}return entries}__name(compilePatterns,"compilePatterns");init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{constants,promises as fs}from"node:fs";import path from"node:path";var debugLogger4=createDebugLogger("WORKFLOW_JOURNAL");var JOURNAL_KEY_VERSION="v2";var DISPATCH_AFFECTING_AGENT_OPTS=["schema","model","effort","isolation","agentType","workingDir","disallowedTools","tools"];function canonicalizeAgentOpts(opts){const projected={};for(const k of DISPATCH_AFFECTING_AGENT_OPTS){const v=opts[k];if(v===void 0||typeof v==="function")continue;projected[k]=v}const sortDeep=__name(val=>{if(typeof val==="function")return void 0;if(Array.isArray(val))return val.map(sortDeep);if(val&&typeof val==="object"){const out={};for(const key of Object.keys(val).sort()){if(key==="__proto__")continue;out[key]=sortDeep(val[key])}return out}return val},"sortDeep");try{return JSON.stringify(sortDeep(projected))}catch{return"{}"}}__name(canonicalizeAgentOpts,"canonicalizeAgentOpts");function deriveAgentKey(prefixHash,prompt,opts){const hash=createHash("sha256");hash.update(prefixHash);hash.update("\0");hash.update(prompt);hash.update("\0");hash.update(canonicalizeAgentOpts(opts));return`${JOURNAL_KEY_VERSION}:${hash.digest("hex")}`}__name(deriveAgentKey,"deriveAgentKey");function deriveArgsSeed(args){const hash=createHash("sha256");let serialized;try{serialized=JSON.stringify(args??null)??"null"}catch{serialized="non-serializable-args"}hash.update(serialized);return`${JOURNAL_KEY_VERSION}:${hash.digest("hex")}`}__name(deriveArgsSeed,"deriveArgsSeed");function buildReplay(entries){let sourceRef;let sourceError;const results=new Map;const started=new Map;const failed=new Set;for(const e of entries){if(e.type==="result"){results.set(e.key,e);failed.delete(e.key)}else if(e.type==="started"){results.delete(e.key);failed.delete(e.key);const list=started.get(e.key);if(list)list.push(e);else started.set(e.key,[e])}else if(e.type==="failed"){results.delete(e.key);failed.add(e.key)}else if(e.type==="source"){try{const ref=readWorkflowSourceRef(e.sourceRef);if(e.version!==1||!ref||sourceRef&&(sourceRef.id!==ref.id||sourceRef.revision!==ref.revision)){throw new Error("Conflicting or unsupported workflow source record.")}sourceRef=ref}catch{sourceError="Workflow journal contains invalid source metadata."}}}return{results,started,failed,...sourceRef?{sourceRef}:{},...sourceError?{sourceError}:{}}}__name(buildReplay,"buildReplay");function describeError(error){return error instanceof Error?error.message:String(error)}__name(describeError,"describeError");var WorkflowJournalWriteError=class extends Error{static{__name(this,"WorkflowJournalWriteError")}__wfRunFailure=true;constructor(cause){super("Could not persist workflow replay invalidation; subsequent agents were not started. Check storage and retry.",{cause});this.name="WorkflowJournalWriteError"}};async function readEntries(journalPath){const contents=await fs.readFile(journalPath,"utf8");const entries=[];for(const line of contents.split("\n")){if(!line.trim())continue;const parsed=parseLineTolerantWithIntegrity(line,journalPath);if(!parsed.complete)throw new Error("Workflow journal contains incomplete records.");for(const entry of parsed.records){if(typeof entry["type"]!=="string"||["started","failed","result"].includes(entry["type"])&&(typeof entry["key"]!=="string"||typeof entry["agentId"]!=="string"||entry["type"]==="result"&&!Object.hasOwn(entry,"result"))||entry["type"]==="launched"&&entry["version"]!==1){throw new Error("Workflow journal contains invalid records.")}entries.push(entry)}}return entries}__name(readEntries,"readEntries");var WorkflowJournal=class{constructor(journalPath,root=path.dirname(path.dirname(journalPath))){this.root=root;this.path=journalPath}static{__name(this,"WorkflowJournal")}pending=Promise.resolve();writeError;path;async hasSymlinkedPath(){if(await isSymlinkedRoot(this.root)||await isSymlinkedRoot(path.dirname(this.path))){return true}return fs.lstat(this.path).then(stat=>stat.isSymbolicLink()).catch(()=>false)}async ensureExists(){try{if(await this.hasSymlinkedPath())return false;await fs.mkdir(path.dirname(this.path),{recursive:true});if(await this.hasSymlinkedPath())return false;const noFollow=process.platform==="win32"?0:constants.O_NOFOLLOW;const file=await fs.open(this.path,constants.O_APPEND|constants.O_CREAT|constants.O_WRONLY|noFollow,384);try{await file.chmod(384)}finally{await file.close()}return true}catch(error){debugLogger4.warn(`WorkflowJournal.ensureExists failed for ${this.path}: ${error}`);return false}}async remove(){await this.drain();try{if(await this.hasSymlinkedPath())return;await fs.rm(this.path,{force:true});await fs.rmdir(path.dirname(this.path)).catch(error=>{const code=error.code;if(code!=="ENOENT"&&code!=="ENOTEMPTY")throw error})}catch(error){debugLogger4.warn(`WorkflowJournal.remove failed for ${this.path}: ${error}`)}}async load(){try{if(await this.hasSymlinkedPath())throw new Error("Workflow journal path is symlinked.");await fs.stat(this.path)}catch(e){if(e.code==="ENOENT"){return{kind:"missing"}}debugLogger4.warn(`WorkflowJournal.load failed for ${this.path}: ${e}`);return{kind:"unreadable",reason:describeError(e)}}try{const entries=await readEntries(this.path);return{kind:"loaded",replay:buildReplay(entries)}}catch(e){debugLogger4.warn(`WorkflowJournal.load failed for ${this.path}: ${e}`);return{kind:"unreadable",reason:describeError(e)}}}async markLaunched(){await this.append({type:"launched",version:1}).catch(error=>debugLogger4.warn(`WorkflowJournal.markLaunched failed for ${this.path}: ${error}`))}retainReplayPrefix(keys){const prefix=new Set(keys);const operation=this.pending.then(async()=>{if(this.writeError)throw this.writeError;let temporaryPath;try{if(await this.hasSymlinkedPath())throw new Error("Workflow journal path is symlinked.");const stat=await fs.stat(this.path);if(process.geteuid&&stat.uid!==process.geteuid()){throw new Error("Workflow journal is owned by another user.")}const entries=await readEntries(this.path);const replay=buildReplay(entries);if(replay.sourceError)throw new Error(replay.sourceError);const retained=entries.filter(entry=>entry.type!=="result"||prefix.has(entry.key));const candidate=`${this.path}.${randomUUID()}.tmp`;const file=await fs.open(candidate,"wx",384);temporaryPath=candidate;try{await file.writeFile(retained.map(entry=>JSON.stringify(entry)+"\n").join(""),"utf8");await file.sync()}finally{await file.close()}if(await this.hasSymlinkedPath())throw new Error("Workflow journal path is symlinked.");await renameWithRetry(temporaryPath,this.path,3,10,fs.rename);temporaryPath=void 0}catch(cause){this.writeError=new WorkflowJournalWriteError(cause);throw this.writeError}finally{if(temporaryPath){await fs.unlink(temporaryPath).catch(error=>debugLogger4.warn(`Workflow journal temporary file cleanup failed: ${error}`))}}});this.pending=operation.catch(()=>void 0);return operation}append(entry){const operation=this.pending.then(()=>{if(this.writeError)throw this.writeError;return writeLine(this.path,entry)});this.pending=operation.catch(()=>void 0);return operation}drain(){return this.pending}};init_esbuild_shims();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.';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- The third failed attempt ends the run \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.";init_esbuild_shims();function abortError(){return new DOMException("Workflow dispatch scheduler aborted.","AbortError")}__name(abortError,"abortError");var WorkflowDispatchScheduler=class{constructor(limit,signal,onStateChange){this.limit=limit;this.signal=signal;if(!Number.isInteger(limit)||limit<1){throw new Error(`Workflow dispatch limit must be a positive integer, got ${String(limit)}.`)}if(onStateChange)this.stateListeners.add(onStateChange);if(signal&&!signal.aborted){signal.addEventListener("abort",()=>this.abortPending(),{once:true})}}static{__name(this,"WorkflowDispatchScheduler")}state="running";inFlight=0;queue=[];gateWaiters=[];stateListeners=new Set;onStateChange(listener){this.stateListeners.add(listener);return()=>{this.stateListeners.delete(listener)}}run(thunk){return new Promise((resolve2,reject)=>{if(this.signal?.aborted){reject(abortError());return}this.queue.push({thunk,resolve:resolve2,reject});this.pump()})}pause(){if(this.state!=="running"||this.signal?.aborted)return false;this.setState("pausing");if(this.inFlight===0)this.setState("paused");return true}resume(){if(this.state!=="paused"||this.signal?.aborted)return false;this.setState("running");while(this.gateWaiters.length>0){this.gateWaiters.shift().resolve()}this.pump();return true}waitUntilRunning(){if(this.signal?.aborted)return Promise.reject(abortError());if(this.state==="running")return Promise.resolve();return new Promise((resolve2,reject)=>{this.gateWaiters.push({resolve:resolve2,reject})})}snapshot(){return{state:this.state,queued:this.queue.length,inFlight:this.inFlight}}pump(){while(this.state==="running"&&this.inFlight<this.limit&&this.queue.length>0){const job=this.queue.shift();if(this.signal?.aborted){job.reject(abortError());continue}this.inFlight++;Promise.resolve().then(job.thunk).then(job.resolve,job.reject).finally(()=>{this.inFlight--;if(this.state==="pausing"&&this.inFlight===0){this.setState("paused")}this.pump()})}}setState(state){if(this.state===state)return;this.state=state;const snapshot=this.snapshot();for(const listener of[...this.stateListeners])listener(snapshot)}abortPending(){const error=abortError();while(this.queue.length>0)this.queue.shift().reject(error);while(this.gateWaiters.length>0){this.gateWaiters.shift().reject(error)}}};var DEFAULT_MAX_AGENTS_PER_RUN=1e3;var MAX_WORKFLOW_AGENTS_ENV="QWEN_CODE_MAX_WORKFLOW_AGENTS";var HARD_MAX_AGENTS_PER_RUN_CEILING=1e4;function resolveMaxAgentsPerRun(env=process.env){const raw=env[MAX_WORKFLOW_AGENTS_ENV];if(raw===void 0||raw.trim()===""){return DEFAULT_MAX_AGENTS_PER_RUN}const parsed=parsePositiveIntegerEnv(raw,0);if(parsed<1){debugLogger.warn(`Invalid ${MAX_WORKFLOW_AGENTS_ENV}=${JSON.stringify(raw)}, using default (${DEFAULT_MAX_AGENTS_PER_RUN})`);return DEFAULT_MAX_AGENTS_PER_RUN}if(parsed>HARD_MAX_AGENTS_PER_RUN_CEILING){debugLogger.warn(`${MAX_WORKFLOW_AGENTS_ENV}=${parsed} exceeds hard ceiling (${HARD_MAX_AGENTS_PER_RUN_CEILING}); clamping.`);return HARD_MAX_AGENTS_PER_RUN_CEILING}return parsed}__name(resolveMaxAgentsPerRun,"resolveMaxAgentsPerRun");var MAX_WORKFLOW_CONCURRENCY_ENV="QWEN_CODE_MAX_WORKFLOW_CONCURRENCY";var HARD_MAX_CONCURRENCY_CEILING=64;function resolveConcurrencyLimit(env=process.env,availableParallelism2=os.availableParallelism){const raw=env[MAX_WORKFLOW_CONCURRENCY_ENV];if(raw!==void 0&&raw.trim()!==""){const parsed=parsePositiveIntegerEnv(raw,0);if(parsed>=1){if(parsed>HARD_MAX_CONCURRENCY_CEILING){debugLogger.warn(`${MAX_WORKFLOW_CONCURRENCY_ENV}=${parsed} exceeds hard ceiling (${HARD_MAX_CONCURRENCY_CEILING}); clamping.`);return HARD_MAX_CONCURRENCY_CEILING}return parsed}debugLogger.warn(`Invalid ${MAX_WORKFLOW_CONCURRENCY_ENV}=${JSON.stringify(raw)}, using cpu-derived default`)}return Math.max(2,Math.min(16,availableParallelism2()-2))}__name(resolveConcurrencyLimit,"resolveConcurrencyLimit");var DEFAULT_WORKFLOW_SUBAGENT_MAX_TURNS=50;var DEFAULT_WORKFLOW_SUBAGENT_MAX_TIME_MINUTES=10;var WORKFLOW_SUBAGENT_MAX_TURNS_ENV="QWEN_CODE_WORKFLOW_AGENT_MAX_TURNS";var WORKFLOW_SUBAGENT_MAX_MINUTES_ENV="QWEN_CODE_WORKFLOW_AGENT_MAX_MINUTES";var HARD_WORKFLOW_SUBAGENT_MAX_TURNS_CEILING=500;var HARD_WORKFLOW_SUBAGENT_MAX_MINUTES_CEILING=100;function resolveSubagentBound(envName,defaultValue,ceiling,env){const raw=env[envName];if(raw===void 0||raw.trim()==="")return defaultValue;const parsed=parsePositiveIntegerEnv(raw,0);if(parsed<1){debugLogger.warn(`Invalid ${envName}=${JSON.stringify(raw)}, using default (${defaultValue})`);return defaultValue}if(parsed>ceiling){debugLogger.warn(`${envName}=${parsed} exceeds hard ceiling (${ceiling}); clamping.`);return ceiling}return parsed}__name(resolveSubagentBound,"resolveSubagentBound");function resolveSubagentMaxTurns(env=process.env,defaultValue=DEFAULT_WORKFLOW_SUBAGENT_MAX_TURNS){return resolveSubagentBound(WORKFLOW_SUBAGENT_MAX_TURNS_ENV,defaultValue,HARD_WORKFLOW_SUBAGENT_MAX_TURNS_CEILING,env)}__name(resolveSubagentMaxTurns,"resolveSubagentMaxTurns");function resolveSubagentMaxTimeMinutes(env=process.env,defaultValue=DEFAULT_WORKFLOW_SUBAGENT_MAX_TIME_MINUTES){return resolveSubagentBound(WORKFLOW_SUBAGENT_MAX_MINUTES_ENV,defaultValue,HARD_WORKFLOW_SUBAGENT_MAX_MINUTES_CEILING,env)}__name(resolveSubagentMaxTimeMinutes,"resolveSubagentMaxTimeMinutes");var WORKFLOW_SUBAGENT_DISALLOWED_TOOLS=[ToolNames.ASK_USER_QUESTION,ToolNames.SEND_MESSAGE,ToolNames.MONITOR,...SUBAGENT_PLAN_LIFECYCLE_TOOLS,ToolNames.AGENT];var WorkflowExecutionError=class extends Error{constructor(message,phases,logs,meta=null){super(message);this.phases=phases;this.logs=logs;this.meta=meta}static{__name(this,"WorkflowExecutionError")}name="WorkflowExecutionError"};function runBudgetFigures(budget){return[budget.runSpent?budget.runSpent():budget.spent(),budget.runCap?budget.runCap():budget.total]}__name(runBudgetFigures,"runBudgetFigures");function generateRunId(){return`wf_${randomBytes(8).toString("hex")}`}__name(generateRunId,"generateRunId");function sanitizeForErrorMessage(value){return stripAnsiAndControl(value)}__name(sanitizeForErrorMessage,"sanitizeForErrorMessage");function createProductionDispatch(config,signal,onTokens,bridgeApprovalEvents,subagentBounds,refuseSubagentTools,parentToolCallId){return async(prompt,opts,dispatchId)=>{if(typeof prompt!=="string"||prompt.length===0){throw new Error("agent() requires a non-empty string prompt.")}if(refuseSubagentTools===true){const hostBound=HOST_BOUND_AGENT_OPTS.filter(key=>opts[key]!==void 0);if(hostBound.length>0){throw new Error(`agent({${hostBound.join(", ")}}): unavailable in this workflow \u2014 its agents carry no tools and use nothing on this host, so only text-only agent() calls (optionally with model, effort or schema) can run.`)}}const stallMs=resolveStallMs(typeof opts.stallMs==="number"?opts.stallMs:void 0);const workflowAgentId=`workflow-agent-${randomBytes(8).toString("hex")}`+(parentToolCallId?`-${parentToolCallId}`:"");const agentIdentity=await resolveWorkflowAgentIdentity(config,opts);if(resolveAgentExecutionBackend(config,agentIdentity.resolvedAgentType)==="container"){throw Object.assign(new Error("Container execution is required; workflow agents are unsupported. Start a regular subagent instead."),{__wfRunFailure:true})}if(agentIdentity.resolvedAgentType?.executor!==void 0){throw new Error("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.")}let attempt=0;let finishTranscript=__name(()=>{},"finishTranscript");let status="failed";try{const result=await runStallResilient(async(attemptSignal,emitter)=>{attempt+=1;const cleanupApprovalBridge=bridgeApprovalEvents?.(emitter,dispatchId);const cleanupTranscript=attachDispatchTranscript(config,workflowAgentId,prompt,agentIdentity.name,emitter,attempt);finishTranscript=cleanupTranscript;try{return await runSingleDispatch(config,prompt,opts,attemptSignal,emitter,workflowAgentId,agentIdentity,onTokens,subagentBounds,refuseSubagentTools)}finally{cleanupTranscript("running");cleanupApprovalBridge?.()}},{stallMs,signal,label:sanitizeForErrorMessage(agentIdentity.name)});status="completed";return result}finally{finishTranscript(status==="failed"&&signal?.aborted?"cancelled":status)}}}__name(createProductionDispatch,"createProductionDispatch");var HOST_BOUND_AGENT_OPTS=["agentType","isolation","workingDir"];async function resolveWorkflowAgentIdentity(config,opts){if(opts.agentType){const resolved=await config.getSubagentManager().findSubagentByName(opts.agentType);if(resolved){return{name:resolved.name,resolvedAgentType:resolved}}}if(typeof opts.label==="string"&&opts.label){return{name:opts.label}}return{name:opts.agentType||"workflow-agent"}}__name(resolveWorkflowAgentIdentity,"resolveWorkflowAgentIdentity");function attachDispatchTranscript(config,agentId,prompt,agentName,emitter,attempt){const append=attempt>1;try{const{jsonlPath,options}=buildAgentTranscriptAttach(config,agentId,{agentName,initialUserPrompt:append?void 0:prompt,appendToExisting:append,retryAttempt:append?attempt:void 0});const writer=attachJsonlTranscriptWriter(emitter,jsonlPath,options);const metaPath=getAgentMetaPath(config.storage.getProjectDir(),options.sessionId,agentId);const now=new Date().toISOString();const meta={agentId,agentType:stripAnsiAndControl(agentName).slice(0,200)||"workflow-agent",description:stripAnsiAndControl(prompt).slice(0,4096),parentSessionId:options.sessionId,parentAgentId:getCurrentAgentId()??null,createdAt:(append?readAgentMeta(metaPath)?.createdAt:void 0)??now,lastUpdatedAt:now,status:"running",isBackgrounded:false,workflowOwner:{pid:process.pid,hostname:os.hostname()}};writeAgentMeta(metaPath,meta);return status=>{writer.cleanup();writeAgentMeta(metaPath,{...meta,status,lastUpdatedAt:new Date().toISOString()})}}catch(error){debugLogger.warn(`[Workflow] failed to attach transcript for ${agentId}: ${error}`);return()=>{}}}__name(attachDispatchTranscript,"attachDispatchTranscript");function terminalDispatchError(workflowAgentId,mode){const message=`Workflow subagent ${workflowAgentId} did not complete (terminate mode: ${mode}).`;switch(mode){case"MAX_TURNS":return new WorkflowAgentFailedError(message,"max_turns",mode);case"TIMEOUT":return new WorkflowAgentFailedError(message,"timeout",mode);case"ERROR":return new WorkflowAgentFailedError(message,"error",mode);default:return new Error(message)}}__name(terminalDispatchError,"terminalDispatchError");async function runSingleDispatch(config,prompt,opts,attemptSignal,emitter,workflowAgentId,agentIdentity,onTokens,subagentBounds,refuseSubagentTools){const{AgentHeadless,ContextState}=await import("./agent-headless-GLP5GUEX.js");const ctx=new ContextState;ctx.set("task_prompt",prompt);debugLogger.debug(`[workflow] Dispatch ${workflowAgentId}`);const ownDir=config.getTargetDir?.();if(opts.workingDir===void 0&&ownDir){await settleBackgroundFix({within:ownDir})}if(opts.workingDir===void 0&&ownDir&&backgroundFixHolding(ownDir,getCurrentAgentId())){throw new Error(`agent(): a background fix agent of /autofix-pr is working in ${ownDir}; its round goes on when it ends.`)}if(DISPATCH_AFFECTING_AGENT_OPTS.every(key=>opts[key]===void 0)){const subagent=await AgentHeadless.create(agentIdentity.name,config,{systemPrompt:WORKFLOW_SUBAGENT_SYSTEM_PROMPT},{},subagentBounds??{max_turns:resolveSubagentMaxTurns(),max_time_minutes:resolveSubagentMaxTimeMinutes()},refuseSubagentTools===true?{tools:[],disallowedTools:[]}:{tools:["*"],disallowedTools:WORKFLOW_SUBAGENT_DISALLOWED_TOOLS},emitter,void 0,void 0,prompt,workflowAgentId);try{await runWithAgentContext(workflowAgentId,()=>subagent.execute(ctx,attemptSignal,{enforceTimeLimitDuringRetryWait:true}))}finally{reportTokens(subagent,opts,onTokens)}const mode=subagent.getTerminateMode();if(mode!=="GOAL"){throw terminalDispatchError(workflowAgentId,mode)}return toModelVisibleSubagentResult(subagent.getFinalText(),mode)}return runOverridePath(config,ctx,opts,attemptSignal,workflowAgentId,agentIdentity,onTokens,emitter,subagentBounds,refuseSubagentTools)}__name(runSingleDispatch,"runSingleDispatch");function reportTokens(subagent,opts,onTokens){if(!onTokens)return;try{const summary=subagent.getExecutionSummary();onTokens(summary.outputTokens,opts)}catch(e){debugLogger.warn("onTokens callback threw:",e)}}__name(reportTokens,"reportTokens");function resolveDispatchEffort(raw){if(raw===void 0)return void 0;const tier=typeof raw==="string"?normalizeReasoningEffort(raw):void 0;if(tier===void 0){throw new Error(`agent({effort}): unknown effort tier ${sanitizeForErrorMessage(JSON.stringify(raw)??String(raw))}. Known tiers are: ${REASONING_EFFORT_TIERS.join(", ")}.`)}return tier}__name(resolveDispatchEffort,"resolveDispatchEffort");function resolveDispatchDenies(raw){if(raw===void 0)return[];if(!Array.isArray(raw)||raw.some(name=>typeof name!=="string"||name.length===0||name!==name.trim())){throw new Error("agent({disallowedTools}): must be an array of non-empty tool-name strings without surrounding whitespace, e.g. ['run_shell_command', 'write_file'].")}return raw.map(name=>resolveBuiltinToolName(name)??name)}__name(resolveDispatchDenies,"resolveDispatchDenies");function resolveDispatchAllows(raw){if(raw===void 0)return void 0;if(!Array.isArray(raw)||raw.length===0||raw.some(name=>typeof name!=="string"||name.length===0||name!==name.trim())){throw new Error("agent({tools}): must be a non-empty array of tool-name strings without surrounding whitespace, e.g. ['run_shell_command', 'read_file']. Omit tools to keep every tool.")}for(const name of raw){const problem=describeAgentToolAllowEntryProblem(name);if(problem!==null){throw new Error(`agent({tools}): ${sanitizeForErrorMessage(problem)}`)}}return[...new Set(raw.map(canonicalAgentToolName))]}__name(resolveDispatchAllows,"resolveDispatchAllows");async function runOverridePath(config,ctx,opts,signal,workflowAgentId,agentIdentity,onTokens,emitter,subagentBounds,refuseSubagentTools){if(opts.isolation==="remote"){throw new Error("agent({isolation:'remote'}) is not available in this build.")}let schemaValidate;if(opts.schema!==void 0){const prepared=prepareWorkflowSchema(opts.schema);if(!prepared.ok){throw new Error(prepared.error)}schemaValidate=prepared.validate}const effort=resolveDispatchEffort(opts.effort);const requestedDenies=resolveDispatchDenies(opts.disallowedTools);const requestedAllows=resolveDispatchAllows(opts.tools);const subagentMgr=config.getSubagentManager();let baseConfig;if(opts.agentType!==void 0){const resolved=agentIdentity.resolvedAgentType;if(!resolved){const safeAgentType=sanitizeForErrorMessage(opts.agentType);throw new Error(`agent({agentType}): agent type '${safeAgentType}' not found.`)}baseConfig=resolved}else{baseConfig={name:agentIdentity.name,description:"Default workflow subagent (per-call overrides).",systemPrompt:WORKFLOW_SUBAGENT_SYSTEM_PROMPT,level:"session",isBuiltin:false}}let schemaSystemPrompt;if(opts.schema!==void 0){schemaSystemPrompt=opts.agentType!==void 0&&baseConfig.systemPrompt?`${baseConfig.systemPrompt}
4
4
 
5
5
  ${WORKFLOW_SUBAGENT_SYSTEM_PROMPT_WITH_SCHEMA}`:WORKFLOW_SUBAGENT_SYSTEM_PROMPT_WITH_SCHEMA}let schemaTools;if(opts.schema!==void 0&&baseConfig.tools&&baseConfig.tools.length>0&&!baseConfig.tools.includes("*")&&!baseConfig.tools.includes(ToolNames.STRUCTURED_OUTPUT)){schemaTools=[...baseConfig.tools,ToolNames.STRUCTURED_OUTPUT]}const augmented={...baseConfig,...opts.model!==void 0?{model:opts.model}:{},...schemaSystemPrompt!==void 0?{systemPrompt:schemaSystemPrompt}:{},...schemaTools!==void 0?{tools:schemaTools}:{},disallowedTools:Array.from(new Set([...baseConfig.disallowedTools??[],...WORKFLOW_SUBAGENT_DISALLOWED_TOOLS,...requestedDenies,...refuseSubagentTools===true?requestedAllows??[]:[]]))};if(requestedDenies.length>0){const unmatched=await subagentMgr.findUnmatchedToolNames(requestedDenies);if(unmatched.length>0){throw new Error(`agent({disallowedTools}): ${sanitizeForErrorMessage(unmatched.map(name=>JSON.stringify(name)).join(", "))} ${unmatched.length===1?"matches":"match"} no tool. Use a tool name (run_shell_command, write_file, edit), a display name (Shell, WriteFile, Edit), or an MCP pattern (mcp__<server>, mcp__<server>__*, mcp__<server>__<tool>).`)}}if(opts.schema!==void 0&&[...baseConfig.disallowedTools??[],...requestedDenies].some(name=>(resolveBuiltinToolName(name)??name)===ToolNames.STRUCTURED_OUTPUT)){throw new Error("agent({schema, disallowedTools}): schema mode needs the structured_output tool, but disallowedTools deny it (from this call or from the agent type).")}if(requestedAllows!==void 0){const agentHasOwnMcpServers=baseConfig.mcpServers!==void 0&&Object.keys(baseConfig.mcpServers).length>0;const checkMcpNames=!agentHasOwnMcpServers;if(requestedAllows.some(name=>resolveBuiltinToolName(name)===void 0&&(checkMcpNames||!name.startsWith("mcp__")))){await config.waitForMcpReady()}const unmatchedAllows=await subagentMgr.findUnmatchedToolNames(requestedAllows,{checkMcpNames});if(unmatchedAllows.length>0){throw new Error(`agent({tools}): ${sanitizeForErrorMessage(listAgentToolNames(unmatchedAllows))} ${unmatchedAllows.length===1?"names":"name"} no tool. Use a tool name (run_shell_command, read_file), a display name (Shell, ReadFile), or an MCP tool's exact name as the model sees it (mcp__<server>__<tool>).`)}const agentTypeTools=baseConfig.tools!==void 0&&baseConfig.tools.length>0&&!baseConfig.tools.includes("*")?baseConfig.tools:void 0;try{augmented.tools=narrowAgentTools({requested:requestedAllows,requestedNames:await subagentMgr.resolveToolNames(requestedAllows),...agentTypeTools!==void 0?{agentTypeTools,agentTypeToolNames:await subagentMgr.resolveToolNames(agentTypeTools)}:{},denies:await subagentMgr.resolveToolNames(augmented.disallowedTools??[]),getMcpIdentity:__name(name=>config.getToolRegistry().getMcpToolIdentity?.(name),"getMcpIdentity"),schema:opts.schema!==void 0})}catch(error){throw new Error(sanitizeForErrorMessage(error instanceof Error?error.message:String(error)))}}const refusedToolConfig=refuseSubagentTools===true?{tools:opts.schema!==void 0?[ToolNames.STRUCTURED_OUTPUT]:[],disallowedTools:[]}:void 0;let worktreeIsolation=null;let effectiveContext=config;let approvalCleanup;if(opts.isolation!==void 0&&opts.workingDir!==void 0){throw new Error("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.")}if(opts.isolation==="worktree"){worktreeIsolation=await provisionWorkflowWorktree(config);effectiveContext=deriveWorktreeConfig(config,worktreeIsolation.path,{customIgnoreFiles:config.getFileFilteringOptions().customIgnoreFiles});installSessionWorkflowRevisionWriteThrough(effectiveContext,config)}else if(opts.workingDir!==void 0){if(typeof opts.workingDir!=="string"||opts.workingDir.trim().length===0){throw new Error("agent({workingDir}): must be a non-empty string naming an existing git worktree of this repository.")}const resolved=await resolveExternalWorktreeDir(config,opts.workingDir,"workingDir");if("error"in resolved){throw new Error(`agent({workingDir: ${sanitizeForErrorMessage(JSON.stringify(opts.workingDir))}}): ${sanitizeForErrorMessage(resolved.error)}`)}await settleBackgroundFix({worktree:resolved.path});if(backgroundFixAt(resolved.path)){throw new Error(`agent({workingDir}): a background fix agent of /autofix-pr is working in ${resolved.path}; its round goes on when it ends.`)}effectiveContext=deriveWorktreeConfig(config,resolved.path,{customIgnoreFiles:config.getFileFilteringOptions().customIgnoreFiles});installSessionWorkflowRevisionWriteThrough(effectiveContext,config)}if(effectiveContext!==config){const approvalHandle=deriveApprovalModeConfig(effectiveContext,config.getApprovalMode());approvalCleanup=approvalHandle.cleanup;effectiveContext=approvalHandle.config}let onParentAbort;try{let schemaState=null;if(schemaValidate!==void 0){effectiveContext=await createSchemaConfigOverride(effectiveContext,opts.schema,schemaValidate);schemaState=createSchemaModeState(schemaValidate)}let dispatchSignal=signal;if(schemaState){const child=new AbortController;if(signal){if(signal.aborted){child.abort(signal.reason)}else{onParentAbort=__name(()=>child.abort(signal.reason),"onParentAbort");signal.addEventListener("abort",onParentAbort)}}schemaState.abortController=child;dispatchSignal=child.signal}const eventEmitter=emitter??(schemaState?new AgentEventEmitter:void 0);if(schemaState&&eventEmitter){attachSchemaListeners(eventEmitter,schemaState)}const{subagent,dispose}=await subagentMgr.createAgentHeadless(augmented,effectiveContext,{runConfigOverrides:subagentBounds??{max_turns:resolveSubagentMaxTurns(),max_time_minutes:resolveSubagentMaxTimeMinutes()},...effort!==void 0?{modelConfigOverrides:{reasoningEffort:effort}}:{},...refusedToolConfig!==void 0?{toolConfigOverride:refusedToolConfig}:{},eventEmitter,taskName:String(ctx.get("task_prompt")),subagentId:workflowAgentId});try{try{await runWithAgentContext(workflowAgentId,()=>subagent.execute(ctx,dispatchSignal,{enforceTimeLimitDuringRetryWait:true}))}finally{reportTokens(subagent,opts,onTokens)}if(schemaState){if(schemaState.result!==null){if(worktreeIsolation){const isolation=worktreeIsolation;worktreeIsolation=null;const preserved=await cleanupWorkflowWorktree(isolation);if(preserved){debugLogger.info(`[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.`)}}return schemaState.result}if(signal?.aborted){throw new DOMException("Workflow aborted.","AbortError")}const mode2=subagent.getTerminateMode();if(mode2!=="GOAL"&&mode2!=="CANCELLED"){throw terminalDispatchError(workflowAgentId,mode2)}throw new WorkflowAgentFailedError(describeMissingStructuredOutput(schemaState),"no_structured_output")}const mode=subagent.getTerminateMode();if(mode!=="GOAL"){throw terminalDispatchError(workflowAgentId,mode)}let finalText=toModelVisibleSubagentResult(subagent.getFinalText(),mode);if(worktreeIsolation){const isolation=worktreeIsolation;worktreeIsolation=null;const preserved=await cleanupWorkflowWorktree(isolation);if(preserved&&typeof finalText==="string"){finalText=appendWorktreePreservedSuffix(finalText,preserved)}}return finalText}finally{await dispose()}}finally{if(onParentAbort&&signal){signal.removeEventListener("abort",onParentAbort)}approvalCleanup?.();if(worktreeIsolation){try{await cleanupWorkflowWorktree(worktreeIsolation)}catch(error){debugLogger.warn(`Workflow worktree cleanup in fallback finally failed for ${worktreeIsolation.path}: ${error instanceof Error?error.message:String(error)}`)}}}}__name(runOverridePath,"runOverridePath");async function provisionWorkflowWorktree(config){const cwd=config.getTargetDir();if(/\.qwen[\\/]worktrees[\\/]/.test(cwd)){throw new Error(`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.`)}const probe=new GitWorktreeService(cwd);const gitCheck=await probe.checkGitAvailable();if(!gitCheck.available){throw new Error(`agent({isolation:'worktree'}): ${gitCheck.error??"git is not available"}.`)}if(!await probe.isGitRepository()){throw new Error(`agent({isolation:'worktree'}): ${cwd} is not a git repository.`)}const projectRoot=await probe.getRepoTopLevel()??cwd;const wtService=projectRoot===cwd?probe:new GitWorktreeService(projectRoot);let parentDirty=false;try{parentDirty=await wtService.hasWorktreeChanges(projectRoot)}catch(error){debugLogger.warn(`[Workflow] hasWorktreeChanges failed at ${projectRoot}: ${error}`);parentDirty=true}if(parentDirty){throw new Error(`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.`)}const slug=generateAgentWorktreeSlug();let parentBranch;try{parentBranch=await wtService.getCurrentBranch()}catch(error){debugLogger.warn(`[Workflow] getCurrentBranch failed at ${projectRoot}: ${error}`)}const created=await wtService.createUserWorktree(slug,parentBranch,{symlinkDirectories:config.getWorktreeSymlinkDirectories()});if(!created.success||!created.worktree){throw new Error(`agent({isolation:'worktree'}): failed to create worktree: ${created.error??"unknown error"}.`)}try{await writeWorktreeSessionMarker(created.worktree.path,config.getSessionId())}catch(error){debugLogger.warn(`[Workflow] failed to write session marker at ${created.worktree.path}: ${error}`)}return{slug,path:created.worktree.path,branch:created.worktree.branch,repoRoot:projectRoot}}__name(provisionWorkflowWorktree,"provisionWorkflowWorktree");async function cleanupWorkflowWorktree(isolation){const wtService=new GitWorktreeService(isolation.repoRoot);const[hasChanges,hasUnmerged]=await Promise.all([wtService.hasWorktreeChanges(isolation.path).catch(error=>{debugLogger.warn(`[Workflow] hasWorktreeChanges failed for ${isolation.path}: ${error}`);return true}),wtService.hasUnmergedWorktreeCommits(isolation.slug).catch(error=>{debugLogger.warn(`[Workflow] hasUnmergedWorktreeCommits failed for ${isolation.slug}: ${error}`);return true})]);if(hasChanges||hasUnmerged){debugLogger.info(`[Workflow] Preserving isolation worktree ${isolation.path} (branch ${isolation.branch}, hasChanges=${hasChanges}, hasUnmerged=${hasUnmerged})`);return{path:isolation.path,branch:isolation.branch}}try{const result=await wtService.removeUserWorktree(isolation.slug,{deleteBranch:true});if(!result.success){debugLogger.warn(`[Workflow] Failed to remove ephemeral worktree ${isolation.path}: ${result.error}`);return{path:isolation.path,branch:isolation.branch}}if(result.branchPreserved){debugLogger.warn(`[Workflow] Removed worktree directory ${isolation.path} but kept branch ${isolation.branch} (unmerged commits at delete time)`);return{branch:isolation.branch}}}catch(error){debugLogger.warn(`[Workflow] Failed to remove ephemeral worktree ${isolation.path}: ${error}`);return{path:isolation.path,branch:isolation.branch}}return null}__name(cleanupWorkflowWorktree,"cleanupWorkflowWorktree");function appendWorktreePreservedSuffix(finalText,preserved){const sep=finalText.endsWith("\n")?"\n":"\n\n";if(preserved.path){return`${finalText}${sep}[worktree preserved: ${preserved.path} (branch ${preserved.branch})]`}return`${finalText}${sep}[worktree directory removed; branch ${preserved.branch} preserved \u2014 recover with \`git worktree add <path> ${preserved.branch}\`]`}__name(appendWorktreePreservedSuffix,"appendWorktreePreservedSuffix");var MAX_FAILED_STRUCTURED_OUTPUT_SUBMISSIONS=3;var MAX_STRUCTURED_OUTPUT_ERROR_LENGTH=500;function createSchemaModeState(validate){return{result:null,attempts:0,lastError:void 0,lastErrorAttempt:0,pendingArgs:new Map,abortController:new AbortController,validate}}__name(createSchemaModeState,"createSchemaModeState");function recordFailedSubmission(state,error){state.attempts+=1;if(typeof error==="string"&&error.trim().length>0){const clean=sanitizeForErrorMessage(error).trim();state.lastError=clean.length>MAX_STRUCTURED_OUTPUT_ERROR_LENGTH?`${clean.slice(0,MAX_STRUCTURED_OUTPUT_ERROR_LENGTH)}\u2026`:clean;state.lastErrorAttempt=state.attempts}if(state.attempts>=MAX_FAILED_STRUCTURED_OUTPUT_SUBMISSIONS&&state.result===null){state.abortController.abort()}}__name(recordFailedSubmission,"recordFailedSubmission");function describeMissingStructuredOutput(state){const attempts=state.attempts;if(attempts===0){return"subagent completed without calling structured_output (no validation attempt \u2014 model produced plain-text content)."}const submissions=`${attempts} failed structured_output submission${attempts===1?"":"s"}`;const head=attempts>=MAX_FAILED_STRUCTURED_OUTPUT_SUBMISSIONS?`subagent stopped after ${submissions} without a valid result.`:`subagent completed after ${submissions} without a valid result.`;if(state.lastError===void 0){return`${head} The failed submissions reported no error detail.`}if(state.lastErrorAttempt===attempts){return`${head} Last error: ${state.lastError}`}return`${head} Submission ${attempts} reported no error detail; the last error (submission ${state.lastErrorAttempt}): ${state.lastError}`}__name(describeMissingStructuredOutput,"describeMissingStructuredOutput");function attachSchemaListeners(emitter,state){const targetTool=ToolNames.STRUCTURED_OUTPUT;emitter.on("tool_call",evt=>{if(evt.name!==targetTool)return;state.pendingArgs.set(evt.callId,evt.args)});emitter.on("tool_result",evt=>{if(evt.name!==targetTool)return;const args=state.pendingArgs.get(evt.callId);state.pendingArgs.delete(evt.callId);if(state.result!==null)return;if(!evt.success){recordFailedSubmission(state,evt.error);return}if(args===void 0){recordFailedSubmission(state,"structured_output reported success for a call whose arguments were not observed.");return}const checked=validateStructuredResult(args,state.validate);if("error"in checked){recordFailedSubmission(state,`structured_output arguments did not pass validation: ${checked.error}`);return}state.result=checked.value;state.abortController.abort()})}__name(attachSchemaListeners,"attachSchemaListeners");async function createSchemaConfigOverride(base,schema,validate){const override=deriveConfig(base);installSessionWorkflowRevisionWriteThrough(override,base);await rebuildToolRegistryOnOverride(override,base);const registry=override.getToolRegistry();registry.registerTool(new SyntheticOutputTool(schema,validate));return override}__name(createSchemaConfigOverride,"createSchemaConfigOverride");var WorkflowOrchestrator=class{constructor(dispatch){this.dispatch=dispatch}static{__name(this,"WorkflowOrchestrator")}async run(req){const runId=req.runId??generateRunId();const maxAgents=resolveMaxAgentsPerRun();const signal=req.abortOnTimeout?.signal;const scheduler=req.scheduler??new WorkflowDispatchScheduler(resolveConcurrencyLimit(),signal);const rejectThroughPauseGate=__name(error=>scheduler.waitUntilRunning().then(()=>{throw error},()=>{throw error}),"rejectThroughPauseGate");let agentCount=0;let dispatchTraceCount=0;const emitter=req.emitter;const budget=req.budget;const dependencyContext=new AsyncLocalStorage;const issueDispatchTrace=__name((prompt,opts,cached=false,workflowCallId)=>{const id=`dispatch-${dispatchTraceCount+=1}`;const store=dependencyContext.getStore();const dependsOn=Array.from(new Set(store?.tails??[]));if(store)store.tails=[id];try{emitter?.dispatchQueued?.({id,...opts.stepId!==void 0?{stepId:opts.stepId}:{},...workflowCallId?{workflowCallId}:{},...typeof opts.label==="string"?{label:opts.label}:{},prompt,dependsOn,queuedAt:Date.now(),...cached?{cached:true}:{}})}catch(e){debugLogger.warn("emitter.dispatchQueued threw:",e)}return id},"issueDispatchTrace");const journal=req.journal;const replay=req.resumeReplay;let prefixHash=deriveArgsSeed(req.args);let hadMiss=false;const replayPrefix=new Set;let replayBarrier;let executionClosed=false;const assertExecutionOpen=__name(()=>{if(executionClosed||signal?.aborted){throw new DOMException("Workflow run has ended.","AbortError")}},"assertExecutionOpen");let journalAgentId=0;const parentSandboxRef={current:void 0};const countedDispatch=__name(async(prompt,opts,workflowCallId)=>{assertExecutionOpen();const stepId=readWorkflowStepId(opts.stepId);if(stepId!==void 0)opts={...opts,stepId};if(typeof prompt!=="string"||prompt.length===0){return rejectThroughPauseGate(new Error("agent() requires a non-empty string prompt."))}const schemaPreparation=opts.schema===void 0?void 0:prepareWorkflowSchema(opts.schema);const schemaError=schemaPreparation!==void 0&&!schemaPreparation.ok?schemaPreparation.error:void 0;let journalKey;let journalEntryId;let respawnLine;if(journal){journalKey=deriveAgentKey(prefixHash,prompt,opts);prefixHash=journalKey;if(!hadMiss&&replay&&schemaError===void 0){const cached=replay.results.get(journalKey);let cachedResult=cached?.result;let cacheUsable=cached!==void 0;if(cached!==void 0&&schemaPreparation?.ok){const checked=validateStructuredResult(cached.result,schemaPreparation.validate);if("error"in checked){debugLogger.info(`[Workflow] resume cache entry no longer satisfies its schema for runId=${runId}; re-running live: `+sanitizeForErrorMessage(checked.error));cacheUsable=false}else{cachedResult=checked.value}}if(cacheUsable){const replayed=cachedResult;replayPrefix.add(journalKey);const respawns=replay.started.get(journalKey);if(respawns&&respawns.length>0){debugLogger.info(`[Workflow] resume cache hit after ${respawns.length} prior respawn(s) for runId=${runId}.`)}const label2=typeof opts.label==="string"?opts.label:void 0;const dispatchId2=issueDispatchTrace(prompt,opts,true,workflowCallId);try{emitter?.agentDispatched?.(label2)}catch(e){debugLogger.warn("emitter.agentDispatched threw:",e)}try{emitter?.agentCompleted?.(label2)}catch(e){debugLogger.warn("emitter.agentCompleted threw:",e)}try{emitter?.dispatchSettled?.(dispatchId2,void 0,Date.now())}catch(e){debugLogger.warn("emitter.dispatchSettled threw:",e)}return scheduler.waitUntilRunning().then(()=>replayed,()=>replayed)}}const priorStarts=replay?.started.get(journalKey);if(priorStarts&&priorStarts.length>0&&!replay?.results.has(journalKey)){const name=typeof opts.label==="string"?`"${stripAnsiAndControl(opts.label)}"`:"an agent";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"})`}if(!hadMiss&&replay){replayBarrier=journal.retainReplayPrefix(new Set(replayPrefix));void replayBarrier.catch(()=>void 0)}hadMiss=true}if(replayBarrier)await replayBarrier;assertExecutionOpen();if(budget&&budget.total!==null&&budget.remaining()<=0){debugLogger.warn(`[Workflow] budget gate refused dispatch at entry: runId=${runId} spent=${budget.spent()} total=${budget.total}`);return rejectThroughPauseGate(new WorkflowBudgetExceededError(runId,budget.total,budget.spent()))}if(agentCount>=maxAgents){return rejectThroughPauseGate(new WorkflowAgentCapExceededError(maxAgents))}agentCount+=1;if(journal&&journalKey!==void 0){journalEntryId=String(journalAgentId+=1)}const label=typeof opts.label==="string"?opts.label:void 0;const dispatchId=issueDispatchTrace(prompt,opts,false,workflowCallId);try{emitter?.agentDispatched?.(label)}catch(e){debugLogger.warn("emitter.agentDispatched threw:",e)}let completionEmitted=false;const emitCompletion=__name(error=>{if(completionEmitted)return;completionEmitted=true;const message=error===void 0?void 0:error instanceof Error?error.message:String(error);try{emitter?.agentCompleted?.(label,message)}catch(e){debugLogger.warn("emitter.agentCompleted threw:",e)}try{emitter?.dispatchSettled?.(dispatchId,message,Date.now())}catch(e){debugLogger.warn("emitter.dispatchSettled threw:",e)}},"emitCompletion");return scheduler.run(async()=>{try{assertExecutionOpen();try{emitter?.dispatchStarted?.(dispatchId,Date.now())}catch(e){debugLogger.warn("emitter.dispatchStarted threw:",e)}if(budget&&budget.total!==null&&budget.remaining()<=0){debugLogger.warn(`[Workflow] budget gate refused dispatch at slot-acquire: runId=${runId} spent=${budget.spent()} total=${budget.total}`);throw new WorkflowBudgetExceededError(runId,budget.total,budget.spent())}if(journal&&journalKey!==void 0&&journalEntryId!==void 0){journal.append({type:"started",key:journalKey,agentId:journalEntryId}).catch(e=>debugLogger.warn(`journal started-append failed: ${e}`))}if(respawnLine){parentSandboxRef.current?.appendLog(respawnLine);try{emitter?.resumeRespawn?.(respawnLine)}catch(e){debugLogger.warn("emitter.resumeRespawn threw:",e)}}if(schemaError!==void 0){throw new Error(schemaError)}const result=await this.dispatch(prompt,opts,dispatchId);emitCompletion();if(!executionClosed&&journal&&journalKey!==void 0){journal.append({type:"result",key:journalKey,agentId:journalEntryId??"",result}).catch(e=>debugLogger.warn(`journal result-append failed: ${e}`))}if(budget){try{emitter?.budgetUpdated?.(...runBudgetFigures(budget))}catch(e){debugLogger.warn("emitter.budgetUpdated threw:",e)}}return result}catch(err){emitCompletion(err);if(budget){try{emitter?.budgetUpdated?.(...runBudgetFigures(budget))}catch(e){debugLogger.warn("emitter.budgetUpdated threw:",e)}}if(journal&&journalKey!==void 0&&!executionClosed&&!signal?.aborted&&!isWorkflowRunLevelError(err)){journal.append({type:"failed",key:journalKey,agentId:journalEntryId??""}).catch(e=>debugLogger.warn(`journal failed-append failed: ${e}`))}if(executionClosed||signal?.aborted||isWorkflowRunLevelError(err)){throw err}if(isWorkflowAgentFailedError(err)){debugLogger.warn(`[Workflow] agent settled to null (${err.kind}): ${err.message}`)}else{debugLogger.warn(`[Workflow] agent settled to null: ${extractErrorMessage(err)}`)}return null}}).then(result=>scheduler.waitUntilRunning().then(()=>result,()=>result),error=>{emitCompletion(error);return scheduler.waitUntilRunning().then(()=>{throw error},()=>{throw error})})},"countedDispatch");const parallelImpl=makeParallelImpl(signal,dependencyContext);const pipelineImpl=makePipelineImpl(signal,dependencyContext);let workflowCallCount=0;const recordCall=__name(call=>{try{emitter?.workflowCallUpdated?.({...call})}catch(error){debugLogger.warn("emitter.workflowCallUpdated threw:",error)}},"recordCall");const resolveSavedWorkflow=req.resolveSavedWorkflow;const workflowImpl=resolveSavedWorkflow?async(nameOrRef,nestedArgs,stepId)=>{const call={id:`workflow-call-${++workflowCallCount}`,...stepId!==void 0?{stepId:readWorkflowStepId(stepId)}:{},...typeof nameOrRef==="string"?{workflowName:nameOrRef}:{},status:"running",startedAt:Date.now()};const recorded=workflowCallCount<=MAX_WORKFLOW_CALL_TRACES;if(recorded)recordCall(call);else if(workflowCallCount===MAX_WORKFLOW_CALL_TRACES+1){try{emitter?.workflowCallsTruncated?.()}catch(error){debugLogger.warn("emitter.workflowCallsTruncated threw:",error)}}let nestedSandbox;try{const resolved=await resolveSavedWorkflow(nameOrRef);if(resolved.name)call.workflowName=resolved.name;nestedSandbox=createWorkflowSandbox({args:nestedArgs,runId,dispatch:__name((prompt,opts)=>countedDispatch(prompt,opts,call.id),"dispatch"),parallel:parallelImpl,pipeline:pipelineImpl,abortOnTimeout:req.abortOnTimeout,emitter,budget,scheduler});const result=await nestedSandbox.run(resolved.script);call.status=signal?.aborted?"cancelled":"completed";return result}catch(error){call.status=signal?.aborted?"cancelled":"failed";try{const message=typeof error==="string"?error:error&&typeof error==="object"?Object.getOwnPropertyDescriptor(error,"message")?.value:void 0;if(typeof message==="string")call.error=message}catch{}throw error}finally{call.endedAt=Date.now();if(recorded)recordCall(call);for(const line of nestedSandbox?.getLogs()??[]){parentSandboxRef.current?.appendLog(line)}}}:void 0;const sandbox=createWorkflowSandbox({args:req.args,maxWallClockMs:req.maxWallClockMs,runId,dispatch:countedDispatch,parallel:parallelImpl,pipeline:pipelineImpl,workflow:workflowImpl,abortOnTimeout:req.abortOnTimeout,emitter,budget,scheduler});parentSandboxRef.current=sandbox;try{let result;try{result=await dependencyContext.run({tails:[]},()=>sandbox.run(req.script))}finally{executionClosed=true;await replayBarrier}return{runId,result,phases:sandbox.getPhases(),logs:sandbox.getLogs(),meta:sandbox.getMeta()}}catch(err){throw new WorkflowExecutionError(extractErrorMessage(err),sandbox.getPhases(),sandbox.getLogs(),sandbox.getMeta())}}};async function settleToNullArray(thunks,signal){const settled=await Promise.allSettled(thunks.map(t=>Promise.resolve().then(t)));if(signal?.aborted)throw new DOMException("Workflow run aborted.","AbortError");const visitedReasons=new WeakSet;const findRunFailureReason=__name(reason=>{if(reason===null||typeof reason!=="object")return void 0;if(visitedReasons.has(reason))return void 0;visitedReasons.add(reason);try{if(reason.__wfRunFailure===true){return reason}const errors=reason?.errors;if(!Array.isArray(errors))return void 0;for(const error of errors){const runFailure=findRunFailureReason(error);if(runFailure!==void 0)return runFailure}}catch{return void 0}return void 0},"findRunFailureReason");for(const result of settled){if(result.status!=="rejected")continue;const runFailure=findRunFailureReason(result.reason);if(runFailure!==void 0)throw runFailure}return settled.map((r,i)=>{if(r.status==="fulfilled")return r.value;const reason=r.reason;debugLogger.warn(`Workflow thunk at index ${i} rejected: ${String(reason?.message??r.reason)}`);return null})}__name(settleToNullArray,"settleToNullArray");function makeParallelImpl(signal,dependencyContext){return thunks=>{if(!Array.isArray(thunks)){return Promise.reject(new Error("parallel() expects an array of thunks (functions returning promises)."))}let batch;try{batch=snapshotBatch("parallel() thunks",thunks)}catch(error){return Promise.reject(error)}for(let i=0;i<batch.length;i++){if(typeof batch[i]!=="function"){return Promise.reject(new Error("parallel() expects an array of functions, not values \u2014 wrap each call: parallel([() => agent(...), () => agent(...)])."))}}const parent=dependencyContext.getStore();const inheritedTails=parent?.tails??[];const branches=batch.map(thunk=>{const store={tails:[...inheritedTails]};return{store,thunk:__name(()=>dependencyContext.run(store,thunk),"thunk")}});return settleToNullArray(branches.map(({thunk})=>thunk),signal).then(result=>{if(parent&&branches.length>0){parent.tails=mergeFanoutTails(parent.tails,inheritedTails,branches.flatMap(({store})=>store.tails))}return result})}}__name(makeParallelImpl,"makeParallelImpl");function makePipelineImpl(signal,dependencyContext){return(items,...stages)=>{if(!Array.isArray(items)){return Promise.reject(new Error("pipeline() expects an array of items as its first argument."))}let batch;try{batch=snapshotBatch("pipeline() items",items);snapshotBatch("pipeline() stages",stages)}catch(error){return Promise.reject(error)}for(const s of stages){if(typeof s!=="function"){return Promise.reject(new Error("pipeline() stages must be functions: pipeline(items, item => ..., result => ...)."))}}const parent=dependencyContext.getStore();const inheritedTails=parent?.tails??[];const branches=batch.map((item,idx)=>{const store={tails:[...inheritedTails]};return{store,thunk:__name(()=>dependencyContext.run(store,()=>runPipelineChain(item,idx,stages)),"thunk")}});return settleToNullArray(branches.map(({thunk})=>thunk),signal).then(result=>{if(parent&&branches.length>0){parent.tails=mergeFanoutTails(parent.tails,inheritedTails,branches.flatMap(({store})=>store.tails))}return result})}}__name(makePipelineImpl,"makePipelineImpl");function snapshotBatch(list,input){let length;try{length=input.length}catch{length=void 0}if(typeof length!=="number"||!Number.isSafeInteger(length)||length<0){throw new Error(`${list} must be an array with a readable length.`)}if(length>WORKFLOW_BATCH_LIMIT){throw new Error(describeOversizedBatch(list,length))}const batch=new Array(length);for(let i=0;i<length;i++){if(i in input)batch[i]=input[i]}return batch}__name(snapshotBatch,"snapshotBatch");function mergeFanoutTails(currentParentTails,inheritedTails,branchTails){const inherited=new Set(inheritedTails);const newBranchTails=branchTails.filter(tail=>!inherited.has(tail));const merged=newBranchTails.length>0?[...newBranchTails,...currentParentTails.filter(tail=>!inherited.has(tail))]:currentParentTails;return Array.from(new Set(merged))}__name(mergeFanoutTails,"mergeFanoutTails");async function runPipelineChain(item,idx,stages){let prev=item;for(const stage of stages){if(prev===null)break;prev=await stage(prev,item,idx)}return prev}__name(runPipelineChain,"runPipelineChain");function extractErrorMessage(err){if(err&&typeof err==="object"&&"message"in err){const m=err.message;if(typeof m==="string")return m;return String(m)}return String(err)}__name(extractErrorMessage,"extractErrorMessage");init_esbuild_shims();import{promises as fs2}from"node:fs";import path2 from"node:path";init_esbuild_shims();var MAX_WORKFLOW_RESULT_PREVIEW_CHARS=25e3;var MAX_RAW_PREVIEW_CHARS=MAX_WORKFLOW_RESULT_PREVIEW_CHARS*4;function buildWorkflowResultPreview(result){const raw=result===""?'""':stringifyWorkflowResult(result,true);const cut=truncateWorkflowText(raw,MAX_RAW_PREVIEW_CHARS);const text=sanitizeWorkflowText(cut);let reportedFailures;try{reportedFailures=reportedFailureLines(result)}catch{reportedFailures=[]}const bounded=truncateWorkflowText(text,MAX_WORKFLOW_RESULT_PREVIEW_CHARS);return{text:bounded,truncated:cut!==raw||bounded!==text,reportedFailures}}__name(buildWorkflowResultPreview,"buildWorkflowResultPreview");function isWorkflowResultPreview(value){if(typeof value!=="object"||value===null||Array.isArray(value)){return false}const{text,truncated,reportedFailures}=value;return typeof text==="string"&&text.length<=MAX_WORKFLOW_RESULT_PREVIEW_CHARS&&typeof truncated==="boolean"&&Array.isArray(reportedFailures)&&reportedFailures.length<=REPORTED_FAILURE_KEYS.length&&reportedFailures.every(line=>typeof line==="string"&&line.length<=MAX_FAILURE_LINE_CHARS)}__name(isWorkflowResultPreview,"isWorkflowResultPreview");var debugLogger5=createDebugLogger("WORKFLOW_SNAPSHOT");var MAX_RETAINED_SNAPSHOTS=30;var SNAPSHOT_TEMP_FILE=/^wf_[0-9a-f]+\.json\.[0-9a-f]+\.tmp$/;var SNAPSHOT_TEMP_GRACE_MS=60*60*1e3;var MAX_SNAPSHOT_ARGS_CHARS=256*1024;function toSnapshot(task){if(!isTerminalWorkflowStatus(task.status)){throw new Error(`Cannot snapshot active workflow ${task.runId}.`)}return{runId:task.runId,...task.sourceRef?{sourceRef:{...task.sourceRef}}:{},...task.workflowCalls?{workflowCalls:task.workflowCalls.map(call=>({...call}))}:{},...task.workflowCallsTruncated?{workflowCallsTruncated:true}:{},...task.toolUseId?{toolUseId:task.toolUseId}:{},...task.parentSessionId?{parentSessionId:task.parentSessionId}:{},description:task.description,...task.workflowName?{workflowName:task.workflowName}:{},sourceRunId:task.sourceRunId,startMode:task.startMode,...snapshotArgs(task.args),meta:task.meta,status:task.status,script:task.script??"",scriptPath:task.scriptPath,phases:[...task.phases],phaseVisits:task.phaseVisits.map(visit=>({...visit})),dispatches:task.dispatches.map(dispatch=>({...dispatch,dependsOn:[...dispatch.dependsOn]})),agentsDispatched:task.agentsDispatched,agentsCompleted:task.agentsCompleted,agentsRespawned:task.agentsRespawned??0,...task.sizeWarning?{sizeWarning:{...task.sizeWarning}}:{},tokensSpent:task.tokensSpent,tokenBudgetTotal:task.tokenBudgetTotal,perPhaseTokens:Array.from(task.perPhaseTokens.entries()),recentLogs:[...task.recentLogs],events:task.events.map(event=>({...event})),startTime:task.startTime,endTime:task.endTime,result:safeResult(task.result),...task.status==="completed"?{resultPreview:buildWorkflowResultPreview(task.result)}:{},error:task.error}}__name(toSnapshot,"toSnapshot");function snapshotArgs(args){if(args===void 0)return{argsRecorded:true};let json;try{json=JSON.stringify(args)}catch{return{argsOmitted:true}}if(json===void 0||json.length>MAX_SNAPSHOT_ARGS_CHARS){return{argsOmitted:true}}return{args:JSON.parse(json),argsRecorded:true}}__name(snapshotArgs,"snapshotArgs");function snapshotArgsUnavailable(snapshot){if(snapshot.argsOmitted)return"omitted";if(snapshot.argsRecorded!==true&&snapshot.args===void 0){return"unrecorded"}return void 0}__name(snapshotArgsUnavailable,"snapshotArgsUnavailable");function safeResult(result){if(result===void 0)return void 0;try{JSON.stringify(result);return result}catch{return`(non-JSON-serializable ${typeof result})`}}__name(safeResult,"safeResult");async function writeWorkflowSnapshot(config,task){const storage=config.storage;if(!storage)return false;try{const snapshot=toSnapshot(task);return await persistWorkflowSnapshot(config,snapshot)}catch(e){debugLogger5.warn(`writeWorkflowSnapshot failed for ${task.runId}: ${e}`);return false}}__name(writeWorkflowSnapshot,"writeWorkflowSnapshot");async function persistWorkflowSnapshot(config,snapshot){const storage=config.storage;if(!storage)return false;try{const dir=storage.getWorkflowRunsDir();await fs2.mkdir(dir,{recursive:true});await atomicWriteFile(storage.getWorkflowRunSnapshotPath(snapshot.runId),JSON.stringify(snapshot,null,2),{encoding:"utf8",mode:384,forceMode:true,noFollow:true});await pruneSnapshots(config,dir);return true}catch(e){debugLogger5.warn(`persistWorkflowSnapshot failed for ${snapshot.runId}: ${e}`);return false}}__name(persistWorkflowSnapshot,"persistWorkflowSnapshot");async function readWorkflowSnapshot(config,runId){const storage=config.storage;if(!storage)return void 0;try{const file=storage.getWorkflowRunSnapshotPath(runId);if((await fs2.lstat(file)).isSymbolicLink())return void 0;const parsed=JSON.parse(await fs2.readFile(file,"utf8"));return isWorkflowSnapshot(parsed)&&parsed.runId===runId?parsed:void 0}catch{return void 0}}__name(readWorkflowSnapshot,"readWorkflowSnapshot");async function listWorkflowSnapshots(config){const storage=config.storage;if(!storage)return[];const dir=storage.getWorkflowRunsDir();let files;try{files=(await fs2.readdir(dir)).filter(f=>f.endsWith(".json"))}catch{return[]}const snapshots=[];for(const file of files){try{const raw=await fs2.readFile(`${dir}/${file}`,"utf8");const parsed=JSON.parse(raw);if(!isWorkflowSnapshot(parsed)){debugLogger5.warn(`skipping invalid workflow snapshot ${file}`);continue}snapshots.push(parsed)}catch(e){debugLogger5.warn(`skipping unparseable snapshot ${file}: ${e}`)}}snapshots.sort((a,b)=>(b.startTime??0)-(a.startTime??0));return snapshots}__name(listWorkflowSnapshots,"listWorkflowSnapshots");async function deleteWorkflowSnapshot(config,runId){const storage=config.storage;if(!storage||!/^wf_[0-9a-f]+$/.test(runId))return false;try{await fs2.rm(path2.dirname(storage.getWorkflowRunJournalPath(runId)),{recursive:true,force:true})}catch(error){debugLogger5.warn(`delete workflow journal failed for ${runId}: ${error}`);return false}if(!await deleteInlineWorkflowScript(config,runId))return false;try{await fs2.unlink(storage.getWorkflowRunSnapshotPath(runId))}catch(error){if(error.code!=="ENOENT"){debugLogger5.warn(`deleteWorkflowSnapshot failed for ${runId}: ${error}`);return false}}return true}__name(deleteWorkflowSnapshot,"deleteWorkflowSnapshot");function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord2,"isRecord");function isFiniteNumber(value){return typeof value==="number"&&Number.isFinite(value)}__name(isFiniteNumber,"isFiniteNumber");function isOptionalString(value){return value===void 0||typeof value==="string"}__name(isOptionalString,"isOptionalString");function isStringArray(value){return Array.isArray(value)&&value.every(item=>typeof item==="string")}__name(isStringArray,"isStringArray");function isWorkflowMeta(value){if(value===null)return true;if(!isRecord2(value))return false;if(typeof value["name"]!=="string"||typeof value["description"]!=="string"||!isOptionalString(value["whenToUse"])){return false}const phases=value["phases"];return phases===void 0||Array.isArray(phases)&&phases.every(phase=>isRecord2(phase)&&typeof phase["title"]==="string"&&isOptionalString(phase["detail"])&&isOptionalString(phase["model"]))}__name(isWorkflowMeta,"isWorkflowMeta");function isWorkflowPhaseVisit(value){return isRecord2(value)&&typeof value["id"]==="string"&&isFiniteNumber(value["index"])&&typeof value["title"]==="string"&&isFiniteNumber(value["startedAt"])&&(value["endedAt"]===void 0||isFiniteNumber(value["endedAt"]))}__name(isWorkflowPhaseVisit,"isWorkflowPhaseVisit");function isWorkflowDispatch(value){if(!isRecord2(value))return false;const status=value["status"];return typeof value["id"]==="string"&&(value["phaseVisitId"]===null||typeof value["phaseVisitId"]==="string")&&typeof value["label"]==="string"&&typeof value["prompt"]==="string"&&isOptionalString(value["subagentId"])&&isOptionalString(value["stepId"])&&isOptionalString(value["workflowCallId"])&&(status==="queued"||status==="running"||status==="completed"||status==="failed"||status==="cancelled"||status==="cached")&&isStringArray(value["dependsOn"])&&isFiniteNumber(value["queuedAt"])&&(value["startedAt"]===void 0||isFiniteNumber(value["startedAt"]))&&(value["endedAt"]===void 0||isFiniteNumber(value["endedAt"]))&&isOptionalString(value["error"])}__name(isWorkflowDispatch,"isWorkflowDispatch");function hasOnlyKeys(value,keys){const allowed=new Set(keys);return Object.keys(value).every(key=>allowed.has(key))}__name(hasOnlyKeys,"hasOnlyKeys");function isWorkflowEvent(value){if(!isRecord2(value)||typeof value["id"]!=="string"||!isFiniteNumber(value["at"])||typeof value["type"]!=="string"){return false}const base=["id","type","at"];switch(value["type"]){case"phase-started":return hasOnlyKeys(value,[...base,"phaseVisitId","title"])&&typeof value["phaseVisitId"]==="string"&&typeof value["title"]==="string";case"phase-completed":return hasOnlyKeys(value,[...base,"phaseVisitId"])&&typeof value["phaseVisitId"]==="string";case"dispatch-queued":case"dispatch-started":case"dispatch-completed":case"dispatch-cancelled":case"dispatch-cached":return hasOnlyKeys(value,[...base,"dispatchId"])&&typeof value["dispatchId"]==="string";case"dispatch-failed":return hasOnlyKeys(value,[...base,"dispatchId","error"])&&typeof value["dispatchId"]==="string"&&typeof value["error"]==="string";case"log":return hasOnlyKeys(value,[...base,"message"])&&typeof value["message"]==="string";case"approval-requested":case"approval-settled":return hasOnlyKeys(value,[...base,"name","dispatchId"])&&typeof value["name"]==="string"&&isOptionalString(value["dispatchId"]);case"workflow-completed":case"workflow-cancelled":return hasOnlyKeys(value,base);case"workflow-failed":return hasOnlyKeys(value,[...base,"error"])&&typeof value["error"]==="string";default:return false}}__name(isWorkflowEvent,"isWorkflowEvent");function isWorkflowCall(value){if(!isRecord2(value))return false;const status=value["status"];return typeof value["id"]==="string"&&isOptionalString(value["stepId"])&&isOptionalString(value["workflowName"])&&(status==="running"||status==="completed"||status==="failed"||status==="cancelled")&&isFiniteNumber(value["startedAt"])&&(value["endedAt"]===void 0||isFiniteNumber(value["endedAt"]))&&isOptionalString(value["error"])}__name(isWorkflowCall,"isWorkflowCall");function isWorkflowSnapshot(value){if(!isRecord2(value))return false;const status=value["status"];const workflowCalls=value["workflowCalls"];const phaseVisits=value["phaseVisits"];const dispatches=value["dispatches"];const events=value["events"];const perPhaseTokens=value["perPhaseTokens"];return(value["sourceRef"]===void 0||isWorkflowSourceRef(value["sourceRef"]))&&(workflowCalls===void 0||Array.isArray(workflowCalls)&&workflowCalls.length<=MAX_WORKFLOW_CALL_TRACES&&workflowCalls.every(isWorkflowCall))&&(value["workflowCallsTruncated"]===void 0||typeof value["workflowCallsTruncated"]==="boolean")&&typeof value["runId"]==="string"&&value["runId"].length>0&&isOptionalString(value["toolUseId"])&&isOptionalString(value["parentSessionId"])&&isOptionalString(value["description"])&&isOptionalString(value["workflowName"])&&isOptionalString(value["sourceRunId"])&&(value["startMode"]===void 0||value["startMode"]==="retry"||value["startMode"]==="rerun")&&(value["argsOmitted"]===void 0||value["argsOmitted"]===true)&&(value["argsRecorded"]===void 0||value["argsRecorded"]===true)&&isWorkflowMeta(value["meta"])&&(status==="completed"||status==="failed"||status==="cancelled")&&typeof value["script"]==="string"&&isOptionalString(value["scriptPath"])&&isStringArray(value["phases"])&&(phaseVisits===void 0||Array.isArray(phaseVisits)&&phaseVisits.every(isWorkflowPhaseVisit))&&(dispatches===void 0||Array.isArray(dispatches)&&dispatches.every(isWorkflowDispatch))&&(events===void 0||Array.isArray(events)&&events.every(isWorkflowEvent))&&isFiniteNumber(value["agentsDispatched"])&&isFiniteNumber(value["agentsCompleted"])&&(value["agentsRespawned"]===void 0||isFiniteNumber(value["agentsRespawned"]))&&(value["sizeWarning"]===void 0||isWorkflowSizeWarning(value["sizeWarning"]))&&isFiniteNumber(value["tokensSpent"])&&(value["tokenBudgetTotal"]===null||isFiniteNumber(value["tokenBudgetTotal"]))&&Array.isArray(perPhaseTokens)&&perPhaseTokens.every(entry=>Array.isArray(entry)&&entry.length===2&&(entry[0]===null||typeof entry[0]==="string")&&isFiniteNumber(entry[1]))&&isStringArray(value["recentLogs"])&&isFiniteNumber(value["startTime"])&&(value["endTime"]===void 0||isFiniteNumber(value["endTime"]))&&(value["resultPreview"]===void 0||isWorkflowResultPreview(value["resultPreview"]))&&isOptionalString(value["error"])}__name(isWorkflowSnapshot,"isWorkflowSnapshot");async function sweepSnapshotTempFiles(dir,entries){const cutoff=Date.now()-SNAPSHOT_TEMP_GRACE_MS;await Promise.all(entries.filter(entry=>SNAPSHOT_TEMP_FILE.test(entry)).map(async entry=>{try{if((await fs2.stat(`${dir}/${entry}`)).mtimeMs>=cutoff)return;await fs2.unlink(`${dir}/${entry}`)}catch(e){debugLogger5.warn(`snapshot temp sweep failed for ${entry}: ${e}`)}}))}__name(sweepSnapshotTempFiles,"sweepSnapshotTempFiles");async function pruneSnapshots(config,dir){let entries;try{entries=await fs2.readdir(dir)}catch{return}await sweepSnapshotTempFiles(dir,entries);const candidates=entries.filter(f=>f.endsWith(".json"));if(candidates.length<=MAX_RETAINED_SNAPSHOTS)return;const settled=await Promise.all(candidates.map(async f=>{try{const parsed=JSON.parse(await fs2.readFile(`${dir}/${f}`,"utf8"));return isWorkflowSnapshot(parsed)?f:void 0}catch(e){debugLogger5.warn(`prune skipped unreadable snapshot ${f}: ${e}`);return void 0}}));const files=settled.filter(f=>f!==void 0);if(files.length<=MAX_RETAINED_SNAPSHOTS)return;const stats=await Promise.all(files.map(async f=>{try{const s=await fs2.stat(`${dir}/${f}`);return{f,mtime:s.mtimeMs}}catch{return{f,mtime:0}}}));stats.sort((a,b)=>a.mtime-b.mtime);const toPrune=stats.slice(0,stats.length-MAX_RETAINED_SNAPSHOTS);const registry=config.getWorkflowRunRegistry?.();const protectedRunIds=new Set([...(registry?.list()??[]).filter(entry=>isActiveWorkflowStatus(entry.status)).map(entry=>entry.runId),...registry?.listStartingRunIds()??[]]);await Promise.all(toPrune.map(s=>{const runId=s.f.replace(/\.json$/,"");const isRunDir=/^wf_[0-9a-f]+$/.test(runId);const deleteArtifacts=isRunDir&&!protectedRunIds.has(runId)&&!isWorkflowRunPersistenceActive(config,runId);return Promise.all([fs2.unlink(`${dir}/${s.f}`).catch(e=>debugLogger5.warn(`prune unlink failed for ${s.f}: ${e}`)),...deleteArtifacts?[fs2.rm(path2.dirname(config.storage.getWorkflowRunJournalPath(runId)),{recursive:true,force:true}).catch(e=>debugLogger5.warn(`prune journal dir failed for ${runId}: ${e}`)),deleteInlineWorkflowScript(config,runId)]:[]])}))}__name(pruneSnapshots,"pruneSnapshots");init_esbuild_shims();import{promises as fs3}from"node:fs";import os2 from"node:os";import path3 from"node:path";var debugLogger6=createDebugLogger("WORKFLOW_CHECKPOINT");var CHECKPOINT_FILE="checkpoint.json";var INTERRUPTED_WORKFLOW_ERROR="interrupted: the process running this workflow exited before it finished";function checkpointFromTask(task,context){return{v:1,runId:task.runId,sessionId:context.sessionId,pid:process.pid,hostname:os2.hostname(),startTime:task.startTime,script:task.script??"",...task.scriptPath?{scriptPath:task.scriptPath}:{},meta:context.meta,description:context.meta?.name??task.description??task.runId,...task.workflowName?{workflowName:task.workflowName}:{},...task.resumeName?{resumeName:task.resumeName}:{},...task.sourceRef?{sourceRef:{...task.sourceRef}}:{},...task.toolUseId?{toolUseId:task.toolUseId}:{},...task.sourceRunId?{sourceRunId:task.sourceRunId}:{},...task.startMode?{startMode:task.startMode}:{},tokenBudgetTotal:task.tokenBudgetTotal??null,...snapshotArgs(task.args)}}__name(checkpointFromTask,"checkpointFromTask");function checkpointPath(config,runId){const storage=config.storage;if(!storage||!isWorkflowRunId(runId))return void 0;return path3.join(path3.dirname(storage.getWorkflowRunJournalPath(runId)),CHECKPOINT_FILE)}__name(checkpointPath,"checkpointPath");async function isRunDirSymlinked(config,file){return await isSymlinkedRoot(config.storage.getWorkflowRunsDir())||await isSymlinkedRoot(path3.dirname(file))}__name(isRunDirSymlinked,"isRunDirSymlinked");async function writeWorkflowCheckpoint(config,checkpoint){const file=checkpointPath(config,checkpoint.runId);if(!file)return"unavailable";try{if(await isRunDirSymlinked(config,file))return"unavailable";await atomicWriteFile(file,JSON.stringify(checkpoint),{encoding:"utf8",mode:384,forceMode:true,noFollow:true});return"written"}catch(error){debugLogger6.warn(`writeWorkflowCheckpoint failed for ${checkpoint.runId}: ${error}`);return"failed"}}__name(writeWorkflowCheckpoint,"writeWorkflowCheckpoint");async function removeWorkflowCheckpoint(config,runId){const file=checkpointPath(config,runId);if(!file)return;try{if(await isRunDirSymlinked(config,file))return;await fs3.rm(file,{force:true})}catch(error){debugLogger6.warn(`removeWorkflowCheckpoint failed for ${runId}: ${error}`)}}__name(removeWorkflowCheckpoint,"removeWorkflowCheckpoint");async function readWorkflowCheckpoint(config,runId){const file=checkpointPath(config,runId);if(!file)return void 0;try{if(await isRunDirSymlinked(config,file))return void 0;if((await fs3.lstat(file)).isSymbolicLink())return void 0;const parsed=JSON.parse(await fs3.readFile(file,"utf8"));return isWorkflowCheckpoint(parsed)&&parsed.runId===runId?parsed:void 0}catch{return void 0}}__name(readWorkflowCheckpoint,"readWorkflowCheckpoint");function isRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord3,"isRecord");function isOptionalString2(value){return value===void 0||typeof value==="string"}__name(isOptionalString2,"isOptionalString");function isWorkflowCheckpoint(value){if(!isRecord3(value))return false;const startMode=value["startMode"];const budget=value["tokenBudgetTotal"];return value["v"]===1&&typeof value["runId"]==="string"&&typeof value["sessionId"]==="string"&&Number.isSafeInteger(value["pid"])&&typeof value["hostname"]==="string"&&typeof value["startTime"]==="number"&&Number.isFinite(value["startTime"])&&typeof value["script"]==="string"&&isOptionalString2(value["scriptPath"])&&isWorkflowMeta(value["meta"])&&typeof value["description"]==="string"&&isOptionalString2(value["workflowName"])&&isOptionalString2(value["resumeName"])&&(value["sourceRef"]===void 0||isWorkflowSourceRef(value["sourceRef"]))&&isOptionalString2(value["toolUseId"])&&isOptionalString2(value["sourceRunId"])&&(startMode===void 0||startMode==="retry"||startMode==="rerun")&&(budget===null||typeof budget==="number"&&Number.isFinite(budget))&&(value["argsOmitted"]===void 0||value["argsOmitted"]===true)&&(value["argsRecorded"]===void 0||value["argsRecorded"]===true)}__name(isWorkflowCheckpoint,"isWorkflowCheckpoint");function isProcessRunning(pid){if(!Number.isSafeInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}__name(isProcessRunning,"isProcessRunning");function writerHasExited(checkpoint,isRunning){if(checkpoint.hostname!==os2.hostname())return false;return checkpoint.pid===process.pid||!isRunning(checkpoint.pid)}__name(writerHasExited,"writerHasExited");async function lastWriteTime(file){try{return(await fs3.stat(file)).mtimeMs}catch{return void 0}}__name(lastWriteTime,"lastWriteTime");async function claimOne(config,seen){const{runId}=seen;const checkpoint=await readWorkflowCheckpoint(config,runId);if(!checkpoint||checkpoint.pid!==seen.pid||checkpoint.startTime!==seen.startTime){return void 0}const existing=await readWorkflowSnapshot(config,runId);if(existing&&existing.startTime>=checkpoint.startTime){await removeWorkflowCheckpoint(config,runId);return void 0}const storage=config.storage;const journalPath=storage.getWorkflowRunJournalPath(runId);const loaded=await new WorkflowJournal(journalPath,storage.getWorkflowRunsDir()).load();const replay=loaded.kind==="loaded"?loaded.replay:void 0;const endTime=Math.max(checkpoint.startTime,await lastWriteTime(journalPath)??checkpoint.startTime);const snapshot={runId,...checkpoint.sessionId?{parentSessionId:checkpoint.sessionId}:{},...checkpoint.sourceRef?{sourceRef:checkpoint.sourceRef}:{},...checkpoint.toolUseId?{toolUseId:checkpoint.toolUseId}:{},description:checkpoint.description,...checkpoint.workflowName?{workflowName:checkpoint.workflowName}:{},...checkpoint.sourceRunId?{sourceRunId:checkpoint.sourceRunId}:{},...checkpoint.startMode?{startMode:checkpoint.startMode}:{},...checkpoint.argsOmitted?{argsOmitted:true}:{...checkpoint.args!==void 0?{args:checkpoint.args}:{},argsRecorded:true},meta:checkpoint.meta,status:"failed",script:checkpoint.script,...checkpoint.scriptPath?{scriptPath:checkpoint.scriptPath}:{},phases:[],agentsDispatched:replay?.started.size??0,agentsCompleted:replay?.results.size??0,tokensSpent:0,tokenBudgetTotal:checkpoint.tokenBudgetTotal,perPhaseTokens:[],recentLogs:[],startTime:checkpoint.startTime,endTime,error:INTERRUPTED_WORKFLOW_ERROR};if(!await persistWorkflowSnapshot(config,snapshot))return void 0;await removeWorkflowCheckpoint(config,runId);return{snapshot,...checkpoint.resumeName?{resumeName:checkpoint.resumeName}:{},hasJournal:loaded.kind==="loaded"}}__name(claimOne,"claimOne");async function claimInterruptedWorkflowRuns(config,options={}){const storage=config.storage;if(!storage)return[];const isRunning=options.isProcessRunning??isProcessRunning;const runsDir=storage.getWorkflowRunsDir();let names;try{if(await isSymlinkedRoot(runsDir))return[];names=(await fs3.readdir(runsDir,{withFileTypes:true})).filter(entry=>entry.isDirectory()&&isWorkflowRunId(entry.name)).map(entry=>entry.name)}catch{return[]}const claimed=[];for(const runId of names){const run=await claimIfInterrupted(config,runId,isRunning);if(run)claimed.push(run)}claimed.sort((a,b)=>b.snapshot.startTime-a.snapshot.startTime);return claimed}__name(claimInterruptedWorkflowRuns,"claimInterruptedWorkflowRuns");async function claimInterruptedWorkflowRun(config,runId,options={}){return claimIfInterrupted(config,runId,options.isProcessRunning??isProcessRunning)}__name(claimInterruptedWorkflowRun,"claimInterruptedWorkflowRun");async function claimIfInterrupted(config,runId,isRunning){const seen=await readWorkflowCheckpoint(config,runId);if(!seen||!writerHasExited(seen,isRunning))return void 0;if(isWorkflowRunPersistenceActive(config,runId))return void 0;try{const attempt=await tryWithWorkflowTaskMutation(getWorkflowTaskMutationKey(config,runId),()=>claimOne(config,seen));return attempt.acquired?attempt.value:void 0}catch(error){debugLogger6.warn(`claiming interrupted run ${runId} failed: ${error}`);return void 0}}__name(claimIfInterrupted,"claimIfInterrupted");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import{promises as fs5}from"node:fs";import*as path5 from"node:path";init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{promises as fs4}from"node:fs";import path4 from"node:path";var debugLogger7=createDebugLogger("REVIEW_WORKFLOW");function resolveReviewWorkflowConcurrency(env=process.env){const configured=parsePositiveIntegerEnv(env[MAX_WORKFLOW_CONCURRENCY_ENV],0)||parsePositiveIntegerEnv(env["QWEN_CODE_MAX_TOOL_CONCURRENCY"],10);return resolveConcurrencyLimit({[MAX_WORKFLOW_CONCURRENCY_ENV]:String(configured)})}__name(resolveReviewWorkflowConcurrency,"resolveReviewWorkflowConcurrency");async function resolveReviewWorkflowLimits(scriptPath,generatedDir,scriptContent,env=process.env,nowMs=Date.now()){let canonicalScript;try{if((await fs4.lstat(generatedDir)).isSymbolicLink())return void 0;const generatedRoot=await fs4.realpath(generatedDir);canonicalScript=await fs4.realpath(scriptPath);if(!canonicalScript.startsWith(path4.join(generatedRoot,"review")+path4.sep)){return void 0}}catch(error){if(error.code!=="ENOENT"){debugLogger7.warn("Cannot classify review workflow; using generic limits:",error)}return void 0}const digest=/^qwen-review-[a-f0-9]{10}-([a-f0-9]{64})\.js$/.exec(path4.basename(canonicalScript))?.[1];if(!digest||createHash2("sha256").update(scriptContent).digest("hex")!==digest){return void 0}const seconds=Number(env["QWEN_CODE_MAX_WORKFLOW_SECONDS"]);let maxWallClockMs=(Number.isFinite(seconds)&&seconds>0?seconds:6*60*60)*1e3;const deadline=Number(env["QWEN_REVIEW_DEADLINE_EPOCH"]);if(Number.isFinite(deadline)&&deadline>0){const rawFloor=env["QWEN_REVIEW_DEADLINE_COMPOSE_FLOOR_SECONDS"];const floor=Number(rawFloor);const floorSeconds=rawFloor?.trim()&&Number.isFinite(floor)&&floor>=0?floor:1200;const remainingMs=deadline*1e3-nowMs-floorSeconds*1e3;if(remainingMs<=0){throw new Error("Review workflow was not launched: the review deadline has reached the compose reserve floor. Recover completed findings and compose now.")}maxWallClockMs=Math.min(maxWallClockMs,remainingMs)}return{subagent:{max_turns:resolveSubagentMaxTurns(env,500),max_time_minutes:resolveSubagentMaxTimeMinutes(env,100)},concurrency:resolveReviewWorkflowConcurrency(env),maxWallClockMs}}__name(resolveReviewWorkflowLimits,"resolveReviewWorkflowLimits");async function resolveResumeName(config,workflowName,scriptPath){if(!workflowName||!scriptPath)return void 0;const canonical=__name(file=>fs5.realpath(file).catch(()=>path5.resolve(file)),"canonical");try{const resolved=await resolveSavedWorkflowScript(workflowName,config);const[byName,ran]=await Promise.all([canonical(resolved.scriptPath),canonical(scriptPath)]);return byName===ran?workflowName:void 0}catch{return void 0}}__name(resolveResumeName,"resolveResumeName");var WorkflowRunHandle=class{constructor(runId,budget,registry,controller,scheduler,start,locations={}){this.runId=runId;this.budget=budget;this.registry=registry;this.controller=controller;this.scheduler=scheduler;this.scriptPath=locations.scriptPath;this.journalPath=locations.journalPath;this.sourceRef=locations.sourceRef;this.completion=Promise.resolve().then(start)}static{__name(this,"WorkflowRunHandle")}completion;scriptPath;journalPath;sourceRef;abort(){this.controller.abort()}pause(){return this.scheduler.pause()}resume(){return this.scheduler.resume()}};var WORKFLOW_SCRIPT_SYNTAX_HINT="Workflow scripts must be plain JavaScript \u2014 the usual causes are TypeScript syntax (type annotations, interfaces, generics) and broken string quoting or escaping. Metadata must be the first non-comment statement and use literal values.";var WorkflowScriptNotLaunchedError=class extends Error{constructor(detail,hint=WORKFLOW_SCRIPT_SYNTAX_HINT){super(`Workflow script is invalid and was not launched:
6
6
  ${detail}`+(hint?`
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{appEvents}from"./chunk-VRKYBH5G.js";import{assembleMcpServers,getPendingGatedMcpServers,getPromptableMcpServers}from"./chunk-P62S5JGM.js";import{getMCPServerStatus}from"./chunk-ZWPSBU7K.js";import{require_fast_deep_equal}from"./chunk-3KUHQGOS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var debugLogger=createDebugLogger("MCP_HOT_RELOAD");var modelProvidersDebugLogger=createDebugLogger("MODEL_PROVIDERS_HOT_RELOAD");function mcpServersEqual(a,b){return(0,import_fast_deep_equal.default)(a??{},b??{})}__name(mcpServersEqual,"mcpServersEqual");function mcpGatingEqual(a,b){const norm=__name(xs=>[...xs??[]].sort(),"norm");const allowedEqual=a.allowed===void 0===(b.allowed===void 0)&&(0,import_fast_deep_equal.default)(norm(a.allowed),norm(b.allowed));return(0,import_fast_deep_equal.default)(norm(a.excluded),norm(b.excluded))&&allowedEqual&&(0,import_fast_deep_equal.default)(norm(a.pending),norm(b.pending))}__name(mcpGatingEqual,"mcpGatingEqual");function recomputeMcpGating(settings,assembled,cwd,bootAllowed,isYolo){const settingsAllowed=settings.merged.mcp?.allowed?.filter(Boolean);const excluded=settings.merged.mcp?.excluded?.filter(Boolean);let allowed=settingsAllowed;if(bootAllowed){allowed=settingsAllowed?settingsAllowed.filter(n=>bootAllowed.includes(n)):[...bootAllowed]}return{allowed,excluded:excluded&&excluded.length>0?excluded:void 0,pending:isYolo?void 0:getPendingGatedMcpServers(assembled,cwd)}}__name(recomputeMcpGating,"recomputeMcpGating");function registerMcpHotReload(watcher,settings,config,topTierMcpServers){debugLogger.debug("registered MCP hot-reload listener on SettingsWatcher");return watcher.addChangeListener(async events=>{debugLogger.debug(`settings change fired (${events.length} event(s)): ${events.map(e=>`${e.scope}:${e.changeType}`).join(", ")}`);const cwd=config.getTargetDir();const next=config.getBareMode()||config.isSafeMode()?{...topTierMcpServers}:assembleMcpServers(settings.merged.mcpServers,cwd,topTierMcpServers);const isYolo=config.getApprovalMode()==="yolo";const bootAllowed=config.getCliAllowedMcpServerNames();const nextGating=config.getBareMode()||config.isSafeMode()?{allowed:bootAllowed?[...bootAllowed]:void 0}:recomputeMcpGating(settings,next,cwd,bootAllowed,isYolo);const prevServers=config.getSettingsMcpServers();const prevGating=config.getMcpGating();debugLogger.debug(`assembled servers: prev=[${Object.keys(prevServers??{}).join(", ")}] next=[${Object.keys(next).join(", ")}]`);debugLogger.debug(`gating next: excluded=[${(nextGating.excluded??[]).join(", ")}] allowed=[${(nextGating.allowed??[]).join(", ")}] pending=[${(nextGating.pending??[]).join(", ")}]`);const serversChanged=!mcpServersEqual(prevServers,next);const gatingChanged=!mcpGatingEqual(prevGating,nextGating);if(!serversChanged&&!gatingChanged){debugLogger.debug("no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile");return}debugLogger.debug(`MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`);const promptable=getPromptableMcpServers(next,cwd);config.setExcludedMcpServers(nextGating.excluded??[]);config.setAllowedMcpServers(nextGating.allowed);config.setPendingMcpServers(nextGating.pending);try{await config.reinitializeMcpServers(next);const finalStatuses=Object.keys(next).map(name=>`${name}=${getMCPServerStatus(name)}`).join(", ");debugLogger.debug(`reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`)}catch(err){debugLogger.error(`reinitializeMcpServers threw: ${err instanceof Error?err.stack??err.message:String(err)}`);appEvents.emit("log-error","Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details.")}if(!isYolo&&promptable.length>0){debugLogger.debug(`gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed"}: [${promptable.join(", ")}]`);appEvents.emit("mcp-pending-approval-changed")}})}__name(registerMcpHotReload,"registerMcpHotReload");function registerModelProvidersHotReload(watcher,settings,config){modelProvidersDebugLogger.debug("registered modelProviders hot-reload listener on SettingsWatcher");let refreshAuthRetryPending=false;const reconcile=__name(async()=>{const next=settings.merged.modelProviders;const providersUnchanged=(0,import_fast_deep_equal.default)(config.getModelProvidersConfig()??{},next??{});if(providersUnchanged&&!refreshAuthRetryPending){return}if(!providersUnchanged){modelProvidersDebugLogger.debug("modelProviders changed \u2014 reloading model registry");try{config.reloadModelProvidersConfig(next)}catch(err){modelProvidersDebugLogger.error(`reloadModelProvidersConfig threw: ${err instanceof Error?err.stack??err.message:String(err)}`);return}}const authType=config.getAuthType();if(!authType){return}try{await config.refreshAuth(authType,true);refreshAuthRetryPending=false}catch(err){const alreadyPending=refreshAuthRetryPending;refreshAuthRetryPending=true;modelProvidersDebugLogger.error(`refreshAuth after modelProviders reload threw: ${err instanceof Error?err.stack??err.message:String(err)}`);if(!alreadyPending){appEvents.emit("log-error",`Model provider settings reloaded, but re-authenticating the active model failed: ${err instanceof Error?err.message:String(err)}. Select a model with /model or restart to apply the change.`)}}},"reconcile");void reconcile();return watcher.addChangeListener(reconcile)}__name(registerModelProvidersHotReload,"registerModelProvidersHotReload");export{recomputeMcpGating,registerMcpHotReload,registerModelProvidersHotReload};
3
+ import{appEvents}from"./chunk-OTYPLLMT.js";import{assembleMcpServers,getPendingGatedMcpServers,getPromptableMcpServers}from"./chunk-TKP3GAUI.js";import{getMCPServerStatus}from"./chunk-ZWPSBU7K.js";import{require_fast_deep_equal}from"./chunk-3KUHQGOS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var debugLogger=createDebugLogger("MCP_HOT_RELOAD");var modelProvidersDebugLogger=createDebugLogger("MODEL_PROVIDERS_HOT_RELOAD");function mcpServersEqual(a,b){return(0,import_fast_deep_equal.default)(a??{},b??{})}__name(mcpServersEqual,"mcpServersEqual");function mcpGatingEqual(a,b){const norm=__name(xs=>[...xs??[]].sort(),"norm");const allowedEqual=a.allowed===void 0===(b.allowed===void 0)&&(0,import_fast_deep_equal.default)(norm(a.allowed),norm(b.allowed));return(0,import_fast_deep_equal.default)(norm(a.excluded),norm(b.excluded))&&allowedEqual&&(0,import_fast_deep_equal.default)(norm(a.pending),norm(b.pending))}__name(mcpGatingEqual,"mcpGatingEqual");function recomputeMcpGating(settings,assembled,cwd,bootAllowed,isYolo){const settingsAllowed=settings.merged.mcp?.allowed?.filter(Boolean);const excluded=settings.merged.mcp?.excluded?.filter(Boolean);let allowed=settingsAllowed;if(bootAllowed){allowed=settingsAllowed?settingsAllowed.filter(n=>bootAllowed.includes(n)):[...bootAllowed]}return{allowed,excluded:excluded&&excluded.length>0?excluded:void 0,pending:isYolo?void 0:getPendingGatedMcpServers(assembled,cwd)}}__name(recomputeMcpGating,"recomputeMcpGating");function registerMcpHotReload(watcher,settings,config,topTierMcpServers){debugLogger.debug("registered MCP hot-reload listener on SettingsWatcher");return watcher.addChangeListener(async events=>{debugLogger.debug(`settings change fired (${events.length} event(s)): ${events.map(e=>`${e.scope}:${e.changeType}`).join(", ")}`);const cwd=config.getTargetDir();const next=config.getBareMode()||config.isSafeMode()?{...topTierMcpServers}:assembleMcpServers(settings.merged.mcpServers,cwd,topTierMcpServers);const isYolo=config.getApprovalMode()==="yolo";const bootAllowed=config.getCliAllowedMcpServerNames();const nextGating=config.getBareMode()||config.isSafeMode()?{allowed:bootAllowed?[...bootAllowed]:void 0}:recomputeMcpGating(settings,next,cwd,bootAllowed,isYolo);const prevServers=config.getSettingsMcpServers();const prevGating=config.getMcpGating();debugLogger.debug(`assembled servers: prev=[${Object.keys(prevServers??{}).join(", ")}] next=[${Object.keys(next).join(", ")}]`);debugLogger.debug(`gating next: excluded=[${(nextGating.excluded??[]).join(", ")}] allowed=[${(nextGating.allowed??[]).join(", ")}] pending=[${(nextGating.pending??[]).join(", ")}]`);const serversChanged=!mcpServersEqual(prevServers,next);const gatingChanged=!mcpGatingEqual(prevGating,nextGating);if(!serversChanged&&!gatingChanged){debugLogger.debug("no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile");return}debugLogger.debug(`MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`);const promptable=getPromptableMcpServers(next,cwd);config.setExcludedMcpServers(nextGating.excluded??[]);config.setAllowedMcpServers(nextGating.allowed);config.setPendingMcpServers(nextGating.pending);try{await config.reinitializeMcpServers(next);const finalStatuses=Object.keys(next).map(name=>`${name}=${getMCPServerStatus(name)}`).join(", ");debugLogger.debug(`reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`)}catch(err){debugLogger.error(`reinitializeMcpServers threw: ${err instanceof Error?err.stack??err.message:String(err)}`);appEvents.emit("log-error","Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details.")}if(!isYolo&&promptable.length>0){debugLogger.debug(`gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed"}: [${promptable.join(", ")}]`);appEvents.emit("mcp-pending-approval-changed")}})}__name(registerMcpHotReload,"registerMcpHotReload");function registerModelProvidersHotReload(watcher,settings,config){modelProvidersDebugLogger.debug("registered modelProviders hot-reload listener on SettingsWatcher");let refreshAuthRetryPending=false;const reconcile=__name(async()=>{const next=settings.merged.modelProviders;const providersUnchanged=(0,import_fast_deep_equal.default)(config.getModelProvidersConfig()??{},next??{});if(providersUnchanged&&!refreshAuthRetryPending){return}if(!providersUnchanged){modelProvidersDebugLogger.debug("modelProviders changed \u2014 reloading model registry");try{config.reloadModelProvidersConfig(next)}catch(err){modelProvidersDebugLogger.error(`reloadModelProvidersConfig threw: ${err instanceof Error?err.stack??err.message:String(err)}`);return}}const authType=config.getAuthType();if(!authType){return}try{await config.refreshAuth(authType,true);refreshAuthRetryPending=false}catch(err){const alreadyPending=refreshAuthRetryPending;refreshAuthRetryPending=true;modelProvidersDebugLogger.error(`refreshAuth after modelProviders reload threw: ${err instanceof Error?err.stack??err.message:String(err)}`);if(!alreadyPending){appEvents.emit("log-error",`Model provider settings reloaded, but re-authenticating the active model failed: ${err instanceof Error?err.message:String(err)}. Select a model with /model or restart to apply the change.`)}}},"reconcile");void reconcile();return watcher.addChangeListener(reconcile)}__name(registerModelProvidersHotReload,"registerModelProvidersHotReload");export{recomputeMcpGating,registerMcpHotReload,registerModelProvidersHotReload};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{SessionOrganizationService}from"./chunk-2JGTWRZJ.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function createSessionOrganizationService(workspaceCwd){return new SessionOrganizationService(workspaceCwd,message=>{writeStderrLine(`qwen serve: session-org: ${message}`)})}__name(createSessionOrganizationService,"createSessionOrganizationService");export{createSessionOrganizationService};
3
+ import{SessionOrganizationService}from"./chunk-7XQ5D34E.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function createSessionOrganizationService(workspaceCwd){return new SessionOrganizationService(workspaceCwd,message=>{writeStderrLine(`qwen serve: session-org: ${message}`)})}__name(createSessionOrganizationService,"createSessionOrganizationService");export{createSessionOrganizationService};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{BaseJsonOutputAdapter}from"./chunk-WGFX3EL3.js";import{observeHeadlessJsonToolResultWire}from"./chunk-BPFFRPWE.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonOutputAdapter=class extends BaseJsonOutputAdapter{static{__name(this,"JsonOutputAdapter")}messages=[];attemptMessageCheckpoint=0;lastAssistantMessageAtAttemptStart=null;constructor(config){super(config)}emitMessageImpl(message){this.messages.push(message);if(typeof message==="object"&&message!==null&&"type"in message&&message.type==="assistant"){this.updateLastAssistantMessage(message)}}shouldEmitStreamEvents(){return false}startAssistantMessage(){this.attemptMessageCheckpoint=this.messages.length;this.lastAssistantMessageAtAttemptStart=this.lastAssistantMessage;super.startAssistantMessage()}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant"||!message.message.content.some(block=>block.type==="tool_use"&&discardedIds.has(block.id)));this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.messages.findLast(message=>message.type==="assistant")??this.lastAssistantMessageAtAttemptStart}}else{const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant");this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.lastAssistantMessageAtAttemptStart}super.restartAttempt(preserveText,discardedToolCalls)}finalizeAssistantMessage(){return this.finalizeAssistantMessageInternal(this.mainAgentMessageState,null)}emitResult(options){const resultMessage=this.buildResultMessage(options,this.lastAssistantMessage);this.messages.push(resultMessage);if(this.config.getOutputFormat()==="text"){if(resultMessage.is_error){process.stderr.write(`${resultMessage.error?.message||""}
3
+ import{BaseJsonOutputAdapter}from"./chunk-5FGBLIXB.js";import{observeHeadlessJsonToolResultWire}from"./chunk-5ZNXAWOG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonOutputAdapter=class extends BaseJsonOutputAdapter{static{__name(this,"JsonOutputAdapter")}messages=[];attemptMessageCheckpoint=0;lastAssistantMessageAtAttemptStart=null;constructor(config){super(config)}emitMessageImpl(message){this.messages.push(message);if(typeof message==="object"&&message!==null&&"type"in message&&message.type==="assistant"){this.updateLastAssistantMessage(message)}}shouldEmitStreamEvents(){return false}startAssistantMessage(){this.attemptMessageCheckpoint=this.messages.length;this.lastAssistantMessageAtAttemptStart=this.lastAssistantMessage;super.startAssistantMessage()}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant"||!message.message.content.some(block=>block.type==="tool_use"&&discardedIds.has(block.id)));this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.messages.findLast(message=>message.type==="assistant")??this.lastAssistantMessageAtAttemptStart}}else{const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant");this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.lastAssistantMessageAtAttemptStart}super.restartAttempt(preserveText,discardedToolCalls)}finalizeAssistantMessage(){return this.finalizeAssistantMessageInternal(this.mainAgentMessageState,null)}emitResult(options){const resultMessage=this.buildResultMessage(options,this.lastAssistantMessage);this.messages.push(resultMessage);if(this.config.getOutputFormat()==="text"){if(resultMessage.is_error){process.stderr.write(`${resultMessage.error?.message||""}
4
4
  `)}else{process.stdout.write(`${resultMessage.result}
5
5
  `)}}else{const json=JSON.stringify(this.messages);const frame=`${json}
6
6
  `;observeHeadlessJsonToolResultWire(this.messages,frame);process.stdout.write(frame)}}emitMessage(message){this.messages.push(message)}};export{JsonOutputAdapter};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{memoryImportReservation,validateMemoryImportBatchProposal}from"./chunk-JEDL4IKF.js";import{MEMORY_IMPORT_BUDGET,MemoryImportRequestError,digest,packMemoryImportSections,previewSource}from"./chunk-76FSYQTG.js";import{rebuildAutoMemoryIndexAtRoot,tokenizeMemoryRecallTerms,tokenizeMemoryRecallText}from"./chunk-2JGTWRZJ.js";import{parseAutoMemoryTopicDocument,resolveTrustedMemoryFile,scanAutoMemorySnapshot}from"./chunk-FUBDS3AV.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{getImportedProjectMemoryRoot,getMemoryRootTrustedAnchor,getUserAutoMemoryRoot}from"./chunk-KVA6DHHF.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs from"node:fs/promises";import{constants}from"node:fs";import{randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";var MemoryImportNotFoundError=class extends Error{static{__name(this,"MemoryImportNotFoundError")}code="ENOENT"};var ImportBudgetError=class extends Error{static{__name(this,"ImportBudgetError")}};var ImportContextError=class extends Error{static{__name(this,"ImportContextError")}};var heldLocks=new AsyncLocalStorage;var exists=__name(async file=>fs.lstat(file).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error}),"exists");async function privateDirectory(directory,anchor){const relative=path.relative(anchor,directory);if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import path escapes runtime.");let current=anchor;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);await fs.mkdir(current,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Import runtime directory must not be a symlink.")}}__name(privateDirectory,"privateDirectory");async function readJson(file){const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>16*1024*1024)throw new Error("Invalid import state file.");const buffer=Buffer.alloc(stat.size+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>stat.size)throw new Error("Import state exceeds the supported limit.");return JSON.parse(buffer.subarray(0,bytesRead).toString("utf8"))}finally{await handle.close()}}__name(readJson,"readJson");async function writeJson(file,value){heldLocks.getStore()?.throwIfAborted();const tmp=`${file}.${randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value),{mode:384,flag:"wx"});try{heldLocks.getStore()?.throwIfAborted();await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}}__name(writeJson,"writeJson");async function abortable(signal,work){signal.throwIfAborted();let abort;const cancelled=new Promise((_resolve,reject)=>{abort=__name(()=>reject(new Error("Import cancelled.")),"abort");signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work(),cancelled])}finally{signal.removeEventListener("abort",abort)}}__name(abortable,"abortable");function publicTask(task){const{requestDigest:_requestDigest,...result}=task;return structuredClone({...result,usage:task.usage??{modelCalls:0,reservedTokens:0},budget:task.budget??{maxCalls:0,maxReservedTokens:0},result:{sourceSections:task.items.length,newDocuments:task.items.filter(item=>item.status==="added").reduce((n,item)=>n+(item.refs?.length??0),0),duplicateSections:task.items.filter(item=>item.status==="duplicate").length,conflictSections:task.items.filter(item=>item.status==="conflict").length,failedSections:task.items.filter(item=>item.status==="failed").length}})}__name(publicTask,"publicTask");function selectImportContext(existing,sources){const queries=sources.map(source=>({text:source.normalize("NFKC").toLowerCase(),terms:tokenizeMemoryRecallTerms(source)}));const index=existing.map(item=>{const parsed=parseAutoMemoryTopicDocument("existing.md",item.content);if(!parsed)throw new ImportContextError("Existing memory has no bounded metadata index. Repair its native metadata before importing.");const metadata=JSON.stringify({name:parsed.title,description:parsed.description,type:parsed.type,category:parsed.category,keywords:parsed.keywords,usage_scenarios:parsed.usageScenarios});const words=tokenizeMemoryRecallText([parsed.title,...parsed.keywords].join(" "));const anchors=[parsed.title,parsed.description].map(text=>text.normalize("NFKC").toLowerCase().trim()).filter(text=>tokenizeMemoryRecallText(text).length>=2);const body=parsed.body.normalize("NFKC").toLowerCase().trim();const relevant=queries.some(({text,terms})=>{if(anchors.some(anchor=>text.includes(anchor))||body.length>0&&text.includes(body))return true;const shared=words.filter(word=>terms.has(word));return shared.length>=2&&shared.length>=words.length/2});return{ref:item.ref,content:relevant?item.content:metadata,indexOnly:!relevant}});const context=[];let bytes=2;for(const entry of[...index.filter(item=>!item.indexOnly),...index.filter(item=>item.indexOnly)]){const size=Buffer.byteLength(JSON.stringify(entry))+(context.length?1:0);if(bytes+size>MEMORY_IMPORT_BUDGET.contextBytes){if(!entry.indexOnly)throw new ImportContextError("Relevant existing evidence exceeds the 32 KiB import context budget. Select a narrower source group or consolidate existing memory before retrying. No model call was made.");continue}bytes+=size;context.push(entry)}return context}__name(selectImportContext,"selectImportContext");function respectsImportScope(proposal,scope){return scope!=="user"||proposal.documents.every(content=>{const type=parseAutoMemoryTopicDocument("import.md",content)?.type;return type==="user"||type==="feedback"})}__name(respectsImportScope,"respectsImportScope");var MemoryImportService=class{constructor(options){this.options=options;this.owner=digest(path.resolve(options.projectRoot))}static{__name(this,"MemoryImportService")}base=Storage.getRuntimeBaseDir();state=path.join(this.base,"memory-import");owner;workers=new Map;controllers=new Map;async readState(file){const relative=path.relative(this.base,path.dirname(file));if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import state escapes runtime.");let current=this.base;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Invalid import state directory.")}return readJson(file)}taskDir(id){if(!/^[a-f0-9]{64}$/.test(id))throw new MemoryImportRequestError("Invalid import batch ID.");return path.join(this.state,"batches",this.owner,id)}async assertRuntimeOutsideGit(){let current=path.resolve(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a runtime directory outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}await fs.mkdir(this.base,{recursive:true,mode:448});current=await fs.realpath(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a private runtime outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}}async prepare(){this.options.assertActive();await this.assertRuntimeOutsideGit();await privateDirectory(path.join(this.state,"batches",this.owner),this.base)}async locked(directory,run,signal){await privateDirectory(directory,this.base);const ownership=new AbortController;const parent=heldLocks.getStore();const held=parent?AbortSignal.any([parent,ownership.signal]):ownership.signal;const work=signal?AbortSignal.any([signal,held]):held;let release;while(!release){work.throwIfAborted();this.options.assertActive();try{release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,update:1e4,retries:0,onCompromised:__name(()=>{ownership.abort(new Error("Import lock lost."))},"onCompromised")})}catch(error){if(error.code!=="ELOCKED")throw error;await new Promise(resolve=>setTimeout(resolve,250))}}try{work.throwIfAborted();const result=await heldLocks.run(held,()=>run(work));held.throwIfAborted();return result}finally{try{if(!ownership.signal.aborted)await release()}finally{ownership.abort(new Error("Import lock released."))}}}async submit(input,selections,key){this.options.assertActive();const preview=previewSource(input);if(typeof key!=="string"||!/^[\w-]{1,128}$/.test(key)||!Array.isArray(selections)||!selections.length||selections.length>2048)throw new MemoryImportRequestError("Provide an idempotency key and explicit non-empty selection.");const seen=new Set;const selected=selections.map(value=>{if(!value||typeof value!=="object")throw new MemoryImportRequestError("Invalid selection.");const selection=value;const section=preview.sections.find(item=>item.id===selection.id&&item.selectable);if(!section||seen.has(selection.id)||!["project","user"].includes(selection.scope))throw new MemoryImportRequestError("Invalid, duplicate or unavailable section selection.");seen.add(selection.id);return{...section,scope:selection.scope}}).sort((a,b)=>a.id.localeCompare(b.id));const retained=JSON.stringify({sections:selected});if(Buffer.byteLength(retained)>16*1024*1024)throw new MemoryImportRequestError("Selected contextual source exceeds the retained snapshot limit.");const requestDigest=digest(JSON.stringify(selected));const id=digest(`${this.owner}\0${key}`);await this.prepare();const dir=this.taskDir(id);return this.locked(path.join(this.state,"admission",this.owner),async()=>{this.options.assertActive();if(await exists(path.join(dir,"task.json"))){const task2=await this.readState(path.join(dir,"task.json"));if(task2.requestDigest!==requestDigest)throw new MemoryImportRequestError("Idempotency key was already used with a different selection.");this.kick(id);return publicTask(task2)}await privateDirectory(dir,this.base);await writeJson(path.join(dir,"source.json"),{sections:selected});const now=new Date().toISOString();const task={version:1,kind:"task",id,status:"queued",createdAt:now,updatedAt:now,requestDigest,usage:{modelCalls:0,reservedTokens:0},budget:{maxCalls:MEMORY_IMPORT_BUDGET.maxCalls,maxReservedTokens:MEMORY_IMPORT_BUDGET.maxReservedTokens},items:selected.map(section=>({id:section.id,scope:section.scope,status:"pending"}))};await writeJson(path.join(dir,"task.json"),task);this.kick(id);return publicTask(task)})}kick(id){if(this.workers.has(id))return;const worker=heldLocks.exit(()=>this.run(id)).catch(()=>{}).finally(()=>{this.workers.delete(id);this.controllers.delete(id)});this.workers.set(id,worker)}async recover(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return;await this.assertRuntimeOutsideGit();await privateDirectory(root,this.base);for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(()=>void 0);if(task&&(task.status==="running"||task.status==="queued"))this.kick(id)}}async list(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return[];await privateDirectory(root,this.base);const result=[];for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.get(id).catch(()=>void 0);if(task)result.push(task)}return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt))}async get(id){this.options.assertActive();const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(cause=>{if(cause.code==="ENOENT")throw new MemoryImportNotFoundError("Import batch not found.",{cause});throw cause});if(task.status!=="completed"&&await exists(path.join(this.taskDir(id),"cancel.json")))task.status="cancelled";return publicTask(task)}async source(id,sectionId){await this.get(id);const source=await this.readState(path.join(this.taskDir(id),"source.json"));const section=source.sections.find(item=>item.id===sectionId);if(!section)throw new MemoryImportRequestError("Source section not found in this batch.");return section}async cancel(id){this.options.assertActive();this.controllers.get(id)?.abort();const task=await this.get(id);if(task.status==="completed")return task;await writeJson(path.join(this.taskDir(id),"cancel.json"),{cancelled:true});this.controllers.get(id)?.abort();await this.workers.get(id);return this.get(id)}async retry(id){await this.get(id);await this.prepare();await this.workers.get(id);const dir=this.taskDir(id);const result=await this.locked(dir,async()=>{const task=await this.readState(path.join(dir,"task.json"));if(task.status==="completed")return publicTask(task);await fs.rm(path.join(dir,"cancel.json"),{force:true});for(const item of task.items)if(item.status==="failed"){item.status="pending";delete item.reason}task.status="queued";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task);return publicTask(task)});this.kick(id);return result}async idle(id){await this.workers.get(id);return this.get(id)}async run(id){const dir=this.taskDir(id);const controller=new AbortController;this.controllers.set(id,controller);await this.locked(dir,async signal=>{const task=await this.readState(path.join(dir,"task.json"));if(!["queued","running"].includes(task.status))return;const source=await this.readState(path.join(dir,"source.json"));if(!task.usage){task.usage={modelCalls:0,reservedTokens:0};task.budget={maxCalls:0,maxReservedTokens:0}}task.budget??={maxCalls:0,maxReservedTokens:0};task.status="running";await writeJson(path.join(dir,"task.json"),task);for(const section of packMemoryImportSections(source.sections).flat()){const item=task.items.find(item2=>item2.id===section.id);if(item.status!=="pending")continue;if(await exists(path.join(dir,"cancel.json")))controller.abort();if(controller.signal.aborted)break;try{this.options.assertActive();Object.assign(item,await this.importSection(section,id,signal,(before,ledger,proposalSignal)=>this.prepareProposal(section,source,task,before,ledger,proposalSignal),async()=>{if(await exists(path.join(dir,"cancel.json")))controller.abort();controller.signal.throwIfAborted();this.options.assertActive()}))}catch(error){if(controller.signal.aborted)break;item.status="failed";item.reason=error instanceof ImportBudgetError||error instanceof ImportContextError?error.message:"Import could not finish. Existing memories were preserved; retry after resolving runtime, model or storage availability."}task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)}task.status=controller.signal.aborted?"cancelled":task.items.some(item=>item.status==="failed")?"partial":"completed";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)},controller.signal)}async prepareProposal(section,source,task,before,ledger,signal){const dir=this.taskDir(task.id);const journalFile=path.join(dir,"proposals.json");const journals=await exists(journalFile)?await this.readState(journalFile):[];let journal=journals.find(entry=>entry.scope===section.scope&&entry.sections.some(item=>item.id===section.id));if(journal&&!respectsImportScope(journal.proposal.items.find(item=>item.id===section.id),section.scope)){journal.sections=journal.sections.filter(item=>item.id!==section.id);journal.proposal.items=journal.proposal.items.filter(item=>item.id!==section.id);if(!journal.sections.length)journals.splice(journals.indexOf(journal),1);await writeJson(journalFile,journals);journal=void 0}if(!journal){const eligible=source.sections.filter(candidate=>candidate.scope===section.scope&&candidate.groupId===section.groupId&&task.items.some(item=>item.id===candidate.id&&item.status==="pending")&&!ledger[candidate.id]&&!journals.some(entry=>entry.sections.some(item=>item.id===candidate.id)));const batch=packMemoryImportSections(eligible).find(items=>items.some(item=>item.id===section.id));if(!batch)throw new Error("Source batch is unavailable.");const input={scope:section.scope,sources:batch.map(({id,content})=>({id,content})),existing:selectImportContext(before.existing,batch.map(item=>item.content))};const reserved=memoryImportReservation(input);if(task.usage.modelCalls>=Math.min(task.budget.maxCalls,MEMORY_IMPORT_BUDGET.maxCalls)||task.usage.reservedTokens+reserved>Math.min(task.budget.maxReservedTokens,MEMORY_IMPORT_BUDGET.maxReservedTokens))throw new ImportBudgetError("Import budget exhausted. Retry preserves this budget; split remaining sources into an explicitly confirmed new task.");signal.throwIfAborted();task.usage.modelCalls++;task.usage.reservedTokens+=reserved;await writeJson(path.join(dir,"task.json"),task);let proposal;try{proposal=validateMemoryImportBatchProposal(await abortable(signal,()=>this.options.propose(input,signal)),batch.map(item=>item.id));if(proposal.items.some(item=>!respectsImportScope(item,section.scope)))throw new ImportContextError("Model returned project knowledge for user memory. Retry to request a scope-valid response; consumed budget is retained.")}catch(error){if(!signal.aborted){for(const item of task.items)if(batch.some(section2=>section2.id===item.id)){item.status="failed";item.reason="Model batch failed validation or execution; explicit retry retains its consumed budget."}}throw error}signal.throwIfAborted();journal={scope:section.scope,sections:batch.map(item=>({id:item.id,key:item.id})),baseline:before.existing.map(item=>({ref:item.ref,digest:digest(item.content)})),proposal};journals.push(journal);await writeJson(journalFile,journals)}const expected=new Map(journal.baseline.map(item=>[item.ref,item.digest]));for(const record of Object.values(ledger)){if(record.phase==="committed")for(const output of record.outputs){const ref=`${section.scope}:${output.relativePath}`;if(!expected.has(ref))expected.set(ref,output.digest)}}if(expected.size!==before.existing.length||before.existing.some(item=>expected.get(item.ref)!==digest(item.content)))return{decision:"conflict",reason:"Existing memory changed since this batch was consolidated; retained proposals cannot overwrite edits or restore forgotten knowledge.",documents:[]};return journal.proposal.items.find(item=>item.id===section.id)}async snapshot(scope){const snapshot=await scanAutoMemorySnapshot(this.options.projectRoot,{scopes:[scope],trustedProject:true,uncapped:true});if(!snapshot.sourceStatus.complete)throw new Error("Existing memory scan is incomplete.");const existing=[];for(const doc of snapshot.docs)existing.push({ref:`${scope}:${doc.relativePath}`,content:await fs.readFile(doc.filePath,"utf8")});existing.sort((a,b)=>a.ref.localeCompare(b.ref));return{version:digest(JSON.stringify(existing)),existing}}async importSection(section,batchId,signal,propose,assertCommit){const root=section.scope==="user"?getUserAutoMemoryRoot():getImportedProjectMemoryRoot(this.options.projectRoot,true);const scopeState=path.join(this.state,"scopes",digest(root));return this.locked(scopeState,async signal2=>{signal2.throwIfAborted();this.options.assertActive();if(await exists(root)&&(await fs.lstat(root)).isSymbolicLink())throw new ImportContextError("Memory import does not support a symlinked memory root. Use a non-symlink memory root before retrying; existing memories were not changed.");const ledgerPath=path.join(scopeState,"ledger.json");const ledger=await exists(ledgerPath)?await this.readState(ledgerPath):{};const key=section.id;let previous=ledger[key];const discardUnpublishedIntent=__name(async stage2=>{signal2.throwIfAborted();this.options.assertActive();delete ledger[key];await writeJson(ledgerPath,ledger);heldLocks.getStore()?.throwIfAborted();await fs.rm(stage2,{recursive:true,force:true})},"discardUnpublishedIntent");const outcome=__name((status,reason)=>({id:section.id,scope:section.scope,status,...reason?{reason}:{}}),"outcome");if(previous?.phase==="intent"){const stage2=path.join(scopeState,previous.stage);if(await exists(stage2)&&!await exists(path.join(root,"imported",key))&&(await this.snapshot(section.scope)).version!==previous.memoryVersion){await discardUnpublishedIntent(stage2);previous=void 0}}if(previous){const stage2=path.join(scopeState,previous.stage);const destination=path.join(root,"imported",key);if(previous.phase==="intent"&&await exists(stage2)&&!await exists(destination)){for(const output of previous.outputs){const file=path.join(stage2,path.basename(output.relativePath));if(digest(await fs.readFile(file,"utf8"))!==output.digest)throw new Error("Invalid staged import.")}signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage2,destination)}for(const output of previous.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously imported memory was edited or forgotten; it will not be restored.")}previous.phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);if(previous.batchId===batchId)return{...previous.outcome,id:section.id,scope:section.scope};return outcome(previous.outcome.status==="added"?"duplicate":previous.outcome.status,"This source has already been processed.")}const before=await this.snapshot(section.scope);const proposal=await propose(before,ledger,signal2);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version)return outcome("conflict","Existing memory changed during consolidation; preview and retry the source.");await assertCommit();if(proposal.decision==="conflict")return outcome("conflict",proposal.reason);if(proposal.decision!=="new"){const result2=outcome(proposal.decision==="skip"?"skipped":"duplicate",proposal.reason);ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const documents=[];for(const content of new Set(proposal.documents)){const parsed=parseAutoMemoryTopicDocument("import.md",content);if(!parsed)throw new Error("Invalid native memory.");if(section.scope==="user"&&parsed.type!=="user"&&parsed.type!=="feedback")throw new Error("Project knowledge cannot be imported into user memory.");const bodyDigest=digest(parsed.body.trim());for(const[sourceId,record]of Object.entries(ledger)){if(record.outputs.some(output=>output.bodyDigest===bodyDigest)){if(record.phase==="intent"&&!await exists(path.join(root,"imported",sourceId)))continue;for(const output of record.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously edited or forgotten imported knowledge cannot be recreated.")}}}if(before.existing.some(existing=>parseAutoMemoryTopicDocument("existing.md",existing.content)?.body.trim()===parsed.body.trim()))continue;if(!documents.some(existing=>parseAutoMemoryTopicDocument("new.md",existing)?.body.trim()===parsed.body.trim()))documents.push(content)}if(!documents.length){const result2=outcome("duplicate","All proposed knowledge already exists.");ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const stageName=`stage-${key}`;const stage=path.join(scopeState,stageName);if(await exists(stage)){await privateDirectory(stage,this.base);await fs.rm(stage,{recursive:true})}await privateDirectory(stage,this.base);const outputs=[];for(const[index,content]of documents.entries()){const filename=`${index}.md`;await fs.writeFile(path.join(stage,filename),content,{flag:"wx",mode:384});outputs.push({relativePath:`imported/${key}/${filename}`,digest:digest(content),bodyDigest:digest(parseAutoMemoryTopicDocument("import.md",content).body.trim())})}const result={...outcome("added",proposal.reason),refs:outputs.map(output=>`${section.scope}:${output.relativePath}`)};ledger[key]={batchId,phase:"intent",outputs,stage:stageName,memoryVersion:before.version,outcome:result};await writeJson(ledgerPath,ledger);signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version){await discardUnpublishedIntent(stage);return outcome("conflict","Existing memory changed before publication.")}await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage,path.join(root,"imported",key));ledger[key].phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);return result},signal)}};export{MemoryImportNotFoundError,MemoryImportService};
3
+ import{memoryImportReservation,validateMemoryImportBatchProposal}from"./chunk-EIFBGEXJ.js";import{MEMORY_IMPORT_BUDGET,MemoryImportRequestError,digest,packMemoryImportSections,previewSource}from"./chunk-YMEW4TTT.js";import{rebuildAutoMemoryIndexAtRoot,tokenizeMemoryRecallTerms,tokenizeMemoryRecallText}from"./chunk-7XQ5D34E.js";import{parseAutoMemoryTopicDocument,resolveTrustedMemoryFile,scanAutoMemorySnapshot}from"./chunk-FUBDS3AV.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{getImportedProjectMemoryRoot,getMemoryRootTrustedAnchor,getUserAutoMemoryRoot}from"./chunk-KVA6DHHF.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs from"node:fs/promises";import{constants}from"node:fs";import{randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";var MemoryImportNotFoundError=class extends Error{static{__name(this,"MemoryImportNotFoundError")}code="ENOENT"};var ImportBudgetError=class extends Error{static{__name(this,"ImportBudgetError")}};var ImportContextError=class extends Error{static{__name(this,"ImportContextError")}};var heldLocks=new AsyncLocalStorage;var exists=__name(async file=>fs.lstat(file).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error}),"exists");async function privateDirectory(directory,anchor){const relative=path.relative(anchor,directory);if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import path escapes runtime.");let current=anchor;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);await fs.mkdir(current,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Import runtime directory must not be a symlink.")}}__name(privateDirectory,"privateDirectory");async function readJson(file){const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>16*1024*1024)throw new Error("Invalid import state file.");const buffer=Buffer.alloc(stat.size+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>stat.size)throw new Error("Import state exceeds the supported limit.");return JSON.parse(buffer.subarray(0,bytesRead).toString("utf8"))}finally{await handle.close()}}__name(readJson,"readJson");async function writeJson(file,value){heldLocks.getStore()?.throwIfAborted();const tmp=`${file}.${randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value),{mode:384,flag:"wx"});try{heldLocks.getStore()?.throwIfAborted();await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}}__name(writeJson,"writeJson");async function abortable(signal,work){signal.throwIfAborted();let abort;const cancelled=new Promise((_resolve,reject)=>{abort=__name(()=>reject(new Error("Import cancelled.")),"abort");signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work(),cancelled])}finally{signal.removeEventListener("abort",abort)}}__name(abortable,"abortable");function publicTask(task){const{requestDigest:_requestDigest,...result}=task;return structuredClone({...result,usage:task.usage??{modelCalls:0,reservedTokens:0},budget:task.budget??{maxCalls:0,maxReservedTokens:0},result:{sourceSections:task.items.length,newDocuments:task.items.filter(item=>item.status==="added").reduce((n,item)=>n+(item.refs?.length??0),0),duplicateSections:task.items.filter(item=>item.status==="duplicate").length,conflictSections:task.items.filter(item=>item.status==="conflict").length,failedSections:task.items.filter(item=>item.status==="failed").length}})}__name(publicTask,"publicTask");function selectImportContext(existing,sources){const queries=sources.map(source=>({text:source.normalize("NFKC").toLowerCase(),terms:tokenizeMemoryRecallTerms(source)}));const index=existing.map(item=>{const parsed=parseAutoMemoryTopicDocument("existing.md",item.content);if(!parsed)throw new ImportContextError("Existing memory has no bounded metadata index. Repair its native metadata before importing.");const metadata=JSON.stringify({name:parsed.title,description:parsed.description,type:parsed.type,category:parsed.category,keywords:parsed.keywords,usage_scenarios:parsed.usageScenarios});const words=tokenizeMemoryRecallText([parsed.title,...parsed.keywords].join(" "));const anchors=[parsed.title,parsed.description].map(text=>text.normalize("NFKC").toLowerCase().trim()).filter(text=>tokenizeMemoryRecallText(text).length>=2);const body=parsed.body.normalize("NFKC").toLowerCase().trim();const relevant=queries.some(({text,terms})=>{if(anchors.some(anchor=>text.includes(anchor))||body.length>0&&text.includes(body))return true;const shared=words.filter(word=>terms.has(word));return shared.length>=2&&shared.length>=words.length/2});return{ref:item.ref,content:relevant?item.content:metadata,indexOnly:!relevant}});const context=[];let bytes=2;for(const entry of[...index.filter(item=>!item.indexOnly),...index.filter(item=>item.indexOnly)]){const size=Buffer.byteLength(JSON.stringify(entry))+(context.length?1:0);if(bytes+size>MEMORY_IMPORT_BUDGET.contextBytes){if(!entry.indexOnly)throw new ImportContextError("Relevant existing evidence exceeds the 32 KiB import context budget. Select a narrower source group or consolidate existing memory before retrying. No model call was made.");continue}bytes+=size;context.push(entry)}return context}__name(selectImportContext,"selectImportContext");function respectsImportScope(proposal,scope){return scope!=="user"||proposal.documents.every(content=>{const type=parseAutoMemoryTopicDocument("import.md",content)?.type;return type==="user"||type==="feedback"})}__name(respectsImportScope,"respectsImportScope");var MemoryImportService=class{constructor(options){this.options=options;this.owner=digest(path.resolve(options.projectRoot))}static{__name(this,"MemoryImportService")}base=Storage.getRuntimeBaseDir();state=path.join(this.base,"memory-import");owner;workers=new Map;controllers=new Map;async readState(file){const relative=path.relative(this.base,path.dirname(file));if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import state escapes runtime.");let current=this.base;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Invalid import state directory.")}return readJson(file)}taskDir(id){if(!/^[a-f0-9]{64}$/.test(id))throw new MemoryImportRequestError("Invalid import batch ID.");return path.join(this.state,"batches",this.owner,id)}async assertRuntimeOutsideGit(){let current=path.resolve(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a runtime directory outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}await fs.mkdir(this.base,{recursive:true,mode:448});current=await fs.realpath(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a private runtime outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}}async prepare(){this.options.assertActive();await this.assertRuntimeOutsideGit();await privateDirectory(path.join(this.state,"batches",this.owner),this.base)}async locked(directory,run,signal){await privateDirectory(directory,this.base);const ownership=new AbortController;const parent=heldLocks.getStore();const held=parent?AbortSignal.any([parent,ownership.signal]):ownership.signal;const work=signal?AbortSignal.any([signal,held]):held;let release;while(!release){work.throwIfAborted();this.options.assertActive();try{release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,update:1e4,retries:0,onCompromised:__name(()=>{ownership.abort(new Error("Import lock lost."))},"onCompromised")})}catch(error){if(error.code!=="ELOCKED")throw error;await new Promise(resolve=>setTimeout(resolve,250))}}try{work.throwIfAborted();const result=await heldLocks.run(held,()=>run(work));held.throwIfAborted();return result}finally{try{if(!ownership.signal.aborted)await release()}finally{ownership.abort(new Error("Import lock released."))}}}async submit(input,selections,key){this.options.assertActive();const preview=previewSource(input);if(typeof key!=="string"||!/^[\w-]{1,128}$/.test(key)||!Array.isArray(selections)||!selections.length||selections.length>2048)throw new MemoryImportRequestError("Provide an idempotency key and explicit non-empty selection.");const seen=new Set;const selected=selections.map(value=>{if(!value||typeof value!=="object")throw new MemoryImportRequestError("Invalid selection.");const selection=value;const section=preview.sections.find(item=>item.id===selection.id&&item.selectable);if(!section||seen.has(selection.id)||!["project","user"].includes(selection.scope))throw new MemoryImportRequestError("Invalid, duplicate or unavailable section selection.");seen.add(selection.id);return{...section,scope:selection.scope}}).sort((a,b)=>a.id.localeCompare(b.id));const retained=JSON.stringify({sections:selected});if(Buffer.byteLength(retained)>16*1024*1024)throw new MemoryImportRequestError("Selected contextual source exceeds the retained snapshot limit.");const requestDigest=digest(JSON.stringify(selected));const id=digest(`${this.owner}\0${key}`);await this.prepare();const dir=this.taskDir(id);return this.locked(path.join(this.state,"admission",this.owner),async()=>{this.options.assertActive();if(await exists(path.join(dir,"task.json"))){const task2=await this.readState(path.join(dir,"task.json"));if(task2.requestDigest!==requestDigest)throw new MemoryImportRequestError("Idempotency key was already used with a different selection.");this.kick(id);return publicTask(task2)}await privateDirectory(dir,this.base);await writeJson(path.join(dir,"source.json"),{sections:selected});const now=new Date().toISOString();const task={version:1,kind:"task",id,status:"queued",createdAt:now,updatedAt:now,requestDigest,usage:{modelCalls:0,reservedTokens:0},budget:{maxCalls:MEMORY_IMPORT_BUDGET.maxCalls,maxReservedTokens:MEMORY_IMPORT_BUDGET.maxReservedTokens},items:selected.map(section=>({id:section.id,scope:section.scope,status:"pending"}))};await writeJson(path.join(dir,"task.json"),task);this.kick(id);return publicTask(task)})}kick(id){if(this.workers.has(id))return;const worker=heldLocks.exit(()=>this.run(id)).catch(()=>{}).finally(()=>{this.workers.delete(id);this.controllers.delete(id)});this.workers.set(id,worker)}async recover(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return;await this.assertRuntimeOutsideGit();await privateDirectory(root,this.base);for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(()=>void 0);if(task&&(task.status==="running"||task.status==="queued"))this.kick(id)}}async list(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return[];await privateDirectory(root,this.base);const result=[];for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.get(id).catch(()=>void 0);if(task)result.push(task)}return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt))}async get(id){this.options.assertActive();const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(cause=>{if(cause.code==="ENOENT")throw new MemoryImportNotFoundError("Import batch not found.",{cause});throw cause});if(task.status!=="completed"&&await exists(path.join(this.taskDir(id),"cancel.json")))task.status="cancelled";return publicTask(task)}async source(id,sectionId){await this.get(id);const source=await this.readState(path.join(this.taskDir(id),"source.json"));const section=source.sections.find(item=>item.id===sectionId);if(!section)throw new MemoryImportRequestError("Source section not found in this batch.");return section}async cancel(id){this.options.assertActive();this.controllers.get(id)?.abort();const task=await this.get(id);if(task.status==="completed")return task;await writeJson(path.join(this.taskDir(id),"cancel.json"),{cancelled:true});this.controllers.get(id)?.abort();await this.workers.get(id);return this.get(id)}async retry(id){await this.get(id);await this.prepare();await this.workers.get(id);const dir=this.taskDir(id);const result=await this.locked(dir,async()=>{const task=await this.readState(path.join(dir,"task.json"));if(task.status==="completed")return publicTask(task);await fs.rm(path.join(dir,"cancel.json"),{force:true});for(const item of task.items)if(item.status==="failed"){item.status="pending";delete item.reason}task.status="queued";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task);return publicTask(task)});this.kick(id);return result}async idle(id){await this.workers.get(id);return this.get(id)}async run(id){const dir=this.taskDir(id);const controller=new AbortController;this.controllers.set(id,controller);await this.locked(dir,async signal=>{const task=await this.readState(path.join(dir,"task.json"));if(!["queued","running"].includes(task.status))return;const source=await this.readState(path.join(dir,"source.json"));if(!task.usage){task.usage={modelCalls:0,reservedTokens:0};task.budget={maxCalls:0,maxReservedTokens:0}}task.budget??={maxCalls:0,maxReservedTokens:0};task.status="running";await writeJson(path.join(dir,"task.json"),task);for(const section of packMemoryImportSections(source.sections).flat()){const item=task.items.find(item2=>item2.id===section.id);if(item.status!=="pending")continue;if(await exists(path.join(dir,"cancel.json")))controller.abort();if(controller.signal.aborted)break;try{this.options.assertActive();Object.assign(item,await this.importSection(section,id,signal,(before,ledger,proposalSignal)=>this.prepareProposal(section,source,task,before,ledger,proposalSignal),async()=>{if(await exists(path.join(dir,"cancel.json")))controller.abort();controller.signal.throwIfAborted();this.options.assertActive()}))}catch(error){if(controller.signal.aborted)break;item.status="failed";item.reason=error instanceof ImportBudgetError||error instanceof ImportContextError?error.message:"Import could not finish. Existing memories were preserved; retry after resolving runtime, model or storage availability."}task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)}task.status=controller.signal.aborted?"cancelled":task.items.some(item=>item.status==="failed")?"partial":"completed";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)},controller.signal)}async prepareProposal(section,source,task,before,ledger,signal){const dir=this.taskDir(task.id);const journalFile=path.join(dir,"proposals.json");const journals=await exists(journalFile)?await this.readState(journalFile):[];let journal=journals.find(entry=>entry.scope===section.scope&&entry.sections.some(item=>item.id===section.id));if(journal&&!respectsImportScope(journal.proposal.items.find(item=>item.id===section.id),section.scope)){journal.sections=journal.sections.filter(item=>item.id!==section.id);journal.proposal.items=journal.proposal.items.filter(item=>item.id!==section.id);if(!journal.sections.length)journals.splice(journals.indexOf(journal),1);await writeJson(journalFile,journals);journal=void 0}if(!journal){const eligible=source.sections.filter(candidate=>candidate.scope===section.scope&&candidate.groupId===section.groupId&&task.items.some(item=>item.id===candidate.id&&item.status==="pending")&&!ledger[candidate.id]&&!journals.some(entry=>entry.sections.some(item=>item.id===candidate.id)));const batch=packMemoryImportSections(eligible).find(items=>items.some(item=>item.id===section.id));if(!batch)throw new Error("Source batch is unavailable.");const input={scope:section.scope,sources:batch.map(({id,content})=>({id,content})),existing:selectImportContext(before.existing,batch.map(item=>item.content))};const reserved=memoryImportReservation(input);if(task.usage.modelCalls>=Math.min(task.budget.maxCalls,MEMORY_IMPORT_BUDGET.maxCalls)||task.usage.reservedTokens+reserved>Math.min(task.budget.maxReservedTokens,MEMORY_IMPORT_BUDGET.maxReservedTokens))throw new ImportBudgetError("Import budget exhausted. Retry preserves this budget; split remaining sources into an explicitly confirmed new task.");signal.throwIfAborted();task.usage.modelCalls++;task.usage.reservedTokens+=reserved;await writeJson(path.join(dir,"task.json"),task);let proposal;try{proposal=validateMemoryImportBatchProposal(await abortable(signal,()=>this.options.propose(input,signal)),batch.map(item=>item.id));if(proposal.items.some(item=>!respectsImportScope(item,section.scope)))throw new ImportContextError("Model returned project knowledge for user memory. Retry to request a scope-valid response; consumed budget is retained.")}catch(error){if(!signal.aborted){for(const item of task.items)if(batch.some(section2=>section2.id===item.id)){item.status="failed";item.reason="Model batch failed validation or execution; explicit retry retains its consumed budget."}}throw error}signal.throwIfAborted();journal={scope:section.scope,sections:batch.map(item=>({id:item.id,key:item.id})),baseline:before.existing.map(item=>({ref:item.ref,digest:digest(item.content)})),proposal};journals.push(journal);await writeJson(journalFile,journals)}const expected=new Map(journal.baseline.map(item=>[item.ref,item.digest]));for(const record of Object.values(ledger)){if(record.phase==="committed")for(const output of record.outputs){const ref=`${section.scope}:${output.relativePath}`;if(!expected.has(ref))expected.set(ref,output.digest)}}if(expected.size!==before.existing.length||before.existing.some(item=>expected.get(item.ref)!==digest(item.content)))return{decision:"conflict",reason:"Existing memory changed since this batch was consolidated; retained proposals cannot overwrite edits or restore forgotten knowledge.",documents:[]};return journal.proposal.items.find(item=>item.id===section.id)}async snapshot(scope){const snapshot=await scanAutoMemorySnapshot(this.options.projectRoot,{scopes:[scope],trustedProject:true,uncapped:true});if(!snapshot.sourceStatus.complete)throw new Error("Existing memory scan is incomplete.");const existing=[];for(const doc of snapshot.docs)existing.push({ref:`${scope}:${doc.relativePath}`,content:await fs.readFile(doc.filePath,"utf8")});existing.sort((a,b)=>a.ref.localeCompare(b.ref));return{version:digest(JSON.stringify(existing)),existing}}async importSection(section,batchId,signal,propose,assertCommit){const root=section.scope==="user"?getUserAutoMemoryRoot():getImportedProjectMemoryRoot(this.options.projectRoot,true);const scopeState=path.join(this.state,"scopes",digest(root));return this.locked(scopeState,async signal2=>{signal2.throwIfAborted();this.options.assertActive();if(await exists(root)&&(await fs.lstat(root)).isSymbolicLink())throw new ImportContextError("Memory import does not support a symlinked memory root. Use a non-symlink memory root before retrying; existing memories were not changed.");const ledgerPath=path.join(scopeState,"ledger.json");const ledger=await exists(ledgerPath)?await this.readState(ledgerPath):{};const key=section.id;let previous=ledger[key];const discardUnpublishedIntent=__name(async stage2=>{signal2.throwIfAborted();this.options.assertActive();delete ledger[key];await writeJson(ledgerPath,ledger);heldLocks.getStore()?.throwIfAborted();await fs.rm(stage2,{recursive:true,force:true})},"discardUnpublishedIntent");const outcome=__name((status,reason)=>({id:section.id,scope:section.scope,status,...reason?{reason}:{}}),"outcome");if(previous?.phase==="intent"){const stage2=path.join(scopeState,previous.stage);if(await exists(stage2)&&!await exists(path.join(root,"imported",key))&&(await this.snapshot(section.scope)).version!==previous.memoryVersion){await discardUnpublishedIntent(stage2);previous=void 0}}if(previous){const stage2=path.join(scopeState,previous.stage);const destination=path.join(root,"imported",key);if(previous.phase==="intent"&&await exists(stage2)&&!await exists(destination)){for(const output of previous.outputs){const file=path.join(stage2,path.basename(output.relativePath));if(digest(await fs.readFile(file,"utf8"))!==output.digest)throw new Error("Invalid staged import.")}signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage2,destination)}for(const output of previous.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously imported memory was edited or forgotten; it will not be restored.")}previous.phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);if(previous.batchId===batchId)return{...previous.outcome,id:section.id,scope:section.scope};return outcome(previous.outcome.status==="added"?"duplicate":previous.outcome.status,"This source has already been processed.")}const before=await this.snapshot(section.scope);const proposal=await propose(before,ledger,signal2);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version)return outcome("conflict","Existing memory changed during consolidation; preview and retry the source.");await assertCommit();if(proposal.decision==="conflict")return outcome("conflict",proposal.reason);if(proposal.decision!=="new"){const result2=outcome(proposal.decision==="skip"?"skipped":"duplicate",proposal.reason);ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const documents=[];for(const content of new Set(proposal.documents)){const parsed=parseAutoMemoryTopicDocument("import.md",content);if(!parsed)throw new Error("Invalid native memory.");if(section.scope==="user"&&parsed.type!=="user"&&parsed.type!=="feedback")throw new Error("Project knowledge cannot be imported into user memory.");const bodyDigest=digest(parsed.body.trim());for(const[sourceId,record]of Object.entries(ledger)){if(record.outputs.some(output=>output.bodyDigest===bodyDigest)){if(record.phase==="intent"&&!await exists(path.join(root,"imported",sourceId)))continue;for(const output of record.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously edited or forgotten imported knowledge cannot be recreated.")}}}if(before.existing.some(existing=>parseAutoMemoryTopicDocument("existing.md",existing.content)?.body.trim()===parsed.body.trim()))continue;if(!documents.some(existing=>parseAutoMemoryTopicDocument("new.md",existing)?.body.trim()===parsed.body.trim()))documents.push(content)}if(!documents.length){const result2=outcome("duplicate","All proposed knowledge already exists.");ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const stageName=`stage-${key}`;const stage=path.join(scopeState,stageName);if(await exists(stage)){await privateDirectory(stage,this.base);await fs.rm(stage,{recursive:true})}await privateDirectory(stage,this.base);const outputs=[];for(const[index,content]of documents.entries()){const filename=`${index}.md`;await fs.writeFile(path.join(stage,filename),content,{flag:"wx",mode:384});outputs.push({relativePath:`imported/${key}/${filename}`,digest:digest(content),bodyDigest:digest(parseAutoMemoryTopicDocument("import.md",content).body.trim())})}const result={...outcome("added",proposal.reason),refs:outputs.map(output=>`${section.scope}:${output.relativePath}`)};ledger[key]={batchId,phase:"intent",outputs,stage:stageName,memoryVersion:before.version,outcome:result};await writeJson(ledgerPath,ledger);signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version){await discardUnpublishedIntent(stage);return outcome("conflict","Existing memory changed before publication.")}await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage,path.join(root,"imported",key));ledger[key].phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);return result},signal)}};export{MemoryImportNotFoundError,MemoryImportService};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team