gerege-cli 0.26.5 → 0.26.7

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 (237) hide show
  1. package/README.md +8 -8
  2. package/chunks/{MaxSizedBox-VMVLMS4X.js → MaxSizedBox-LSNOJEKM.js} +1 -1
  3. package/chunks/{StandaloneSessionPicker-UNORCVYY.js → StandaloneSessionPicker-KSYGPMEV.js} +1 -1
  4. package/chunks/{acp-subagent-executor-623ZUTJT.js → acp-subagent-executor-NSW2MFUI.js} +1 -1
  5. package/chunks/{acpAgent-MTTDTK2C.js → acpAgent-3DTOHTDM.js} +3 -3
  6. package/chunks/{advisor-ANUGICJ5.js → advisor-7JGQPS7X.js} +1 -1
  7. package/chunks/{agent-GNCQDICJ.js → agent-PNKQJGDO.js} +1 -1
  8. package/chunks/{agent-headless-OPUXAXQM.js → agent-headless-7D33X7QQ.js} +1 -1
  9. package/chunks/{agent-host-client-K6GRPTFD.js → agent-host-client-3R2MAUVE.js} +1 -1
  10. package/chunks/{agent-host-connections-MF3YBZU2.js → agent-host-connections-2D7DECAE.js} +1 -1
  11. package/chunks/{anthropicContentGenerator-OK4PFE5Y.js → anthropicContentGenerator-MGTJJGEQ.js} +1 -1
  12. package/chunks/{autofix-pr-MABTGEHZ.js → autofix-pr-OIHHZSPQ.js} +1 -1
  13. package/chunks/{batch-V2NJT3M5.js → batch-6UDAMPAA.js} +1 -1
  14. package/chunks/{bridge-BJQ627CX.js → bridge-QXVXPNJ6.js} +1 -1
  15. package/chunks/{channel-settings-store-4JMCI4UR.js → channel-settings-store-P4W4R5SJ.js} +1 -1
  16. package/chunks/{chunk-ZN57TOVA.js → chunk-2DU2WMTL.js} +1 -1
  17. package/chunks/{chunk-ISGF3BVD.js → chunk-2J2BQ3PL.js} +2 -2
  18. package/chunks/{chunk-TQTIEK2W.js → chunk-2LMSDH6P.js} +1 -1
  19. package/chunks/{chunk-EIILQ6KT.js → chunk-3EZ5GCUT.js} +1 -1
  20. package/chunks/{chunk-UY2ET2AL.js → chunk-3ICJI5KW.js} +1 -1
  21. package/chunks/{chunk-VDRE7U3P.js → chunk-4A663FE6.js} +5 -5
  22. package/chunks/{chunk-2IGE2K5V.js → chunk-4AKTP4MM.js} +1 -1
  23. package/chunks/{chunk-NO26JN24.js → chunk-4LC4INFI.js} +1 -1
  24. package/chunks/{chunk-CKZRJP4F.js → chunk-4ME3BUJK.js} +1 -1
  25. package/chunks/{chunk-3XBJYUWP.js → chunk-4QOVM2LL.js} +1 -1
  26. package/chunks/{chunk-ZYTG6R7S.js → chunk-4VR4DUUD.js} +1 -1
  27. package/chunks/{chunk-DE53B2R7.js → chunk-4W27Z3OL.js} +1 -1
  28. package/chunks/{chunk-QOYRDEXR.js → chunk-53IB4U4E.js} +1 -1
  29. package/chunks/{chunk-CCOUFBOY.js → chunk-5R2JIZID.js} +1 -1
  30. package/chunks/{chunk-MPAR4JBP.js → chunk-5TWAP4OG.js} +1 -1
  31. package/chunks/{chunk-3NQESE5K.js → chunk-6JAXAFX7.js} +1 -1
  32. package/chunks/{chunk-POA4NX4N.js → chunk-6WV5RKYB.js} +1 -1
  33. package/chunks/{chunk-KN27BFXM.js → chunk-6YFNUVJR.js} +1 -1
  34. package/chunks/{chunk-2X3UF2CF.js → chunk-7HFFTOAD.js} +1 -1
  35. package/chunks/{chunk-KDYUZBZC.js → chunk-ATTJQLQV.js} +1 -1
  36. package/chunks/{chunk-USJFJZ23.js → chunk-BGELKSQ4.js} +1 -1
  37. package/chunks/{chunk-X4BFEDWU.js → chunk-BIPPD7W6.js} +1 -1
  38. package/chunks/{chunk-DEMXCA3K.js → chunk-BVV7UXES.js} +1 -1
  39. package/chunks/{chunk-2VCDJ6UF.js → chunk-BY46PCWY.js} +1 -1
  40. package/chunks/{chunk-CXGGC4NO.js → chunk-CDKBM72V.js} +1 -1
  41. package/chunks/{chunk-5WLKN3GD.js → chunk-CK3OKTTL.js} +1 -1
  42. package/chunks/{chunk-FHBGTZ4K.js → chunk-DEJ47KJE.js} +1 -1
  43. package/chunks/{chunk-DTTC4ZKY.js → chunk-DQQN2HOP.js} +1 -1
  44. package/chunks/{chunk-PN62SUYK.js → chunk-DTX2OVQW.js} +1 -1
  45. package/chunks/{chunk-IBYFSHBB.js → chunk-DVUKYOCJ.js} +1 -1
  46. package/chunks/{chunk-Q5E5SOY2.js → chunk-E3KWSRJN.js} +1 -1
  47. package/chunks/{chunk-IDUGQMTP.js → chunk-EEPNACXJ.js} +1 -1
  48. package/chunks/{chunk-E5YRAQXM.js → chunk-EKRUF347.js} +1 -1
  49. package/chunks/{chunk-HSYBIGMS.js → chunk-F5SLLEJY.js} +1 -1
  50. package/chunks/{chunk-5ZQWQ3RK.js → chunk-F7622ZRQ.js} +1 -1
  51. package/chunks/{chunk-KKBOCRPF.js → chunk-FKUDVIME.js} +1 -1
  52. package/chunks/{chunk-62NLMVVT.js → chunk-FRVXSKL4.js} +1 -1
  53. package/chunks/{chunk-FIM7MM25.js → chunk-FTF2NFLB.js} +1 -1
  54. package/chunks/{chunk-OHXQYU6S.js → chunk-G4MWPXNY.js} +1 -1
  55. package/chunks/{chunk-SELRSZFK.js → chunk-GA35LMSX.js} +1 -1
  56. package/chunks/{chunk-SMYBY353.js → chunk-H34KVVI4.js} +1 -1
  57. package/chunks/{chunk-NGOIJH7K.js → chunk-H5EXNXGW.js} +1 -1
  58. package/chunks/{chunk-UBXLQ6TP.js → chunk-HJLRKM3W.js} +1 -1
  59. package/chunks/{chunk-CAPG7UVH.js → chunk-HVP4UF2Q.js} +1 -1
  60. package/chunks/{chunk-H57IX45A.js → chunk-HXTYFGSQ.js} +1 -1
  61. package/chunks/{chunk-55RVKT4O.js → chunk-IIHUDJX7.js} +1 -1
  62. package/chunks/{chunk-XFLLE2J3.js → chunk-IQMKQKKD.js} +2 -2
  63. package/chunks/{chunk-SQQORHMS.js → chunk-ISQMHOCC.js} +1 -1
  64. package/chunks/{chunk-YLAI26PX.js → chunk-IY7M5HKF.js} +1 -1
  65. package/chunks/{chunk-FDUXQAGW.js → chunk-IZXHCHJD.js} +1 -1
  66. package/chunks/{chunk-ZOBX6C7E.js → chunk-JHC22BZH.js} +1 -1
  67. package/chunks/{chunk-26ISBUM7.js → chunk-K7GN4CMV.js} +6 -6
  68. package/chunks/{chunk-4GC5HJZO.js → chunk-L7LO3YRT.js} +1 -1
  69. package/chunks/{chunk-ZSVSRF4C.js → chunk-LT3J74BZ.js} +1 -1
  70. package/chunks/{chunk-2PY7R7GG.js → chunk-LY4XTBL4.js} +1 -1
  71. package/chunks/{chunk-7IERHQ63.js → chunk-LYFRGP42.js} +1 -1
  72. package/chunks/{chunk-FPZPCZFS.js → chunk-MDCA4I63.js} +1 -1
  73. package/chunks/{chunk-2LLPGSUK.js → chunk-MS2XCBPP.js} +1 -1
  74. package/chunks/{chunk-3Y6LSWEW.js → chunk-MXZXQUVP.js} +1 -1
  75. package/chunks/{chunk-IH2PFVWO.js → chunk-N4ZQC5HB.js} +1 -1
  76. package/chunks/{chunk-MTW3A3KT.js → chunk-N6EFYQ7M.js} +1 -1
  77. package/chunks/{chunk-AQWHCRKY.js → chunk-NHPKD7LY.js} +1 -1
  78. package/chunks/{chunk-ABJGFEES.js → chunk-NO7VTKRL.js} +1 -1
  79. package/chunks/{chunk-CNFA5UUM.js → chunk-NPAENNRO.js} +1 -1
  80. package/chunks/{chunk-IA4K4PGK.js → chunk-NYBYDW6R.js} +1 -1
  81. package/chunks/{chunk-FNB3DPQZ.js → chunk-O3TUZQP4.js} +1 -1
  82. package/chunks/{chunk-RVJJFDF3.js → chunk-OZFZBGZG.js} +1 -1
  83. package/chunks/{chunk-B6D3KTUK.js → chunk-P2MZZMCS.js} +1 -1
  84. package/chunks/{chunk-GSOBASYW.js → chunk-PMBI46K4.js} +1 -1
  85. package/chunks/{chunk-WI4UMN3Q.js → chunk-Q5RRVBTY.js} +1 -1
  86. package/chunks/{chunk-5UZT4SXG.js → chunk-QHYSRPQR.js} +1 -1
  87. package/chunks/{chunk-2NOMOJWE.js → chunk-QONPET6Y.js} +2 -2
  88. package/chunks/{chunk-MOPJNP5I.js → chunk-QSPXKBUX.js} +1 -1
  89. package/chunks/{chunk-C56YJIEI.js → chunk-QTKPC24L.js} +1 -1
  90. package/chunks/{chunk-6X73W4TL.js → chunk-QTVSPQZQ.js} +1 -1
  91. package/chunks/{chunk-ADZI3OFT.js → chunk-QVHDM6N7.js} +1 -1
  92. package/chunks/{chunk-NVSKOSFG.js → chunk-RT6J7PV4.js} +1 -1
  93. package/chunks/{chunk-7MTBINFX.js → chunk-RULGA7WE.js} +2 -2
  94. package/chunks/{chunk-AMTFJVDD.js → chunk-SAVYMUU3.js} +1 -1
  95. package/chunks/{chunk-Z5XENA4A.js → chunk-T3CQ72HC.js} +8 -7
  96. package/chunks/{chunk-OPYGNTZP.js → chunk-U5YOAOU3.js} +1 -1
  97. package/chunks/{chunk-HFV6CQWE.js → chunk-ULLW2AYD.js} +1 -1
  98. package/chunks/{chunk-KGJ47CI5.js → chunk-UM5KBBYP.js} +1 -1
  99. package/chunks/{chunk-F26LTWDZ.js → chunk-UVMLWDRU.js} +1 -1
  100. package/chunks/{chunk-BRPJ5EHA.js → chunk-VK7LOUOJ.js} +1 -1
  101. package/chunks/{chunk-4EQWJTJR.js → chunk-VUNHJ74J.js} +1 -1
  102. package/chunks/{chunk-WB34KMOT.js → chunk-W2CV36HT.js} +1 -1
  103. package/chunks/{chunk-ADTFKUH2.js → chunk-WCI33URB.js} +1 -1
  104. package/chunks/{chunk-4TYTJQWR.js → chunk-WEPC42YR.js} +1 -1
  105. package/chunks/{chunk-YGHM5CDT.js → chunk-WF7Q3ZSQ.js} +1 -1
  106. package/chunks/{chunk-UJYOILZR.js → chunk-WK666FGZ.js} +3 -3
  107. package/chunks/{chunk-3WQPUP5U.js → chunk-WMLYHZZX.js} +1 -1
  108. package/chunks/{chunk-OCBJCZC2.js → chunk-WSI4G7XC.js} +1 -1
  109. package/chunks/{chunk-Q6QS5JTK.js → chunk-WXK7Z45R.js} +1 -1
  110. package/chunks/{chunk-6NI33TVK.js → chunk-X2TY7VTY.js} +1 -1
  111. package/chunks/{chunk-BBOJUFMW.js → chunk-YWK3E4WJ.js} +1 -1
  112. package/chunks/{chunk-FNXO5KWB.js → chunk-YY4GWNTU.js} +2 -2
  113. package/chunks/{chunk-FLJLUMQF.js → chunk-ZFOEVHWG.js} +1 -1
  114. package/chunks/{codex-subagent-executor-EK3A2WBH.js → codex-subagent-executor-GPTKVP7H.js} +1 -1
  115. package/chunks/{config-utils-DLOK7OLM.js → config-utils-6B5FHBSF.js} +1 -1
  116. package/chunks/{contextCommand-AVCUCHQC.js → contextCommand-FGRDE3GA.js} +1 -1
  117. package/chunks/{core-runtime-QSS4ZTG6.js → core-runtime-OFEHSKDB.js} +1 -1
  118. package/chunks/{create-sub-session-PNF7QDKC.js → create-sub-session-D2KEWVHQ.js} +1 -1
  119. package/chunks/{cron-create-C6JOFIU4.js → cron-create-RFGGKTL7.js} +1 -1
  120. package/chunks/{daemon-git-worktree-guard-5XZAZ7D2.js → daemon-git-worktree-guard-AV752IOZ.js} +1 -1
  121. package/chunks/{daemon-status-provider-MRNELSNJ.js → daemon-status-provider-GHQBRDMC.js} +1 -1
  122. package/chunks/{daemon-trust-policy-26CMW3WY.js → daemon-trust-policy-24ENJNTQ.js} +1 -1
  123. package/chunks/{daemon-trust-policy-monitor-3DWO6NQY.js → daemon-trust-policy-monitor-NMSQAGWV.js} +1 -1
  124. package/chunks/{deferred-core-runtime-DEC3N46T.js → deferred-core-runtime-5BAMFFOI.js} +1 -1
  125. package/chunks/{edit-3HMQPCHN.js → edit-XCECLEH3.js} +1 -1
  126. package/chunks/{enterPlanMode-QHJF4JXZ.js → enterPlanMode-SEN2PMRM.js} +1 -1
  127. package/chunks/{environment-NGIBJWOT.js → environment-CCPQJYKS.js} +1 -1
  128. package/chunks/{errors-MSTGCVGJ.js → errors-Y6HHUTGK.js} +1 -1
  129. package/chunks/{execution-tool-VR4TGOI4.js → execution-tool-HADWGMIG.js} +1 -1
  130. package/chunks/{execution-worker-EJH7HIE2.js → execution-worker-GZS7WOQL.js} +1 -1
  131. package/chunks/{exitPlanMode-P25OHQJ6.js → exitPlanMode-76B5HDLT.js} +1 -1
  132. package/chunks/{fast-path-II433ZDP.js → fast-path-OEV7LQYV.js} +1 -1
  133. package/chunks/{glob-4Q6DCT3F.js → glob-NLWCQRMS.js} +1 -1
  134. package/chunks/{goal-tools-FFMAJW6V.js → goal-tools-43XV33BT.js} +1 -1
  135. package/chunks/{handleAutoUpdate-QNM26NZK.js → handleAutoUpdate-JDQWGSSP.js} +1 -1
  136. package/chunks/{i18n-L5URVOBB.js → i18n-JW6BVEGF.js} +1 -1
  137. package/chunks/{initializer-NQ2NECYP.js → initializer-UT6JLZ3O.js} +1 -1
  138. package/chunks/{installationInfo-BCTXASUM.js → installationInfo-LKWDV3S2.js} +1 -1
  139. package/chunks/{interactive-mod-session-PPTBI37E.js → interactive-mod-session-2KWKYVPC.js} +1 -1
  140. package/chunks/{list-7TE5TUZJ.js → list-BKINK3S2.js} +1 -1
  141. package/chunks/{llm-BWWKUBBZ.js → llm-3RWXAVM2.js} +4 -4
  142. package/chunks/{llm-content-generator-QOTGPBYC.js → llm-content-generator-MDRBSH73.js} +1 -1
  143. package/chunks/{loadedSettingsAdapter-THAGI5M2.js → loadedSettingsAdapter-WWJUKWUN.js} +1 -1
  144. package/chunks/{local-7BTAGV4J.js → local-TT4FLCTR.js} +1 -1
  145. package/chunks/{local-execution-environment-S3OR4KSC.js → local-execution-environment-OBA6VWYL.js} +1 -1
  146. package/chunks/{loggingContentGenerator-AXJ5E5RS.js → loggingContentGenerator-CK7IKYQH.js} +1 -1
  147. package/chunks/{loop-wakeup-AJTLMLRX.js → loop-wakeup-4MSRX3DY.js} +1 -1
  148. package/chunks/{manage-memory-JHTUVMDJ.js → manage-memory-PX5PZJKZ.js} +1 -1
  149. package/chunks/{managed-execution-engine-U6GNJ4U4.js → managed-execution-engine-WMAUR3ZK.js} +1 -1
  150. package/chunks/{managed-local-serve-P4ZXVRBU.js → managed-local-serve-X7REHGB4.js} +1 -1
  151. package/chunks/{managed-npm-update-UDUILNR5.js → managed-npm-update-6HUVAJH7.js} +1 -1
  152. package/chunks/{managed-runtime-attestation-worker-P34ZBNRG.js → managed-runtime-attestation-worker-F4AT53M5.js} +1 -1
  153. package/chunks/{managed-runtime-bootstrap-CLMYNPH5.js → managed-runtime-bootstrap-3BP5JRJX.js} +1 -1
  154. package/chunks/{managed-runtime-session-worker-7H7AZJBV.js → managed-runtime-session-worker-2PO7J5UK.js} +1 -1
  155. package/chunks/{managed-runtime-ssh-worker-5KEMC7FD.js → managed-runtime-ssh-worker-4N7EMRSV.js} +1 -1
  156. package/chunks/{managed-session-authority-CFUZ45HT.js → managed-session-authority-MYOYTUM2.js} +1 -1
  157. package/chunks/{mcp-YMG4RVMC.js → mcp-5OTEMZ7P.js} +1 -1
  158. package/chunks/{memory-7STURUXK.js → memory-TNW7RSAV.js} +1 -1
  159. package/chunks/mn-JMS6SWTO.js +8 -0
  160. package/chunks/{model-call-collection-WBWTO3EG.js → model-call-collection-KNTWFZQS.js} +1 -1
  161. package/chunks/{model-configuration-6KCZZSZD.js → model-configuration-U5C5P5UQ.js} +1 -1
  162. package/chunks/{modelConfigUtils-Z2EKFSPN.js → modelConfigUtils-R4KFI2WK.js} +1 -1
  163. package/chunks/{monitor-U5E33JO6.js → monitor-RD2PFK42.js} +1 -1
  164. package/chunks/{nonInteractiveCli-BVCL5I5R.js → nonInteractiveCli-QQ72HZSH.js} +1 -1
  165. package/chunks/{nonInteractiveToolExecutor-B4EUOMYF.js → nonInteractiveToolExecutor-QPQYR6IS.js} +1 -1
  166. package/chunks/{notebook-edit-MXKD5J2C.js → notebook-edit-YLRN3UZT.js} +1 -1
  167. package/chunks/{omni-I5YECZBW.js → omni-CUJ52EW5.js} +1 -1
  168. package/chunks/{openaiContentGenerator-Q5SINFJJ.js → openaiContentGenerator-6B5MAU54.js} +1 -1
  169. package/chunks/{openaiResponsesContentGenerator-R3XCZLZY.js → openaiResponsesContentGenerator-I245I3R7.js} +1 -1
  170. package/chunks/{pidfile-UOGUNUTK.js → pidfile-P2HIGAUA.js} +1 -1
  171. package/chunks/{processUtils-QGQGZHBA.js → processUtils-JSKN5UGS.js} +1 -1
  172. package/chunks/{prompt-terminal-ledger-L57JMVSR.js → prompt-terminal-ledger-F5TSXVGU.js} +1 -1
  173. package/chunks/{qwenContentGenerator-UKZ237LC.js → qwenContentGenerator-IEDZONWG.js} +1 -1
  174. package/chunks/{reactive-degrade-3OM3HWVA.js → reactive-degrade-FYZBJCF6.js} +1 -1
  175. package/chunks/{read-file-63ZLWMOW.js → read-file-VNZNSD6X.js} +1 -1
  176. package/chunks/{resumeHistoryUtils-R5YQS4YQ.js → resumeHistoryUtils-IDPE6N2N.js} +1 -1
  177. package/chunks/{review-AT6OWVDO.js → review-TBJRZWTD.js} +1 -1
  178. package/chunks/{ripGrep-7KBZGTPV.js → ripGrep-4W5B5FOE.js} +1 -1
  179. package/chunks/{run-qwen-serve-CLBG7W6F.js → run-qwen-serve-44X262G5.js} +1 -1
  180. package/chunks/{runtime-R3QIGB7U.js → runtime-6H6LKD73.js} +1 -1
  181. package/chunks/{sandboxConfig-PM3ZRQYV.js → sandboxConfig-SQXDRGVN.js} +1 -1
  182. package/chunks/{scheduled-tasks-PUMNN5XV.js → scheduled-tasks-62IZKHJG.js} +1 -1
  183. package/chunks/{scheduler-KTPM226B.js → scheduler-QUCXJYRL.js} +1 -1
  184. package/chunks/{search-memory-7I5MGDNV.js → search-memory-TC2Z34QN.js} +1 -1
  185. package/chunks/{send-message-J526AEBI.js → send-message-TFZX7KI7.js} +1 -1
  186. package/chunks/{serve-KLTMPK4W.js → serve-WSICDFGG.js} +1 -1
  187. package/chunks/{server-VLRNY6KG.js → server-GYYVTNGY.js} +3 -3
  188. package/chunks/{session-2EB57NXY.js → session-KF3O23ZJ.js} +1 -1
  189. package/chunks/{session-attachments-root-I7TESMWL.js → session-attachments-root-7HFUSONH.js} +1 -1
  190. package/chunks/{session-execution-engine-selector-5FAMSPSO.js → session-execution-engine-selector-NVILT6BR.js} +1 -1
  191. package/chunks/{session-pr-refresh-JCPVQPNJ.js → session-pr-refresh-3KDFTDEV.js} +1 -1
  192. package/chunks/{sessionService-YRW2IFPR.js → sessionService-XRTFLPDW.js} +1 -1
  193. package/chunks/{settings-KO2Q47JP.js → settings-QPPK6WXE.js} +1 -1
  194. package/chunks/{shell-OLZVNTQZ.js → shell-WYQDZWL7.js} +1 -1
  195. package/chunks/{skill-XW2AQS7M.js → skill-FYPT6AU7.js} +1 -1
  196. package/chunks/{skill-settings-TKAVQ4XP.js → skill-settings-OGFI5KZF.js} +1 -1
  197. package/chunks/{spawnChannel-MBGCTK2J.js → spawnChannel-ANOOVPG7.js} +1 -1
  198. package/chunks/{standalone-update-A3YLLIAN.js → standalone-update-45WTDY4E.js} +1 -1
  199. package/chunks/{start-opentui-ui-G5ROAR4V.js → start-opentui-ui-TL5WK33V.js} +1 -1
  200. package/chunks/{startInteractiveUI-PZQR4U53.js → startInteractiveUI-N2IREVBM.js} +1 -1
  201. package/chunks/{team-create-S5ZY2UMF.js → team-create-R77PRZ5U.js} +1 -1
  202. package/chunks/{team-plan-approval-KX6RXEST.js → team-plan-approval-6DCRKB5I.js} +1 -1
  203. package/chunks/{terminal-image-renderer-SCJREXE6.js → terminal-image-renderer-TB7EX2WW.js} +1 -1
  204. package/chunks/{theme-manager-DZSM4EBR.js → theme-manager-RQDXJGVR.js} +1 -1
  205. package/chunks/{tool-call-UK56SWCT.js → tool-call-LVB4NCDT.js} +1 -1
  206. package/chunks/{tool-result-media-JLLSLGFL.js → tool-result-media-LRBB2KS6.js} +1 -1
  207. package/chunks/{tool-search-OWPFLVV5.js → tool-search-OG73QAQZ.js} +1 -1
  208. package/chunks/{total-session-admission-NQU4ACKH.js → total-session-admission-A4CUF6AD.js} +1 -1
  209. package/chunks/{trustedFolders-N7GXFYSF.js → trustedFolders-LSGOYTU2.js} +1 -1
  210. package/chunks/{update-relaunch-5SPXXHM2.js → update-relaunch-OGC6BZO7.js} +1 -1
  211. package/chunks/{updateCheck-VXUIX2XG.js → updateCheck-7J3GXTER.js} +1 -1
  212. package/chunks/{upload-config-OWLL4SRQ.js → upload-config-ML5XEJIF.js} +1 -1
  213. package/chunks/{useAutoAcceptIndicator-OUYRR56F.js → useAutoAcceptIndicator-6DH6GQ2X.js} +1 -1
  214. package/chunks/{validateNonInterActiveAuth-PSVJO5HK.js → validateNonInterActiveAuth-KJDAGZCM.js} +1 -1
  215. package/chunks/{version-C26S7UAW.js → version-7JN2YXL2.js} +1 -1
  216. package/chunks/{web-fetch-AYOYV7R4.js → web-fetch-42ZR4FEZ.js} +1 -1
  217. package/chunks/{web-search-DAREKD3Z.js → web-search-74NLPMZJ.js} +1 -1
  218. package/chunks/{workflow-WBGPKVO6.js → workflow-WNPHX42I.js} +1 -1
  219. package/chunks/{workflow-ancestor-trust-GEEB53TB.js → workflow-ancestor-trust-HGF6G7LQ.js} +1 -1
  220. package/chunks/{workspace-agents-IMAQME4W.js → workspace-agents-3YFBFAK3.js} +1 -1
  221. package/chunks/{workspace-providers-status-VALHVEU2.js → workspace-providers-status-EPJI6KRV.js} +1 -1
  222. package/chunks/{workspace-recovery-worker-AIAVRDGU.js → workspace-recovery-worker-T3FK5YOD.js} +1 -1
  223. package/chunks/{workspace-registration-store-FXEGZG3L.js → workspace-registration-store-VEXYBDMA.js} +1 -1
  224. package/chunks/{workspace-registry-GYFFHWCD.js → workspace-registry-NRZYTP2X.js} +1 -1
  225. package/chunks/{workspace-runtime-coordinator-VZ462TLU.js → workspace-runtime-coordinator-USNSTP2V.js} +1 -1
  226. package/chunks/{workspace-service-5DIZM4IZ.js → workspace-service-USATWO56.js} +1 -1
  227. package/chunks/{workspace-skills-status-DOOBVL5N.js → workspace-skills-status-M5JTSFDL.js} +1 -1
  228. package/chunks/{workspace-trust-reconciler-LOICVUVW.js → workspace-trust-reconciler-ZUZ2O5WC.js} +1 -1
  229. package/chunks/{write-file-EJNMAHQD.js → write-file-UMJVKE4S.js} +1 -1
  230. package/chunks/{zoom-image-S3OARMYP.js → zoom-image-76XYHQ3Z.js} +1 -1
  231. package/cli.js +2 -2
  232. package/execution-worker.js +1 -1
  233. package/export-transcript-document.js +1 -1
  234. package/gerege.mjs +64 -15
  235. package/locales/mn.js +2702 -3774
  236. package/package.json +3 -3
  237. package/chunks/mn-YH2OTBWJ.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{functionResponsePartsToString}from"./chunk-UJYOILZR.js";import{observeHeadlessToolResultProjection,observeHeadlessToolResultWire}from"./chunk-26ISBUM7.js";import{projectJsonStringToByteBudget}from"./chunk-WQUA4G2X.js";import{createNotStartedToolErrorResponse,parseAndFormatApiError,toolResultBoundaryArtifact}from"./chunk-Z5XENA4A.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{formatVisionBridgeNoticeDisplay,isVisionBridgeNoticeDisplay}from"./chunk-ZWPSBU7K.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";init_esbuild_shims();import{randomUUID}from"node:crypto";init_esbuild_shims();var HEADLESS_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var HEADLESS_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for Headless transport ...]\n";function projectHeadlessToolResultContent(value){return projectJsonStringToByteBudget(value,HEADLESS_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET,HEADLESS_TOOL_RESULT_TEXT_TRUNCATION_MARKER)}__name(projectHeadlessToolResultContent,"projectHeadlessToolResultContent");var BaseJsonOutputAdapter=class{static{__name(this,"BaseJsonOutputAdapter")}config;mainAgentMessageState;subagentMessageStates=new Map;lastAssistantMessage=null;permissionDenials=[];constructor(config){this.config=config;this.mainAgentMessageState=this.createMessageState()}createMessageState(){return{messageId:null,blocks:[],openBlocks:new Set,usage:this.createUsage(),messageStarted:false,finalized:false,currentBlockType:null}}getMessageState(parentToolUseId){if(parentToolUseId===null){return this.mainAgentMessageState}let state=this.subagentMessageStates.get(parentToolUseId);if(!state){state=this.createMessageState();this.subagentMessageStates.set(parentToolUseId,state)}return state}createUsage(metadata){const usage={input_tokens:0,output_tokens:0};if(!metadata){return usage}if(typeof metadata.promptTokenCount==="number"){usage.input_tokens=metadata.promptTokenCount}if(typeof metadata.candidatesTokenCount==="number"){usage.output_tokens=metadata.candidatesTokenCount}if(typeof metadata.cachedContentTokenCount==="number"){usage.cache_read_input_tokens=metadata.cachedContentTokenCount}if(typeof metadata.totalTokenCount==="number"){usage.total_tokens=metadata.totalTokenCount}return usage}buildMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);if(!state.messageId){throw new Error("Message not started")}if(state.blocks.length>0){const blockTypes=new Set(state.blocks.map(block=>block.type));if(blockTypes.size>1){throw new Error(`Assistant message must contain only one type of ContentBlock, found: ${Array.from(blockTypes).join(", ")}`)}}const stopReason=state.blocks.length>0&&state.blocks.every(block=>block.type==="tool_use")?"tool_use":null;return{type:"assistant",uuid:state.messageId,session_id:this.config.getSessionId(),parent_tool_use_id:parentToolUseId,message:{id:state.messageId,type:"message",role:"assistant",model:this.config.getModel(),content:state.blocks,stop_reason:stopReason,usage:state.usage}}}finalizePendingBlocks(state,parentToolUseId){const actualParentToolUseId=parentToolUseId??null;const lastBlock=state.blocks[state.blocks.length-1];if(!lastBlock){return}const index=state.blocks.length-1;if(!state.openBlocks.has(index)){return}if(lastBlock.type==="text"||lastBlock.type==="thinking"){this.onBlockClosed(state,index,actualParentToolUseId);this.closeBlock(state,index)}}openBlock(state,index,_block){state.openBlocks.add(index)}closeBlock(state,index){if(!state.openBlocks.has(index)){return}state.openBlocks.delete(index)}ensureBlockTypeConsistency(state,targetType,parentToolUseId){if(state.currentBlockType===targetType){return}if(state.currentBlockType===null){state.currentBlockType=targetType;return}this.finalizeAssistantMessageInternal(state,parentToolUseId);this.startAssistantMessageInternal(state);state.currentBlockType=targetType}startAssistantMessageInternal(state){state.messageId=randomUUID();state.blocks=[];state.openBlocks=new Set;state.usage=this.createUsage();state.messageStarted=false;state.finalized=false;state.currentBlockType=null}finalizeAssistantMessageInternal(state,parentToolUseId){if(state.finalized){return this.buildMessage(parentToolUseId)}state.finalized=true;this.finalizePendingBlocks(state,parentToolUseId);const orderedOpenBlocks=Array.from(state.openBlocks).sort((a,b)=>a-b);for(const index of orderedOpenBlocks){this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}const message=this.buildMessage(parentToolUseId);if(state.messageStarted){this.emitMessageImpl(message)}return message}emitControlMessageImpl(_message){}onTextBlockCreated(_state,_index,_block,_parentToolUseId){}onTextAppended(_state,_index,_fragment,_parentToolUseId){}onThinkingBlockCreated(_state,_index,_block,_parentToolUseId){}onThinkingAppended(_state,_index,_fragment,_parentToolUseId){}onToolUseBlockCreated(_state,_index,_block,_parentToolUseId){}onToolUseInputSet(_state,_index,_input,_parentToolUseId){}onBlockClosed(_state,_index,_parentToolUseId){}onEnsureMessageStarted(_state,_parentToolUseId){}getSessionId(){return this.config.getSessionId()}getModel(){return this.config.getModel()}startAssistantMessage(){this.startAssistantMessageInternal(this.mainAgentMessageState)}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const state=this.mainAgentMessageState;const retainedBlocks=[];const retainedOpenBlocks=new Set;for(const[index,block]of state.blocks.entries()){if(block.type==="tool_use"&&discardedIds.has(block.id)){continue}const retainedIndex=retainedBlocks.length;retainedBlocks.push(block);if(state.openBlocks.has(index)){retainedOpenBlocks.add(retainedIndex)}}state.blocks=retainedBlocks;state.openBlocks=retainedOpenBlocks;state.currentBlockType=retainedBlocks.at(-1)?.type??null;state.messageStarted=retainedBlocks.length>0}return}this.startAssistantMessageInternal(this.mainAgentMessageState)}emitDiscardedAttemptToolResults(discardedToolCalls){const message="Skipped because the provider attempt was retried before execution.";for(const request of discardedToolCalls){this.emitToolResult(request,createNotStartedToolErrorResponse(request,message))}}processEvent(event){const state=this.mainAgentMessageState;if(state.finalized){return}switch(event.type){case"content":this.appendText(state,event.value,null);break;case"citation":if(typeof event.value==="string"){this.appendText(state,`
3
+ import{functionResponsePartsToString}from"./chunk-WK666FGZ.js";import{observeHeadlessToolResultProjection,observeHeadlessToolResultWire}from"./chunk-K7GN4CMV.js";import{projectJsonStringToByteBudget}from"./chunk-WQUA4G2X.js";import{createNotStartedToolErrorResponse,parseAndFormatApiError,toolResultBoundaryArtifact}from"./chunk-T3CQ72HC.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{formatVisionBridgeNoticeDisplay,isVisionBridgeNoticeDisplay}from"./chunk-ZWPSBU7K.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";init_esbuild_shims();import{randomUUID}from"node:crypto";init_esbuild_shims();var HEADLESS_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var HEADLESS_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for Headless transport ...]\n";function projectHeadlessToolResultContent(value){return projectJsonStringToByteBudget(value,HEADLESS_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET,HEADLESS_TOOL_RESULT_TEXT_TRUNCATION_MARKER)}__name(projectHeadlessToolResultContent,"projectHeadlessToolResultContent");var BaseJsonOutputAdapter=class{static{__name(this,"BaseJsonOutputAdapter")}config;mainAgentMessageState;subagentMessageStates=new Map;lastAssistantMessage=null;permissionDenials=[];constructor(config){this.config=config;this.mainAgentMessageState=this.createMessageState()}createMessageState(){return{messageId:null,blocks:[],openBlocks:new Set,usage:this.createUsage(),messageStarted:false,finalized:false,currentBlockType:null}}getMessageState(parentToolUseId){if(parentToolUseId===null){return this.mainAgentMessageState}let state=this.subagentMessageStates.get(parentToolUseId);if(!state){state=this.createMessageState();this.subagentMessageStates.set(parentToolUseId,state)}return state}createUsage(metadata){const usage={input_tokens:0,output_tokens:0};if(!metadata){return usage}if(typeof metadata.promptTokenCount==="number"){usage.input_tokens=metadata.promptTokenCount}if(typeof metadata.candidatesTokenCount==="number"){usage.output_tokens=metadata.candidatesTokenCount}if(typeof metadata.cachedContentTokenCount==="number"){usage.cache_read_input_tokens=metadata.cachedContentTokenCount}if(typeof metadata.totalTokenCount==="number"){usage.total_tokens=metadata.totalTokenCount}return usage}buildMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);if(!state.messageId){throw new Error("Message not started")}if(state.blocks.length>0){const blockTypes=new Set(state.blocks.map(block=>block.type));if(blockTypes.size>1){throw new Error(`Assistant message must contain only one type of ContentBlock, found: ${Array.from(blockTypes).join(", ")}`)}}const stopReason=state.blocks.length>0&&state.blocks.every(block=>block.type==="tool_use")?"tool_use":null;return{type:"assistant",uuid:state.messageId,session_id:this.config.getSessionId(),parent_tool_use_id:parentToolUseId,message:{id:state.messageId,type:"message",role:"assistant",model:this.config.getModel(),content:state.blocks,stop_reason:stopReason,usage:state.usage}}}finalizePendingBlocks(state,parentToolUseId){const actualParentToolUseId=parentToolUseId??null;const lastBlock=state.blocks[state.blocks.length-1];if(!lastBlock){return}const index=state.blocks.length-1;if(!state.openBlocks.has(index)){return}if(lastBlock.type==="text"||lastBlock.type==="thinking"){this.onBlockClosed(state,index,actualParentToolUseId);this.closeBlock(state,index)}}openBlock(state,index,_block){state.openBlocks.add(index)}closeBlock(state,index){if(!state.openBlocks.has(index)){return}state.openBlocks.delete(index)}ensureBlockTypeConsistency(state,targetType,parentToolUseId){if(state.currentBlockType===targetType){return}if(state.currentBlockType===null){state.currentBlockType=targetType;return}this.finalizeAssistantMessageInternal(state,parentToolUseId);this.startAssistantMessageInternal(state);state.currentBlockType=targetType}startAssistantMessageInternal(state){state.messageId=randomUUID();state.blocks=[];state.openBlocks=new Set;state.usage=this.createUsage();state.messageStarted=false;state.finalized=false;state.currentBlockType=null}finalizeAssistantMessageInternal(state,parentToolUseId){if(state.finalized){return this.buildMessage(parentToolUseId)}state.finalized=true;this.finalizePendingBlocks(state,parentToolUseId);const orderedOpenBlocks=Array.from(state.openBlocks).sort((a,b)=>a-b);for(const index of orderedOpenBlocks){this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}const message=this.buildMessage(parentToolUseId);if(state.messageStarted){this.emitMessageImpl(message)}return message}emitControlMessageImpl(_message){}onTextBlockCreated(_state,_index,_block,_parentToolUseId){}onTextAppended(_state,_index,_fragment,_parentToolUseId){}onThinkingBlockCreated(_state,_index,_block,_parentToolUseId){}onThinkingAppended(_state,_index,_fragment,_parentToolUseId){}onToolUseBlockCreated(_state,_index,_block,_parentToolUseId){}onToolUseInputSet(_state,_index,_input,_parentToolUseId){}onBlockClosed(_state,_index,_parentToolUseId){}onEnsureMessageStarted(_state,_parentToolUseId){}getSessionId(){return this.config.getSessionId()}getModel(){return this.config.getModel()}startAssistantMessage(){this.startAssistantMessageInternal(this.mainAgentMessageState)}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const state=this.mainAgentMessageState;const retainedBlocks=[];const retainedOpenBlocks=new Set;for(const[index,block]of state.blocks.entries()){if(block.type==="tool_use"&&discardedIds.has(block.id)){continue}const retainedIndex=retainedBlocks.length;retainedBlocks.push(block);if(state.openBlocks.has(index)){retainedOpenBlocks.add(retainedIndex)}}state.blocks=retainedBlocks;state.openBlocks=retainedOpenBlocks;state.currentBlockType=retainedBlocks.at(-1)?.type??null;state.messageStarted=retainedBlocks.length>0}return}this.startAssistantMessageInternal(this.mainAgentMessageState)}emitDiscardedAttemptToolResults(discardedToolCalls){const message="Skipped because the provider attempt was retried before execution.";for(const request of discardedToolCalls){this.emitToolResult(request,createNotStartedToolErrorResponse(request,message))}}processEvent(event){const state=this.mainAgentMessageState;if(state.finalized){return}switch(event.type){case"content":this.appendText(state,event.value,null);break;case"citation":if(typeof event.value==="string"){this.appendText(state,`
4
4
  ${event.value}`,null)}break;case"thought":this.appendThinking(state,event.value.subject,event.value.description,null);break;case"tool_call_request":this.appendToolUse(state,event.value,null);break;case"finished":if(event.value?.usageMetadata){state.usage=this.createUsage(event.value.usageMetadata)}this.finalizePendingBlocks(state,null);break;case"error":{const errorText=parseAndFormatApiError(event.value.error,this.config.getContentGeneratorConfig()?.authType);this.appendText(state,errorText,null);break}case"model_fallback":this.emitSystemMessage("model_fallback",{fromModel:event.fromModel,toModel:event.toModel,statusCode:event.statusCode,fallbackIndex:event.fallbackIndex});break;default:break}}startSubagentAssistantMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);this.startAssistantMessageInternal(state)}finalizeSubagentAssistantMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);return this.finalizeAssistantMessageInternal(state,parentToolUseId)}emitSubagentErrorResult(errorMessage,numTurns,parentToolUseId){const state=this.getMessageState(parentToolUseId);if(state.messageStarted&&!state.finalized){this.finalizeSubagentAssistantMessage(parentToolUseId)}const errorResult=this.buildSubagentErrorResult(errorMessage,numTurns);this.emitMessageImpl(errorResult)}processSubagentToolCall(toolCall,parentToolUseId){const state=this.getMessageState(parentToolUseId);const hasText=state.blocks.some(b=>b.type==="text")||state.currentBlockType==="text"&&state.blocks.length>0;if(hasText){this.finalizeSubagentAssistantMessage(parentToolUseId);this.startSubagentAssistantMessage(parentToolUseId)}if(!state.messageId||!state.messageStarted){this.startAssistantMessageInternal(state)}this.ensureBlockTypeConsistency(state,"tool_use",parentToolUseId);this.ensureMessageStarted(state,parentToolUseId);this.finalizePendingBlocks(state,parentToolUseId);const{index}=this.createSubagentToolUseBlock(state,toolCall,parentToolUseId);this.processSubagentToolUseBlock(state,index,toolCall,parentToolUseId);this.finalizeSubagentAssistantMessage(parentToolUseId);this.startSubagentAssistantMessage(parentToolUseId)}processSubagentToolUseBlock(state,index,toolCall,parentToolUseId){const startBlock={type:"tool_use",id:toolCall.callId,name:toolCall.name,input:{}};this.onToolUseBlockCreated(state,index,startBlock,parentToolUseId);this.onToolUseInputSet(state,index,toolCall.args??{},parentToolUseId);this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}updateLastAssistantMessage(message){this.lastAssistantMessage=message}appendText(state,fragment,parentToolUseId){if(fragment.length===0){return}this.ensureBlockTypeConsistency(state,"text",parentToolUseId);this.ensureMessageStarted(state,parentToolUseId);let current=state.blocks[state.blocks.length-1];const isNewBlock=!current||current.type!=="text";if(isNewBlock){current={type:"text",text:""};const index2=state.blocks.length;state.blocks.push(current);this.openBlock(state,index2,current);this.onTextBlockCreated(state,index2,current,parentToolUseId)}current.text+=fragment;const index=state.blocks.length-1;this.onTextAppended(state,index,fragment,parentToolUseId)}appendThinking(state,subject,description,parentToolUseId){const actualParentToolUseId=parentToolUseId??null;const parts=[];if(subject&&subject.length>0){parts.push(subject)}if(description&&description.length>0){parts.push(description)}const fragment=parts.join(": ");if(!fragment){return}this.ensureBlockTypeConsistency(state,"thinking",actualParentToolUseId);this.ensureMessageStarted(state,actualParentToolUseId);let current=state.blocks[state.blocks.length-1];const isNewBlock=!current||current.type!=="thinking";if(isNewBlock){current={type:"thinking",thinking:"",signature:subject};const index2=state.blocks.length;state.blocks.push(current);this.openBlock(state,index2,current);this.onThinkingBlockCreated(state,index2,current,actualParentToolUseId)}current.thinking=`${current.thinking??""}${fragment}`;const index=state.blocks.length-1;this.onThinkingAppended(state,index,fragment,actualParentToolUseId)}appendToolUse(state,request,parentToolUseId){this.ensureBlockTypeConsistency(state,"tool_use",parentToolUseId);this.ensureMessageStarted(state,parentToolUseId);this.finalizePendingBlocks(state,parentToolUseId);const index=state.blocks.length;const block={type:"tool_use",id:request.callId,name:request.name,input:request.args};state.blocks.push(block);this.openBlock(state,index,block);const startBlock={type:"tool_use",id:request.callId,name:request.name,input:{}};this.onToolUseBlockCreated(state,index,startBlock,parentToolUseId);this.onToolUseInputSet(state,index,request.args??{},parentToolUseId);this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}ensureMessageStarted(state,parentToolUseId){if(state.messageStarted){return}state.messageStarted=true;this.onEnsureMessageStarted(state,parentToolUseId)}createSubagentToolUseBlock(state,toolCall,_parentToolUseId){const index=state.blocks.length;const block={type:"tool_use",id:toolCall.callId,name:toolCall.name,input:toolCall.args||{}};state.blocks.push(block);this.openBlock(state,index,block);return{block,index}}emitUserMessage(parts,parentToolUseId){const content=partsToContentBlock(parts);const message={type:"user",uuid:randomUUID(),session_id:this.getSessionId(),parent_tool_use_id:parentToolUseId??null,message:{role:"user",content}};this.emitMessageImpl(message)}checkResponsePartsForError(responseParts){return checkResponsePartsForError(responseParts)}emitToolResult(request,response,parentToolUseId=null){const responsePartsError=this.checkResponsePartsForError(response.responseParts);const hasError=Boolean(response.error)||Boolean(responsePartsError);if(response.error&&response.errorType==="execution_denied"){const denial={tool_name:request.name,tool_use_id:request.callId,tool_input:request.args};this.permissionDenials.push(denial)}const block={type:"tool_result",tool_use_id:request.callId,is_error:hasError};const content=toolResultContent(response);let projectedContent;if(content!==void 0){projectedContent=projectHeadlessToolResultContent(content);block.content=projectedContent}const message={type:"user",uuid:randomUUID(),session_id:this.getSessionId(),parent_tool_use_id:parentToolUseId,message:{role:"user",content:[block]}};if(content!==void 0&&projectedContent!==void 0){observeHeadlessToolResultProjection(message,content,projectedContent,request.callId,response.boundaryArtifact??toolResultBoundaryArtifact(response.persistedOutputFiles,response.artifacts))}this.emitMessageImpl(message)}emitSystemMessage(subtype,data){const systemMessage={type:"system",subtype,uuid:randomUUID(),session_id:this.getSessionId(),parent_tool_use_id:null,data};this.emitMessageImpl(systemMessage)}emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath=null,permissionSuggestions=null){const message={type:"control_request",request_id:requestId,request:{subtype:"can_use_tool",tool_name:toolName,tool_use_id:toolUseId,input,permission_suggestions:permissionSuggestions,blocked_path:blockedPath}};this.emitControlMessageImpl(message)}emitControlResponse(requestId,allowed){const message={type:"control_response",response:{subtype:"success",request_id:requestId,response:{allowed}}};this.emitControlMessageImpl(message)}emitControlError(requestId,errorMessage){const message={type:"control_response",response:{subtype:"error",request_id:requestId,error:errorMessage}};this.emitControlMessageImpl(message)}emitToolProgress(_request,_progress){}buildResultMessage(options,lastAssistantMessage){const usage=options.usage??createExtendedUsage();const resultText=options.summary??(lastAssistantMessage?extractTextFromBlocks(lastAssistantMessage.message.content):"");const baseUuid=randomUUID();const baseSessionId=this.getSessionId();if(options.isError){const errorMessage=options.errorMessage??"Unknown error";return{type:"result",subtype:options.subtype??"error_during_execution",uuid:baseUuid,session_id:baseSessionId,is_error:true,duration_ms:options.durationMs,duration_api_ms:options.apiDurationMs,num_turns:options.numTurns,usage,permission_denials:[...this.permissionDenials],error:{message:errorMessage}}}else{const hasStructured="structuredResult"in options;const normalizedStructured=hasStructured?options.structuredResult??null:void 0;const finalResult=hasStructured?JSON.stringify(normalizedStructured):resultText;const success={type:"result",subtype:options.subtype??"success",uuid:baseUuid,session_id:baseSessionId,is_error:false,duration_ms:options.durationMs,duration_api_ms:options.apiDurationMs,num_turns:options.numTurns,result:finalResult,usage,permission_denials:[...this.permissionDenials]};if(options.stats){success.stats=options.stats}if(hasStructured){success.structured_result=normalizedStructured}return success}}buildSubagentErrorResult(errorMessage,numTurns){const usage={input_tokens:0,output_tokens:0};return{type:"result",subtype:"error_during_execution",uuid:randomUUID(),session_id:this.getSessionId(),is_error:true,duration_ms:0,duration_api_ms:0,num_turns:numTurns,usage,permission_denials:[],error:{message:errorMessage}}}};function partsToContentBlock(parts){const blocks=[];let currentTextBlock=null;for(const part of parts){let textContent=null;if("text"in part&&typeof part.text==="string"){textContent=part.text}else if("functionResponse"in part&&part.functionResponse){const output=part.functionResponse.response?.["output"]??part.functionResponse.response?.["content"]??"";textContent=typeof output==="string"?output:JSON.stringify(output)}else{textContent=JSON.stringify(part)}if(textContent!==null&&textContent.length>0){if(currentTextBlock===null){currentTextBlock={type:"text",text:textContent};blocks.push(currentTextBlock)}else{currentTextBlock.text+=textContent}}}return blocks}__name(partsToContentBlock,"partsToContentBlock");function checkResponsePartsForError(responseParts){if(!responseParts||responseParts.length===0){return void 0}for(const part of responseParts){if("functionResponse"in part&&part.functionResponse?.response&&typeof part.functionResponse.response==="object"&&"error"in part.functionResponse.response&&part.functionResponse.response["error"]){const error=part.functionResponse.response["error"];return typeof error==="string"?error:String(error)}}return void 0}__name(checkResponsePartsForError,"checkResponsePartsForError");function mcpAppFallbackText(display){if(!display||typeof display!=="object"||!("type"in display)||display.type!=="mcp_app"||!("fallbackText"in display)||typeof display.fallbackText!=="string"){return void 0}const text=display.fallbackText.trim();return text.length>0?display.fallbackText:void 0}__name(mcpAppFallbackText,"mcpAppFallbackText");function toolResultContent(response){if(response.visionBridgeNotice){const content=toolResultContent({...response,visionBridgeNotice:void 0});return content?`${response.visionBridgeNotice}
5
5
  ${content}`:response.visionBridgeNotice}if(isVisionBridgeNoticeDisplay(response.resultDisplay)){const notice=formatVisionBridgeNoticeDisplay(response.resultDisplay);if(response.error){return`${notice}
6
6
  ${response.error.message}`}const responsePartsError2=checkResponsePartsForError(response.responseParts);if(responsePartsError2){return`${notice}
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{redactMcpServersSetting,restoreRedactedMcpServersSetting}from"./chunk-44U2VNWI.js";import{safeLogValue}from"./chunk-SVGTUGV2.js";import{requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeFromParam,sendGenerationClosedError}from"./chunk-KKBOCRPF.js";import{STATUS_SCHEMA_VERSION}from"./chunk-LUDNUVSA.js";import{isServeDebugMode}from"./chunk-CUNEBE5E.js";import{loadSettings}from"./chunk-WI4UMN3Q.js";import{BuiltinAgentRegistry,SubagentManager}from"./chunk-Z5XENA4A.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{SubagentError,SubagentErrorCode}from"./chunk-B3ZFUGTC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";import{isDeepStrictEqual}from"node:util";var AGENT_TYPE_PATTERN=/^[\p{L}\p{N}_-]+$/u;var AGENT_TYPE_MAX_LENGTH=64;var AGENT_TYPE_MIN_LENGTH=2;var MAX_DESCRIPTION_BYTES=256*1024;var MAX_SYSTEM_PROMPT_BYTES=256*1024;var MAX_TOOLS_ENTRIES=256;var MAX_TOOL_ID_LENGTH=256;var MAX_RECORD_ENTRIES=128;var SUBAGENT_APPROVAL_MODES=[...APPROVAL_MODES,"bubble"];var SUBAGENT_PERMISSION_MODES=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"];var SUBAGENT_COLORS=["auto","red","blue","green","yellow","purple","orange","pink","cyan"];function captureTrustedGeneration(deps,res){const assertGenerationOpen=deps.captureGenerationAssertion?.()??(()=>{});try{assertGenerationOpen()}catch{res.set("Retry-After","1");res.status(503).json({error:"Workspace runtime is not active.",code:"workspace_runtime_unavailable"});return null}if(deps.isWorkspaceTrusted?.()===false){res.status(403).json({error:"Workspace is not trusted.",code:"untrusted_workspace"});return null}return assertGenerationOpen}__name(captureTrustedGeneration,"captureTrustedGeneration");function mountWorkspaceAgentsRoutes(app,deps){const manager=createDaemonSubagentManager(deps.boundWorkspace);app.get("/workspace/agents",async(_req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;try{const agents=await manager.listSubagents({force:true});assertGenerationOpen();const status={v:STATUS_SCHEMA_VERSION,workspaceCwd:deps.boundWorkspace,agents:agents.map(toSummary)};res.status(200).json(status)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to list workspace agents",code:"agent_list_failed"})}});app.post("/workspace/agents",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const scope=body["scope"];if(scope!=="workspace"&&scope!=="global"){res.status(400).json({error:'`scope` must be "workspace" or "global"',code:"invalid_scope"});return}const level=scope==="workspace"?"project":"user";const config=parseAgentConfig(restoreAgentMcpServerSecrets(body,deps.boundWorkspace,level),level,res);if(!config)return;const collision=await manager.loadSubagent(config.name,level);if(collision){res.status(409).json({error:`Subagent "${config.name}" already exists at ${level} level`,code:"agent_already_exists",name:config.name,level});return}try{assertGenerationOpen();await manager.createSubagent(config,{level,assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.ALREADY_EXISTS){res.status(409).json({error:err.message,code:"agent_already_exists",name:err.subagentName??config.name});return}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_CONFIG||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??config.name});return}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??config.name});return}}writeStderrLine(`qwen serve: POST /workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to create workspace agent",code:"agent_create_failed"});return}const created=await manager.loadSubagent(config.name,level);try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!created){writeStderrLine(`qwen serve: agent_create_reload_failed (name=${safeLogValue(config.name)} level=${level}) \u2014 file likely persisted on disk; check \`GET /workspace/agents\` for a phantom entry`);res.status(500).json({error:"Agent creation succeeded but reload failed",code:"agent_create_reload_failed",name:config.name,level});return}deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"created",name:config.name,level},...originatorClientId?{originatorClientId}:{}});res.status(201).json({ok:true,agent:toDetail(created)})});app.post("/workspace/agents/generate",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const description=body["description"];if(typeof description!=="string"||description.trim().length===0){res.status(400).json({error:"`description` must be a non-empty string",code:"invalid_description"});return}if(Buffer.byteLength(description,"utf8")>4096){res.status(400).json({error:"`description` exceeds the 4096-byte limit",code:"invalid_description"});return}try{const generated=await deps.bridge.generateWorkspaceAgent(description.trim(),originatorClientId);assertGenerationOpen();res.status(200).json(generated)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST /workspace/agents/generate failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to generate workspace agent",code:"agent_generate_failed"})}});app.get("/workspace/agents/:agentType",async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;try{const scopedLevel=parseScopeQuery(req,res);if(scopedLevel===null)return;const config=await manager.loadSubagent(agentType,scopedLevel);assertGenerationOpen();if(!config){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}res.status(200).json(toDetail(config))}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to read workspace agent",code:"agent_read_failed"})}});app.post("/workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const preferredLevel=parseScopeQuery(req,res);if(preferredLevel===null)return;const existing=await manager.loadSubagent(agentType,preferredLevel);if(!existing){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}if(assertMutableLevel(existing,agentType,res)){return}const body=restoreAgentMcpServerSecrets(deps.safeBody(req),deps.boundWorkspace,existing.level,existing.mcpServers);const updates=parseAgentUpdates(body,res);if(!updates)return;if(Object.keys(updates).length===0){res.status(400).json({error:"`POST /workspace/agents/:agentType` requires at least one updatable field in the body",code:"invalid_config",name:agentType});return}if(isNoOpUpdate(existing,updates)){res.status(200).json({ok:true,agent:toDetail(existing),changed:false});return}try{assertGenerationOpen();await manager.updateSubagent(agentType,updates,existing.level,{assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: POST /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to update workspace agent",code:"agent_update_failed"});return}const updated=await manager.loadSubagent(agentType,existing.level);try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!updated){writeStderrLine(`qwen serve: agent_update_reload_failed (name=${safeLogValue(agentType)} level=${existing.level}) \u2014 disk write completed; check \`GET /workspace/agents/${safeLogValue(agentType)}\` for the new state`);res.status(500).json({error:"Agent update succeeded but reload failed",code:"agent_update_reload_failed",name:agentType,level:existing.level});return}const eventLevel=existing.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"updated",name:existing.name,level:eventLevel},...originatorClientId?{originatorClientId}:{}});res.status(200).json({ok:true,agent:toDetail(updated),changed:true})});app.delete("/workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const scopedLevel=parseScopeQuery(req,res);if(scopedLevel===null)return;const levelsToCheck=scopedLevel?[scopedLevel]:["project","user"];const existingAtLevels=[];for(const lvl of levelsToCheck){const found=await manager.loadSubagent(agentType,lvl);if(found)existingAtLevels.push(found)}for(const found of existingAtLevels){if(assertMutableLevel(found,agentType,res))return}try{assertGenerationOpen();await manager.deleteSubagent(agentType,scopedLevel,void 0,{assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: DELETE /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to delete workspace agent",code:"agent_delete_failed"});return}const removed=[];const remaining=[];for(const found of existingAtLevels){if(!found.filePath){removed.push(found);continue}try{await fs.access(found.filePath);remaining.push(found)}catch{removed.push(found)}}try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(remaining.length>0){writeStderrLine(`qwen serve: DELETE /workspace/agents/${safeLogValue(agentType)} partial \u2014 removed=${removed.map(r=>r.level).join(",")||"none"} remaining=${remaining.map(r=>`${r.level}:${r.filePath}`).join(",")}`);for(const found of removed){const evtLevel=found.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:found.name,level:evtLevel},...originatorClientId?{originatorClientId}:{}})}res.status(500).json({error:`Failed to delete every level of subagent "${agentType}" \u2014 ${remaining.length} level(s) still have their file on disk`,code:"agent_delete_partial",name:agentType,removedLevels:removed.map(r=>r.level),remainingLevels:remaining.map(r=>r.level)});return}if(existingAtLevels.length===0){const fallbackLevel=scopedLevel==="user"?"user":"project";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:agentType,level:fallbackLevel},...originatorClientId?{originatorClientId}:{}})}else{for(const found of removed){const evtLevel=found.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:found.name,level:evtLevel},...originatorClientId?{originatorClientId}:{}})}}res.status(204).end()})}__name(mountWorkspaceAgentsRoutes,"mountWorkspaceAgentsRoutes");function mountWorkspaceQualifiedAgentsRoutes(app,deps){app.get("/workspaces/:workspace/agents",async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);try{const agents=await manager.listSubagents({force:true});runtime.generationGuard?.assertOpen();const status={v:STATUS_SCHEMA_VERSION,workspaceCwd:runtime.workspaceCwd,agents:agents.filter(agent=>agent.level==="project").map(toSummary)};res.status(200).json(status)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspaces/:workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to list workspace agents",code:"agent_list_failed"})}});app.post("/workspaces/:workspace/agents",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const level=parseWorkspaceOnlyAgentBodyScope(body,res);if(level===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const config=parseAgentConfig(restoreAgentMcpServerSecrets(body,runtime.workspaceCwd,level),level,res);if(!config)return;const collision=await manager.loadSubagent(config.name,level);if(collision){res.status(409).json({error:`Subagent "${config.name}" already exists at ${level} level`,code:"agent_already_exists",name:config.name,level});return}try{runtime.generationGuard?.assertOpen();await manager.createSubagent(config,{level,assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(sendCreateAgentError(res,err,config.name))return;writeStderrLine(`qwen serve: POST /workspaces/:workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to create workspace agent",code:"agent_create_failed"});return}const created=await manager.loadSubagent(config.name,level);try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!created){writeStderrLine(`qwen serve: agent_create_reload_failed (name=${safeLogValue(config.name)} level=${level}) \u2014 file likely persisted on disk; check \`GET /workspaces/:workspace/agents\` for a phantom entry`);res.status(500).json({error:"Agent creation succeeded but reload failed",code:"agent_create_reload_failed",name:config.name,level});return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"created",name:config.name,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(201).json({ok:true,agent:toDetail(created)})});app.get("/workspaces/:workspace/agents/:agentType",async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);try{const config=await manager.loadSubagent(agentType,scopedLevel);runtime.generationGuard?.assertOpen();if(!config){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}res.status(200).json(toDetail(config))}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to read workspace agent",code:"agent_read_failed"})}});app.post("/workspaces/:workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const existing=await manager.loadSubagent(agentType,scopedLevel);if(!existing){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}if(assertMutableLevel(existing,agentType,res))return;const body=restoreAgentMcpServerSecrets(deps.safeBody(req),runtime.workspaceCwd,existing.level,existing.mcpServers);const updates=parseAgentUpdates(body,res);if(!updates)return;if(Object.keys(updates).length===0){res.status(400).json({error:"`POST /workspaces/:workspace/agents/:agentType` requires at least one updatable field in the body",code:"invalid_config",name:agentType});return}if(isNoOpUpdate(existing,updates)){res.status(200).json({ok:true,agent:toDetail(existing),changed:false});return}try{runtime.generationGuard?.assertOpen();await manager.updateSubagent(agentType,updates,existing.level,{assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(sendUpdateAgentError(res,err,agentType))return;writeStderrLine(`qwen serve: POST /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to update workspace agent",code:"agent_update_failed"});return}const updated=await manager.loadSubagent(agentType,existing.level);try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!updated){writeStderrLine(`qwen serve: agent_update_reload_failed (name=${safeLogValue(agentType)} level=${existing.level}) \u2014 disk write completed; check \`GET /workspaces/:workspace/agents/${safeLogValue(agentType)}\` for the new state`);res.status(500).json({error:"Agent update succeeded but reload failed",code:"agent_update_reload_failed",name:agentType,level:existing.level});return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"updated",name:existing.name,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(200).json({ok:true,agent:toDetail(updated),changed:true})});app.delete("/workspaces/:workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const existing=await manager.loadSubagent(agentType,scopedLevel);if(existing&&assertMutableLevel(existing,agentType,res))return;try{runtime.generationGuard?.assertOpen();await manager.deleteSubagent(agentType,scopedLevel,void 0,{assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: DELETE /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to delete workspace agent",code:"agent_delete_failed"});return}if(existing?.filePath){try{await fs.access(existing.filePath);writeStderrLine(`qwen serve: DELETE /workspaces/:workspace/agents/${safeLogValue(agentType)} partial \u2014 remaining=${existing.level}:${existing.filePath}`);res.status(500).json({error:`Failed to delete subagent "${agentType}" \u2014 ${existing.level} level still has its file on disk`,code:"agent_delete_partial",name:agentType,removedLevels:[],remainingLevels:[existing.level]});return}catch{}}try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:existing?.name??agentType,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(204).end()})}__name(mountWorkspaceQualifiedAgentsRoutes,"mountWorkspaceQualifiedAgentsRoutes");function validateAgentType(req,res){const raw=req.params["agentType"];if(!raw||raw.length===0){res.status(400).json({error:"`agentType` path parameter is required",code:"invalid_agent_type"});return null}if(raw.length>AGENT_TYPE_MAX_LENGTH||!AGENT_TYPE_PATTERN.test(raw)){res.status(400).json({error:"`agentType` must contain only letters, numbers, hyphens, or underscores (max 64 chars)",code:"invalid_agent_type",agentType:raw});return null}return raw}__name(validateAgentType,"validateAgentType");function parseScopeQuery(req,res){const raw=req.query["scope"];if(raw===void 0)return void 0;if(typeof raw!=="string"){res.status(400).json({error:'`scope` query must be a single "workspace" or "global" value',code:"invalid_scope"});return null}if(raw!=="workspace"&&raw!=="global"){res.status(400).json({error:'`scope` query must be "workspace" or "global"',code:"invalid_scope"});return null}return raw==="workspace"?"project":"user"}__name(parseScopeQuery,"parseScopeQuery");function assertMutableLevel(found,agentType,res){if(found.isBuiltin||found.level==="builtin"||found.level==="extension"||found.level==="session"){res.status(403).json({error:`Cannot modify ${found.level}-level subagent "${agentType}"`,code:"agent_readonly",name:found.name,level:found.level});return true}return false}__name(assertMutableLevel,"assertMutableLevel");function resolveOriginatorClientId(deps,req,res){const clientId=deps.parseClientId(req,res);if(clientId===null)return null;if(clientId===void 0)return void 0;if(!deps.bridge.knownClientIds().has(clientId)){res.status(400).json({error:`Client id "${clientId}" is not registered for this workspace`,code:"invalid_client_id",clientId});return null}return clientId}__name(resolveOriginatorClientId,"resolveOriginatorClientId");function resolveTrustedWorkspaceAgentRuntime(deps,req,res){const runtime=resolveWorkspaceRuntimeFromParam(deps.workspaceRegistry,req,res);if(!runtime)return void 0;if(!requireTrustedWorkspaceRuntime(runtime,res))return void 0;return runtime}__name(resolveTrustedWorkspaceAgentRuntime,"resolveTrustedWorkspaceAgentRuntime");function workspaceAgentDepsForRuntime(runtime,deps){return{bridge:runtime.bridge,boundWorkspace:runtime.workspaceCwd,mutate:deps.mutate,parseClientId:deps.parseClientId,safeBody:deps.safeBody}}__name(workspaceAgentDepsForRuntime,"workspaceAgentDepsForRuntime");function parseWorkspaceOnlyAgentBodyScope(body,res){const scope=body["scope"];if(scope===void 0||scope==="workspace"||scope==="project"){return"project"}return rejectWorkspaceQualifiedAgentScope(scope,res)}__name(parseWorkspaceOnlyAgentBodyScope,"parseWorkspaceOnlyAgentBodyScope");function parseWorkspaceOnlyAgentScopeQuery(req,res){const raw=req.query["scope"];if(raw===void 0||raw==="workspace"||raw==="project"){return"project"}if(typeof raw!=="string"){res.status(400).json({error:"`scope` query must be a single workspace/project value",code:"invalid_scope"});return null}return rejectWorkspaceQualifiedAgentScope(raw,res)}__name(parseWorkspaceOnlyAgentScopeQuery,"parseWorkspaceOnlyAgentScopeQuery");function rejectWorkspaceQualifiedAgentScope(scope,res){if(scope==="global"||scope==="user"){res.status(400).json({error:"Workspace-qualified agents routes only support workspace/project scope",code:"global_scope_not_supported_for_workspace_route"});return null}res.status(400).json({error:'`scope` must be "workspace" or "project"',code:"invalid_scope"});return null}__name(rejectWorkspaceQualifiedAgentScope,"rejectWorkspaceQualifiedAgentScope");function restoreAgentMcpServerSecrets(body,workspace,level,currentAgentServers){const incoming=body["mcpServers"];if(typeof incoming!=="object"||incoming===null||Array.isArray(incoming)){return body}const settings=loadSettings(workspace);const configuredServers=level==="user"?settings.user.settings.mcpServers??{}:settings.merged.mcpServers??{};return{...body,mcpServers:restoreRedactedMcpServersSetting(incoming,{...configuredServers,...currentAgentServers})}}__name(restoreAgentMcpServerSecrets,"restoreAgentMcpServerSecrets");function sendCreateAgentError(res,err,name){if(!(err instanceof SubagentError))return false;if(err.code===SubagentErrorCode.ALREADY_EXISTS){res.status(409).json({error:err.message,code:"agent_already_exists",name:err.subagentName??name});return true}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_CONFIG||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??name});return true}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??name});return true}return false}__name(sendCreateAgentError,"sendCreateAgentError");function sendUpdateAgentError(res,err,agentType){if(!(err instanceof SubagentError))return false;if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??agentType});return true}return false}__name(sendUpdateAgentError,"sendUpdateAgentError");function parseAgentConfig(body,level,res){if("executionBackend"in body){return sendInvalidConfig(res,"Daemon agents do not support executionBackend.")}const rawName=body["name"];if(typeof rawName!=="string"||rawName.trim().length===0){res.status(422).json({error:"`name` is required and must be a non-empty string",code:"invalid_config"});return void 0}const name=rawName.trim();if(name.length<AGENT_TYPE_MIN_LENGTH||name.length>AGENT_TYPE_MAX_LENGTH||!AGENT_TYPE_PATTERN.test(name)){res.status(422).json({error:`\`name\` must be ${AGENT_TYPE_MIN_LENGTH}-${AGENT_TYPE_MAX_LENGTH} characters of letters, numbers, hyphens, or underscores`,code:"invalid_config",name});return void 0}if(BuiltinAgentRegistry.isBuiltinAgent(name)){res.status(422).json({error:`"${name}" shadows a built-in subagent and cannot be used as a project- or user-level agent name. Choose a different name.`,code:"invalid_config",name});return void 0}const description=body["description"];if(typeof description!=="string"||description.trim().length===0){res.status(422).json({error:"`description` is required and must be a non-empty string",code:"invalid_config"});return void 0}if(Buffer.byteLength(description,"utf8")>MAX_DESCRIPTION_BYTES){res.status(422).json({error:`\`description\` exceeds the ${MAX_DESCRIPTION_BYTES}-byte limit`,code:"invalid_config"});return void 0}const systemPrompt=body["systemPrompt"];if(typeof systemPrompt!=="string"||systemPrompt.trim().length===0){res.status(422).json({error:"`systemPrompt` is required and must be a non-empty string (whitespace only is rejected)",code:"invalid_config"});return void 0}if(Buffer.byteLength(systemPrompt,"utf8")>MAX_SYSTEM_PROMPT_BYTES){res.status(422).json({error:`\`systemPrompt\` exceeds the ${MAX_SYSTEM_PROMPT_BYTES}-byte limit`,code:"invalid_config"});return void 0}const tools=parseStringArray(body["tools"],"tools",res);if(tools===null)return void 0;const disallowedTools=parseStringArray(body["disallowedTools"],"disallowedTools",res);if(disallowedTools===null)return void 0;const config={name,description,systemPrompt,level};if(tools!==void 0)config.tools=tools;if(disallowedTools!==void 0)config.disallowedTools=disallowedTools;if(rejectIfPresentWrongType(body,"model","string",res))return void 0;if(typeof body["model"]==="string"){if(!body["model"].trim()){return sendInvalidConfig(res,"`model` must not be empty when provided")}config.model=body["model"].trim()}if(rejectIfPresentWrongType(body,"color","string",res))return void 0;if(typeof body["color"]==="string"){if(!SUBAGENT_COLORS.includes(body["color"])){return sendInvalidConfig(res,`\`color\` must be one of ${JSON.stringify(SUBAGENT_COLORS)}`)}config.color=body["color"]}if(rejectIfPresentWrongType(body,"approvalMode","string",res)){return void 0}if(typeof body["approvalMode"]==="string"){if(!SUBAGENT_APPROVAL_MODES.includes(body["approvalMode"])){return sendInvalidConfig(res,`\`approvalMode\` must be one of ${JSON.stringify(SUBAGENT_APPROVAL_MODES)}`)}config.approvalMode=body["approvalMode"]}if(rejectIfPresentWrongType(body,"permissionMode","string",res)){return void 0}if(typeof body["permissionMode"]==="string"){if(!SUBAGENT_PERMISSION_MODES.includes(body["permissionMode"])){return sendInvalidConfig(res,`\`permissionMode\` must be one of ${JSON.stringify(SUBAGENT_PERMISSION_MODES)}`)}config.permissionMode=body["permissionMode"]}if("maxTurns"in body){const maxTurns=parseMaxTurns(body["maxTurns"],res);if(maxTurns===null)return void 0;config.maxTurns=maxTurns}if("mcpServers"in body){const mcpServers=parseRecordField(body["mcpServers"],"mcpServers",value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"an object of server names to server configuration objects",res);if(mcpServers===null)return void 0;if(Object.keys(mcpServers).length>0)config.mcpServers=mcpServers}if("hooks"in body){const hooks=parseRecordField(body["hooks"],"hooks",Array.isArray,"an object of hook event names to matcher arrays",res);if(hooks===null)return void 0;if(Object.keys(hooks).length>0)config.hooks=hooks}if(rejectIfPresentWrongType(body,"background","boolean",res)){return void 0}if(typeof body["background"]==="boolean"){config.background=body["background"]}const runConfig=body["runConfig"];if(runConfig!==void 0){const sanitized=sanitizeRunConfig(runConfig,res);if(sanitized===null)return void 0;config.runConfig=sanitized}return config}__name(parseAgentConfig,"parseAgentConfig");function parseAgentUpdates(body,res){if("executionBackend"in body){return sendInvalidConfig(res,"Daemon agents do not support executionBackend.")}const updates={};if("description"in body){const value=body["description"];if(typeof value!=="string"||value.trim().length===0){res.status(422).json({error:"`description` must be a non-empty string (whitespace only is rejected) when provided",code:"invalid_config"});return void 0}if(Buffer.byteLength(value,"utf8")>MAX_DESCRIPTION_BYTES){res.status(422).json({error:`\`description\` exceeds the ${MAX_DESCRIPTION_BYTES}-byte limit`,code:"invalid_config"});return void 0}updates.description=value}if("systemPrompt"in body){const value=body["systemPrompt"];if(typeof value!=="string"||value.trim().length===0){res.status(422).json({error:"`systemPrompt` must be a non-empty string (whitespace only is rejected) when provided",code:"invalid_config"});return void 0}if(Buffer.byteLength(value,"utf8")>MAX_SYSTEM_PROMPT_BYTES){res.status(422).json({error:`\`systemPrompt\` exceeds the ${MAX_SYSTEM_PROMPT_BYTES}-byte limit`,code:"invalid_config"});return void 0}updates.systemPrompt=value}if("tools"in body){const tools=parseStringArray(body["tools"],"tools",res);if(tools===null)return void 0;if(tools!==void 0)updates.tools=tools}if("disallowedTools"in body){const disallowedTools=parseStringArray(body["disallowedTools"],"disallowedTools",res);if(disallowedTools===null)return void 0;if(disallowedTools!==void 0){updates.disallowedTools=disallowedTools}}if(body["model"]===null){updates.model=void 0}else if(rejectIfPresentWrongType(body,"model","string",res)){return void 0}else if(typeof body["model"]==="string"){if(!body["model"].trim()){return sendInvalidConfig(res,"`model` must not be empty when provided")}updates.model=body["model"].trim()}if(body["color"]===null){updates.color=void 0}else if(rejectIfPresentWrongType(body,"color","string",res)){return void 0}else if(typeof body["color"]==="string"){if(!SUBAGENT_COLORS.includes(body["color"])){return sendInvalidConfig(res,`\`color\` must be one of ${JSON.stringify(SUBAGENT_COLORS)}`)}updates.color=body["color"]}if(body["approvalMode"]===null){updates.approvalMode=void 0}else if(rejectIfPresentWrongType(body,"approvalMode","string",res)){return void 0}else if(typeof body["approvalMode"]==="string"){if(!SUBAGENT_APPROVAL_MODES.includes(body["approvalMode"])){return sendInvalidConfig(res,`\`approvalMode\` must be one of ${JSON.stringify(SUBAGENT_APPROVAL_MODES)}`)}updates.approvalMode=body["approvalMode"]}if(body["permissionMode"]===null){updates.permissionMode=void 0}else if(rejectIfPresentWrongType(body,"permissionMode","string",res)){return void 0}else if(typeof body["permissionMode"]==="string"){if(!SUBAGENT_PERMISSION_MODES.includes(body["permissionMode"])){return sendInvalidConfig(res,`\`permissionMode\` must be one of ${JSON.stringify(SUBAGENT_PERMISSION_MODES)}`)}updates.permissionMode=body["permissionMode"]}if("maxTurns"in body){if(body["maxTurns"]===null){updates.maxTurns=void 0}else{const maxTurns=parseMaxTurns(body["maxTurns"],res);if(maxTurns===null)return void 0;updates.maxTurns=maxTurns}}if("mcpServers"in body){const mcpServers=parseRecordField(body["mcpServers"],"mcpServers",value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"an object of server names to server configuration objects",res);if(mcpServers===null)return void 0;updates.mcpServers=mcpServers}if("hooks"in body){const hooks=parseRecordField(body["hooks"],"hooks",Array.isArray,"an object of hook event names to matcher arrays",res);if(hooks===null)return void 0;updates.hooks=hooks}if(rejectIfPresentWrongType(body,"background","boolean",res)){return void 0}if(typeof body["background"]==="boolean"){updates.background=body["background"]}if("runConfig"in body){const sanitized=sanitizeRunConfig(body["runConfig"],res);if(sanitized===null)return void 0;updates.runConfig=sanitized}return updates}__name(parseAgentUpdates,"parseAgentUpdates");function parseStringArray(value,field,res){if(value===void 0)return void 0;if(!Array.isArray(value)||value.some(v=>typeof v!=="string")){res.status(422).json({error:`\`${field}\` must be an array of strings when provided`,code:"invalid_config"});return null}if(value.length>MAX_TOOLS_ENTRIES){res.status(422).json({error:`\`${field}\` exceeds the ${MAX_TOOLS_ENTRIES}-entry limit`,code:"invalid_config"});return null}if(value.some(v=>v.length>MAX_TOOL_ID_LENGTH)){res.status(422).json({error:`\`${field}\` entries must be at most ${MAX_TOOL_ID_LENGTH} characters`,code:"invalid_config"});return null}return value}__name(parseStringArray,"parseStringArray");function sendInvalidConfig(res,error){res.status(422).json({error,code:"invalid_config"});return void 0}__name(sendInvalidConfig,"sendInvalidConfig");function parseMaxTurns(value,res){if(typeof value!=="number"||!Number.isFinite(value)||!Number.isInteger(value)||value<=0){sendInvalidConfig(res,"`maxTurns` must be a positive integer");return null}return value}__name(parseMaxTurns,"parseMaxTurns");function parseRecordField(value,field,isValidEntry,expected,res){if(typeof value!=="object"||value===null||Array.isArray(value)){sendInvalidConfig(res,`\`${field}\` must be ${expected}`);return null}const entries=Object.entries(value);if(entries.length>MAX_RECORD_ENTRIES){sendInvalidConfig(res,`\`${field}\` exceeds the ${MAX_RECORD_ENTRIES}-entry limit`);return null}const output={};for(const[key,entry]of entries){if(!key||key.length>MAX_TOOL_ID_LENGTH||key==="__proto__"||key==="constructor"||key==="prototype"||!isValidEntry(entry)){sendInvalidConfig(res,`\`${field}\` must be ${expected}`);return null}output[key]=entry}return output}__name(parseRecordField,"parseRecordField");function rejectIfPresentWrongType(body,key,expected,res){if(!(key in body))return false;if(typeof body[key]===expected)return false;res.status(422).json({error:`\`${key}\` must be a ${expected} when provided`,code:"invalid_config"});return true}__name(rejectIfPresentWrongType,"rejectIfPresentWrongType");function isNoOpUpdate(existing,updates){if(updates.description!==void 0&&updates.description!==existing.description){return false}if(updates.systemPrompt!==void 0&&updates.systemPrompt!==existing.systemPrompt){return false}if(updates.tools!==void 0&&!shallowArrayEqual(updates.tools,existing.tools)){return false}if(updates.disallowedTools!==void 0&&!shallowArrayEqual(updates.disallowedTools,existing.disallowedTools)){return false}if("model"in updates&&updates.model!==existing.model){return false}if("color"in updates&&updates.color!==existing.color){return false}if("approvalMode"in updates&&updates.approvalMode!==existing.approvalMode){return false}if("permissionMode"in updates&&updates.permissionMode!==existing.permissionMode){return false}if("maxTurns"in updates&&updates.maxTurns!==existing.maxTurns){return false}if(updates.mcpServers!==void 0&&!isDeepStrictEqual(normalizedRecord(updates.mcpServers),normalizedRecord(existing.mcpServers))){return false}if(updates.hooks!==void 0&&!isDeepStrictEqual(normalizedRecord(updates.hooks),normalizedRecord(existing.hooks))){return false}if(updates.background!==void 0&&updates.background!==existing.background){return false}if(updates.runConfig!==void 0){const e=existing.runConfig??{};const u=updates.runConfig;if("max_time_minutes"in u){if(u["max_time_minutes"]!==e["max_time_minutes"])return false}if("max_turns"in u){if(u["max_turns"]!==e["max_turns"])return false}}return true}__name(isNoOpUpdate,"isNoOpUpdate");function normalizedRecord(value){if(!value||Object.keys(value).length===0)return void 0;return normalizeRecordValue(value)}__name(normalizedRecord,"normalizedRecord");function normalizeRecordValue(value){if(Array.isArray(value))return value.map(normalizeRecordValue);if(typeof value!=="object"||value===null)return value;return Object.fromEntries(Object.entries(value).filter(([,entry])=>entry!==void 0).map(([key,entry])=>[key,normalizeRecordValue(entry)]))}__name(normalizeRecordValue,"normalizeRecordValue");function shallowArrayEqual(a,b){if(a===b)return true;if(!a||!b)return false;if(a.length!==b.length)return false;for(let i=0;i<a.length;i++)if(a[i]!==b[i])return false;return true}__name(shallowArrayEqual,"shallowArrayEqual");function sanitizeRunConfig(raw,res){if(typeof raw!=="object"||raw===null||Array.isArray(raw)){res.status(422).json({error:"`runConfig` must be an object when provided",code:"invalid_config"});return null}const input=raw;const out={};if("max_time_minutes"in input){const v=input["max_time_minutes"];if(typeof v!=="number"||!Number.isFinite(v)||v<=0){res.status(422).json({error:"`runConfig.max_time_minutes` must be a positive finite number when provided",code:"invalid_config"});return null}out["max_time_minutes"]=v}if("max_turns"in input){const v=input["max_turns"];if(typeof v!=="number"||!Number.isFinite(v)||v<=0||!Number.isInteger(v)){res.status(422).json({error:"`runConfig.max_turns` must be a positive integer when provided",code:"invalid_config"});return null}out["max_turns"]=v}return out}__name(sanitizeRunConfig,"sanitizeRunConfig");function toSummary(config){const summary={kind:"agent",name:config.name,description:config.description,level:config.level,isBuiltin:config.isBuiltin===true||config.level==="builtin",hasTools:Array.isArray(config.tools)&&config.tools.length>0};if(config.tools)summary.tools=[...config.tools];if(config.disallowedTools){summary.disallowedTools=[...config.disallowedTools]}if(config.model)summary.model=config.model;if(config.color)summary.color=config.color;if(config.background!==void 0)summary.background=config.background;if(config.approvalMode)summary.approvalMode=config.approvalMode;if(config.permissionMode)summary.permissionMode=config.permissionMode;if(config.maxTurns!==void 0)summary.maxTurns=config.maxTurns;if(config.mcpServers){summary.mcpServerNames=Object.keys(config.mcpServers)}if(config.hooks)summary.hookEvents=Object.keys(config.hooks);if(config.runConfig){const runConfig={};if(typeof config.runConfig.max_time_minutes==="number"){runConfig.max_time_minutes=config.runConfig.max_time_minutes}if(typeof config.runConfig.max_turns==="number"){runConfig.max_turns=config.runConfig.max_turns}summary.runConfig=runConfig}if(config.extensionName)summary.extensionName=config.extensionName;if(config.filePath)summary.filePath=config.filePath;return summary}__name(toSummary,"toSummary");function toDetail(config){const detail={...toSummary(config),systemPrompt:config.systemPrompt};if(config.mcpServers){detail.mcpServers=redactMcpServersSetting(config.mcpServers)}if(config.hooks)detail.hooks=config.hooks;return detail}__name(toDetail,"toDetail");function createDaemonSubagentManager(boundWorkspace,safeMode=false){const stub={getSdkMode:__name(()=>false,"getSdkMode"),getProjectRoot:__name(()=>boundWorkspace,"getProjectRoot"),getActiveExtensions:__name(()=>[],"getActiveExtensions"),isSafeMode:__name(()=>safeMode,"isSafeMode"),getAgentsSettings:__name(()=>({}),"getAgentsSettings")};const guarded=new Proxy(stub,{get(target,prop){if(prop in target){return target[prop]}if(prop==="then")return void 0;throw new Error(`qwen serve workspace agents: SubagentManager touched Config.${String(prop)} which the daemon stub does not implement. Add it to createDaemonSubagentManager and audit safety.`)},has(target,prop){if(prop in target)return true;if(prop==="then")return false;throw new Error(`qwen serve workspace agents: SubagentManager probed Config.${String(prop)} via 'in' check; the daemon stub does not implement it. Add it to createDaemonSubagentManager and audit safety.`)}});return new SubagentManager(guarded)}__name(createDaemonSubagentManager,"createDaemonSubagentManager");export{mountWorkspaceAgentsRoutes,mountWorkspaceQualifiedAgentsRoutes,toSummary,toDetail,createDaemonSubagentManager};
3
+ import{redactMcpServersSetting,restoreRedactedMcpServersSetting}from"./chunk-44U2VNWI.js";import{safeLogValue}from"./chunk-SVGTUGV2.js";import{requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeFromParam,sendGenerationClosedError}from"./chunk-FKUDVIME.js";import{STATUS_SCHEMA_VERSION}from"./chunk-LUDNUVSA.js";import{isServeDebugMode}from"./chunk-CUNEBE5E.js";import{loadSettings}from"./chunk-Q5RRVBTY.js";import{BuiltinAgentRegistry,SubagentManager}from"./chunk-T3CQ72HC.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{SubagentError,SubagentErrorCode}from"./chunk-B3ZFUGTC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";import{isDeepStrictEqual}from"node:util";var AGENT_TYPE_PATTERN=/^[\p{L}\p{N}_-]+$/u;var AGENT_TYPE_MAX_LENGTH=64;var AGENT_TYPE_MIN_LENGTH=2;var MAX_DESCRIPTION_BYTES=256*1024;var MAX_SYSTEM_PROMPT_BYTES=256*1024;var MAX_TOOLS_ENTRIES=256;var MAX_TOOL_ID_LENGTH=256;var MAX_RECORD_ENTRIES=128;var SUBAGENT_APPROVAL_MODES=[...APPROVAL_MODES,"bubble"];var SUBAGENT_PERMISSION_MODES=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"];var SUBAGENT_COLORS=["auto","red","blue","green","yellow","purple","orange","pink","cyan"];function captureTrustedGeneration(deps,res){const assertGenerationOpen=deps.captureGenerationAssertion?.()??(()=>{});try{assertGenerationOpen()}catch{res.set("Retry-After","1");res.status(503).json({error:"Workspace runtime is not active.",code:"workspace_runtime_unavailable"});return null}if(deps.isWorkspaceTrusted?.()===false){res.status(403).json({error:"Workspace is not trusted.",code:"untrusted_workspace"});return null}return assertGenerationOpen}__name(captureTrustedGeneration,"captureTrustedGeneration");function mountWorkspaceAgentsRoutes(app,deps){const manager=createDaemonSubagentManager(deps.boundWorkspace);app.get("/workspace/agents",async(_req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;try{const agents=await manager.listSubagents({force:true});assertGenerationOpen();const status={v:STATUS_SCHEMA_VERSION,workspaceCwd:deps.boundWorkspace,agents:agents.map(toSummary)};res.status(200).json(status)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to list workspace agents",code:"agent_list_failed"})}});app.post("/workspace/agents",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const scope=body["scope"];if(scope!=="workspace"&&scope!=="global"){res.status(400).json({error:'`scope` must be "workspace" or "global"',code:"invalid_scope"});return}const level=scope==="workspace"?"project":"user";const config=parseAgentConfig(restoreAgentMcpServerSecrets(body,deps.boundWorkspace,level),level,res);if(!config)return;const collision=await manager.loadSubagent(config.name,level);if(collision){res.status(409).json({error:`Subagent "${config.name}" already exists at ${level} level`,code:"agent_already_exists",name:config.name,level});return}try{assertGenerationOpen();await manager.createSubagent(config,{level,assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.ALREADY_EXISTS){res.status(409).json({error:err.message,code:"agent_already_exists",name:err.subagentName??config.name});return}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_CONFIG||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??config.name});return}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??config.name});return}}writeStderrLine(`qwen serve: POST /workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to create workspace agent",code:"agent_create_failed"});return}const created=await manager.loadSubagent(config.name,level);try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!created){writeStderrLine(`qwen serve: agent_create_reload_failed (name=${safeLogValue(config.name)} level=${level}) \u2014 file likely persisted on disk; check \`GET /workspace/agents\` for a phantom entry`);res.status(500).json({error:"Agent creation succeeded but reload failed",code:"agent_create_reload_failed",name:config.name,level});return}deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"created",name:config.name,level},...originatorClientId?{originatorClientId}:{}});res.status(201).json({ok:true,agent:toDetail(created)})});app.post("/workspace/agents/generate",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const description=body["description"];if(typeof description!=="string"||description.trim().length===0){res.status(400).json({error:"`description` must be a non-empty string",code:"invalid_description"});return}if(Buffer.byteLength(description,"utf8")>4096){res.status(400).json({error:"`description` exceeds the 4096-byte limit",code:"invalid_description"});return}try{const generated=await deps.bridge.generateWorkspaceAgent(description.trim(),originatorClientId);assertGenerationOpen();res.status(200).json(generated)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST /workspace/agents/generate failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to generate workspace agent",code:"agent_generate_failed"})}});app.get("/workspace/agents/:agentType",async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;try{const scopedLevel=parseScopeQuery(req,res);if(scopedLevel===null)return;const config=await manager.loadSubagent(agentType,scopedLevel);assertGenerationOpen();if(!config){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}res.status(200).json(toDetail(config))}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to read workspace agent",code:"agent_read_failed"})}});app.post("/workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const preferredLevel=parseScopeQuery(req,res);if(preferredLevel===null)return;const existing=await manager.loadSubagent(agentType,preferredLevel);if(!existing){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}if(assertMutableLevel(existing,agentType,res)){return}const body=restoreAgentMcpServerSecrets(deps.safeBody(req),deps.boundWorkspace,existing.level,existing.mcpServers);const updates=parseAgentUpdates(body,res);if(!updates)return;if(Object.keys(updates).length===0){res.status(400).json({error:"`POST /workspace/agents/:agentType` requires at least one updatable field in the body",code:"invalid_config",name:agentType});return}if(isNoOpUpdate(existing,updates)){res.status(200).json({ok:true,agent:toDetail(existing),changed:false});return}try{assertGenerationOpen();await manager.updateSubagent(agentType,updates,existing.level,{assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: POST /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to update workspace agent",code:"agent_update_failed"});return}const updated=await manager.loadSubagent(agentType,existing.level);try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!updated){writeStderrLine(`qwen serve: agent_update_reload_failed (name=${safeLogValue(agentType)} level=${existing.level}) \u2014 disk write completed; check \`GET /workspace/agents/${safeLogValue(agentType)}\` for the new state`);res.status(500).json({error:"Agent update succeeded but reload failed",code:"agent_update_reload_failed",name:agentType,level:existing.level});return}const eventLevel=existing.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"updated",name:existing.name,level:eventLevel},...originatorClientId?{originatorClientId}:{}});res.status(200).json({ok:true,agent:toDetail(updated),changed:true})});app.delete("/workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const scopedLevel=parseScopeQuery(req,res);if(scopedLevel===null)return;const levelsToCheck=scopedLevel?[scopedLevel]:["project","user"];const existingAtLevels=[];for(const lvl of levelsToCheck){const found=await manager.loadSubagent(agentType,lvl);if(found)existingAtLevels.push(found)}for(const found of existingAtLevels){if(assertMutableLevel(found,agentType,res))return}try{assertGenerationOpen();await manager.deleteSubagent(agentType,scopedLevel,void 0,{assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: DELETE /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to delete workspace agent",code:"agent_delete_failed"});return}const removed=[];const remaining=[];for(const found of existingAtLevels){if(!found.filePath){removed.push(found);continue}try{await fs.access(found.filePath);remaining.push(found)}catch{removed.push(found)}}try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(remaining.length>0){writeStderrLine(`qwen serve: DELETE /workspace/agents/${safeLogValue(agentType)} partial \u2014 removed=${removed.map(r=>r.level).join(",")||"none"} remaining=${remaining.map(r=>`${r.level}:${r.filePath}`).join(",")}`);for(const found of removed){const evtLevel=found.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:found.name,level:evtLevel},...originatorClientId?{originatorClientId}:{}})}res.status(500).json({error:`Failed to delete every level of subagent "${agentType}" \u2014 ${remaining.length} level(s) still have their file on disk`,code:"agent_delete_partial",name:agentType,removedLevels:removed.map(r=>r.level),remainingLevels:remaining.map(r=>r.level)});return}if(existingAtLevels.length===0){const fallbackLevel=scopedLevel==="user"?"user":"project";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:agentType,level:fallbackLevel},...originatorClientId?{originatorClientId}:{}})}else{for(const found of removed){const evtLevel=found.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:found.name,level:evtLevel},...originatorClientId?{originatorClientId}:{}})}}res.status(204).end()})}__name(mountWorkspaceAgentsRoutes,"mountWorkspaceAgentsRoutes");function mountWorkspaceQualifiedAgentsRoutes(app,deps){app.get("/workspaces/:workspace/agents",async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);try{const agents=await manager.listSubagents({force:true});runtime.generationGuard?.assertOpen();const status={v:STATUS_SCHEMA_VERSION,workspaceCwd:runtime.workspaceCwd,agents:agents.filter(agent=>agent.level==="project").map(toSummary)};res.status(200).json(status)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspaces/:workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to list workspace agents",code:"agent_list_failed"})}});app.post("/workspaces/:workspace/agents",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const level=parseWorkspaceOnlyAgentBodyScope(body,res);if(level===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const config=parseAgentConfig(restoreAgentMcpServerSecrets(body,runtime.workspaceCwd,level),level,res);if(!config)return;const collision=await manager.loadSubagent(config.name,level);if(collision){res.status(409).json({error:`Subagent "${config.name}" already exists at ${level} level`,code:"agent_already_exists",name:config.name,level});return}try{runtime.generationGuard?.assertOpen();await manager.createSubagent(config,{level,assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(sendCreateAgentError(res,err,config.name))return;writeStderrLine(`qwen serve: POST /workspaces/:workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to create workspace agent",code:"agent_create_failed"});return}const created=await manager.loadSubagent(config.name,level);try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!created){writeStderrLine(`qwen serve: agent_create_reload_failed (name=${safeLogValue(config.name)} level=${level}) \u2014 file likely persisted on disk; check \`GET /workspaces/:workspace/agents\` for a phantom entry`);res.status(500).json({error:"Agent creation succeeded but reload failed",code:"agent_create_reload_failed",name:config.name,level});return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"created",name:config.name,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(201).json({ok:true,agent:toDetail(created)})});app.get("/workspaces/:workspace/agents/:agentType",async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);try{const config=await manager.loadSubagent(agentType,scopedLevel);runtime.generationGuard?.assertOpen();if(!config){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}res.status(200).json(toDetail(config))}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to read workspace agent",code:"agent_read_failed"})}});app.post("/workspaces/:workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const existing=await manager.loadSubagent(agentType,scopedLevel);if(!existing){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}if(assertMutableLevel(existing,agentType,res))return;const body=restoreAgentMcpServerSecrets(deps.safeBody(req),runtime.workspaceCwd,existing.level,existing.mcpServers);const updates=parseAgentUpdates(body,res);if(!updates)return;if(Object.keys(updates).length===0){res.status(400).json({error:"`POST /workspaces/:workspace/agents/:agentType` requires at least one updatable field in the body",code:"invalid_config",name:agentType});return}if(isNoOpUpdate(existing,updates)){res.status(200).json({ok:true,agent:toDetail(existing),changed:false});return}try{runtime.generationGuard?.assertOpen();await manager.updateSubagent(agentType,updates,existing.level,{assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(sendUpdateAgentError(res,err,agentType))return;writeStderrLine(`qwen serve: POST /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to update workspace agent",code:"agent_update_failed"});return}const updated=await manager.loadSubagent(agentType,existing.level);try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!updated){writeStderrLine(`qwen serve: agent_update_reload_failed (name=${safeLogValue(agentType)} level=${existing.level}) \u2014 disk write completed; check \`GET /workspaces/:workspace/agents/${safeLogValue(agentType)}\` for the new state`);res.status(500).json({error:"Agent update succeeded but reload failed",code:"agent_update_reload_failed",name:agentType,level:existing.level});return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"updated",name:existing.name,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(200).json({ok:true,agent:toDetail(updated),changed:true})});app.delete("/workspaces/:workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const existing=await manager.loadSubagent(agentType,scopedLevel);if(existing&&assertMutableLevel(existing,agentType,res))return;try{runtime.generationGuard?.assertOpen();await manager.deleteSubagent(agentType,scopedLevel,void 0,{assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: DELETE /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to delete workspace agent",code:"agent_delete_failed"});return}if(existing?.filePath){try{await fs.access(existing.filePath);writeStderrLine(`qwen serve: DELETE /workspaces/:workspace/agents/${safeLogValue(agentType)} partial \u2014 remaining=${existing.level}:${existing.filePath}`);res.status(500).json({error:`Failed to delete subagent "${agentType}" \u2014 ${existing.level} level still has its file on disk`,code:"agent_delete_partial",name:agentType,removedLevels:[],remainingLevels:[existing.level]});return}catch{}}try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:existing?.name??agentType,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(204).end()})}__name(mountWorkspaceQualifiedAgentsRoutes,"mountWorkspaceQualifiedAgentsRoutes");function validateAgentType(req,res){const raw=req.params["agentType"];if(!raw||raw.length===0){res.status(400).json({error:"`agentType` path parameter is required",code:"invalid_agent_type"});return null}if(raw.length>AGENT_TYPE_MAX_LENGTH||!AGENT_TYPE_PATTERN.test(raw)){res.status(400).json({error:"`agentType` must contain only letters, numbers, hyphens, or underscores (max 64 chars)",code:"invalid_agent_type",agentType:raw});return null}return raw}__name(validateAgentType,"validateAgentType");function parseScopeQuery(req,res){const raw=req.query["scope"];if(raw===void 0)return void 0;if(typeof raw!=="string"){res.status(400).json({error:'`scope` query must be a single "workspace" or "global" value',code:"invalid_scope"});return null}if(raw!=="workspace"&&raw!=="global"){res.status(400).json({error:'`scope` query must be "workspace" or "global"',code:"invalid_scope"});return null}return raw==="workspace"?"project":"user"}__name(parseScopeQuery,"parseScopeQuery");function assertMutableLevel(found,agentType,res){if(found.isBuiltin||found.level==="builtin"||found.level==="extension"||found.level==="session"){res.status(403).json({error:`Cannot modify ${found.level}-level subagent "${agentType}"`,code:"agent_readonly",name:found.name,level:found.level});return true}return false}__name(assertMutableLevel,"assertMutableLevel");function resolveOriginatorClientId(deps,req,res){const clientId=deps.parseClientId(req,res);if(clientId===null)return null;if(clientId===void 0)return void 0;if(!deps.bridge.knownClientIds().has(clientId)){res.status(400).json({error:`Client id "${clientId}" is not registered for this workspace`,code:"invalid_client_id",clientId});return null}return clientId}__name(resolveOriginatorClientId,"resolveOriginatorClientId");function resolveTrustedWorkspaceAgentRuntime(deps,req,res){const runtime=resolveWorkspaceRuntimeFromParam(deps.workspaceRegistry,req,res);if(!runtime)return void 0;if(!requireTrustedWorkspaceRuntime(runtime,res))return void 0;return runtime}__name(resolveTrustedWorkspaceAgentRuntime,"resolveTrustedWorkspaceAgentRuntime");function workspaceAgentDepsForRuntime(runtime,deps){return{bridge:runtime.bridge,boundWorkspace:runtime.workspaceCwd,mutate:deps.mutate,parseClientId:deps.parseClientId,safeBody:deps.safeBody}}__name(workspaceAgentDepsForRuntime,"workspaceAgentDepsForRuntime");function parseWorkspaceOnlyAgentBodyScope(body,res){const scope=body["scope"];if(scope===void 0||scope==="workspace"||scope==="project"){return"project"}return rejectWorkspaceQualifiedAgentScope(scope,res)}__name(parseWorkspaceOnlyAgentBodyScope,"parseWorkspaceOnlyAgentBodyScope");function parseWorkspaceOnlyAgentScopeQuery(req,res){const raw=req.query["scope"];if(raw===void 0||raw==="workspace"||raw==="project"){return"project"}if(typeof raw!=="string"){res.status(400).json({error:"`scope` query must be a single workspace/project value",code:"invalid_scope"});return null}return rejectWorkspaceQualifiedAgentScope(raw,res)}__name(parseWorkspaceOnlyAgentScopeQuery,"parseWorkspaceOnlyAgentScopeQuery");function rejectWorkspaceQualifiedAgentScope(scope,res){if(scope==="global"||scope==="user"){res.status(400).json({error:"Workspace-qualified agents routes only support workspace/project scope",code:"global_scope_not_supported_for_workspace_route"});return null}res.status(400).json({error:'`scope` must be "workspace" or "project"',code:"invalid_scope"});return null}__name(rejectWorkspaceQualifiedAgentScope,"rejectWorkspaceQualifiedAgentScope");function restoreAgentMcpServerSecrets(body,workspace,level,currentAgentServers){const incoming=body["mcpServers"];if(typeof incoming!=="object"||incoming===null||Array.isArray(incoming)){return body}const settings=loadSettings(workspace);const configuredServers=level==="user"?settings.user.settings.mcpServers??{}:settings.merged.mcpServers??{};return{...body,mcpServers:restoreRedactedMcpServersSetting(incoming,{...configuredServers,...currentAgentServers})}}__name(restoreAgentMcpServerSecrets,"restoreAgentMcpServerSecrets");function sendCreateAgentError(res,err,name){if(!(err instanceof SubagentError))return false;if(err.code===SubagentErrorCode.ALREADY_EXISTS){res.status(409).json({error:err.message,code:"agent_already_exists",name:err.subagentName??name});return true}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_CONFIG||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??name});return true}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??name});return true}return false}__name(sendCreateAgentError,"sendCreateAgentError");function sendUpdateAgentError(res,err,agentType){if(!(err instanceof SubagentError))return false;if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??agentType});return true}return false}__name(sendUpdateAgentError,"sendUpdateAgentError");function parseAgentConfig(body,level,res){if("executionBackend"in body){return sendInvalidConfig(res,"Daemon agents do not support executionBackend.")}const rawName=body["name"];if(typeof rawName!=="string"||rawName.trim().length===0){res.status(422).json({error:"`name` is required and must be a non-empty string",code:"invalid_config"});return void 0}const name=rawName.trim();if(name.length<AGENT_TYPE_MIN_LENGTH||name.length>AGENT_TYPE_MAX_LENGTH||!AGENT_TYPE_PATTERN.test(name)){res.status(422).json({error:`\`name\` must be ${AGENT_TYPE_MIN_LENGTH}-${AGENT_TYPE_MAX_LENGTH} characters of letters, numbers, hyphens, or underscores`,code:"invalid_config",name});return void 0}if(BuiltinAgentRegistry.isBuiltinAgent(name)){res.status(422).json({error:`"${name}" shadows a built-in subagent and cannot be used as a project- or user-level agent name. Choose a different name.`,code:"invalid_config",name});return void 0}const description=body["description"];if(typeof description!=="string"||description.trim().length===0){res.status(422).json({error:"`description` is required and must be a non-empty string",code:"invalid_config"});return void 0}if(Buffer.byteLength(description,"utf8")>MAX_DESCRIPTION_BYTES){res.status(422).json({error:`\`description\` exceeds the ${MAX_DESCRIPTION_BYTES}-byte limit`,code:"invalid_config"});return void 0}const systemPrompt=body["systemPrompt"];if(typeof systemPrompt!=="string"||systemPrompt.trim().length===0){res.status(422).json({error:"`systemPrompt` is required and must be a non-empty string (whitespace only is rejected)",code:"invalid_config"});return void 0}if(Buffer.byteLength(systemPrompt,"utf8")>MAX_SYSTEM_PROMPT_BYTES){res.status(422).json({error:`\`systemPrompt\` exceeds the ${MAX_SYSTEM_PROMPT_BYTES}-byte limit`,code:"invalid_config"});return void 0}const tools=parseStringArray(body["tools"],"tools",res);if(tools===null)return void 0;const disallowedTools=parseStringArray(body["disallowedTools"],"disallowedTools",res);if(disallowedTools===null)return void 0;const config={name,description,systemPrompt,level};if(tools!==void 0)config.tools=tools;if(disallowedTools!==void 0)config.disallowedTools=disallowedTools;if(rejectIfPresentWrongType(body,"model","string",res))return void 0;if(typeof body["model"]==="string"){if(!body["model"].trim()){return sendInvalidConfig(res,"`model` must not be empty when provided")}config.model=body["model"].trim()}if(rejectIfPresentWrongType(body,"color","string",res))return void 0;if(typeof body["color"]==="string"){if(!SUBAGENT_COLORS.includes(body["color"])){return sendInvalidConfig(res,`\`color\` must be one of ${JSON.stringify(SUBAGENT_COLORS)}`)}config.color=body["color"]}if(rejectIfPresentWrongType(body,"approvalMode","string",res)){return void 0}if(typeof body["approvalMode"]==="string"){if(!SUBAGENT_APPROVAL_MODES.includes(body["approvalMode"])){return sendInvalidConfig(res,`\`approvalMode\` must be one of ${JSON.stringify(SUBAGENT_APPROVAL_MODES)}`)}config.approvalMode=body["approvalMode"]}if(rejectIfPresentWrongType(body,"permissionMode","string",res)){return void 0}if(typeof body["permissionMode"]==="string"){if(!SUBAGENT_PERMISSION_MODES.includes(body["permissionMode"])){return sendInvalidConfig(res,`\`permissionMode\` must be one of ${JSON.stringify(SUBAGENT_PERMISSION_MODES)}`)}config.permissionMode=body["permissionMode"]}if("maxTurns"in body){const maxTurns=parseMaxTurns(body["maxTurns"],res);if(maxTurns===null)return void 0;config.maxTurns=maxTurns}if("mcpServers"in body){const mcpServers=parseRecordField(body["mcpServers"],"mcpServers",value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"an object of server names to server configuration objects",res);if(mcpServers===null)return void 0;if(Object.keys(mcpServers).length>0)config.mcpServers=mcpServers}if("hooks"in body){const hooks=parseRecordField(body["hooks"],"hooks",Array.isArray,"an object of hook event names to matcher arrays",res);if(hooks===null)return void 0;if(Object.keys(hooks).length>0)config.hooks=hooks}if(rejectIfPresentWrongType(body,"background","boolean",res)){return void 0}if(typeof body["background"]==="boolean"){config.background=body["background"]}const runConfig=body["runConfig"];if(runConfig!==void 0){const sanitized=sanitizeRunConfig(runConfig,res);if(sanitized===null)return void 0;config.runConfig=sanitized}return config}__name(parseAgentConfig,"parseAgentConfig");function parseAgentUpdates(body,res){if("executionBackend"in body){return sendInvalidConfig(res,"Daemon agents do not support executionBackend.")}const updates={};if("description"in body){const value=body["description"];if(typeof value!=="string"||value.trim().length===0){res.status(422).json({error:"`description` must be a non-empty string (whitespace only is rejected) when provided",code:"invalid_config"});return void 0}if(Buffer.byteLength(value,"utf8")>MAX_DESCRIPTION_BYTES){res.status(422).json({error:`\`description\` exceeds the ${MAX_DESCRIPTION_BYTES}-byte limit`,code:"invalid_config"});return void 0}updates.description=value}if("systemPrompt"in body){const value=body["systemPrompt"];if(typeof value!=="string"||value.trim().length===0){res.status(422).json({error:"`systemPrompt` must be a non-empty string (whitespace only is rejected) when provided",code:"invalid_config"});return void 0}if(Buffer.byteLength(value,"utf8")>MAX_SYSTEM_PROMPT_BYTES){res.status(422).json({error:`\`systemPrompt\` exceeds the ${MAX_SYSTEM_PROMPT_BYTES}-byte limit`,code:"invalid_config"});return void 0}updates.systemPrompt=value}if("tools"in body){const tools=parseStringArray(body["tools"],"tools",res);if(tools===null)return void 0;if(tools!==void 0)updates.tools=tools}if("disallowedTools"in body){const disallowedTools=parseStringArray(body["disallowedTools"],"disallowedTools",res);if(disallowedTools===null)return void 0;if(disallowedTools!==void 0){updates.disallowedTools=disallowedTools}}if(body["model"]===null){updates.model=void 0}else if(rejectIfPresentWrongType(body,"model","string",res)){return void 0}else if(typeof body["model"]==="string"){if(!body["model"].trim()){return sendInvalidConfig(res,"`model` must not be empty when provided")}updates.model=body["model"].trim()}if(body["color"]===null){updates.color=void 0}else if(rejectIfPresentWrongType(body,"color","string",res)){return void 0}else if(typeof body["color"]==="string"){if(!SUBAGENT_COLORS.includes(body["color"])){return sendInvalidConfig(res,`\`color\` must be one of ${JSON.stringify(SUBAGENT_COLORS)}`)}updates.color=body["color"]}if(body["approvalMode"]===null){updates.approvalMode=void 0}else if(rejectIfPresentWrongType(body,"approvalMode","string",res)){return void 0}else if(typeof body["approvalMode"]==="string"){if(!SUBAGENT_APPROVAL_MODES.includes(body["approvalMode"])){return sendInvalidConfig(res,`\`approvalMode\` must be one of ${JSON.stringify(SUBAGENT_APPROVAL_MODES)}`)}updates.approvalMode=body["approvalMode"]}if(body["permissionMode"]===null){updates.permissionMode=void 0}else if(rejectIfPresentWrongType(body,"permissionMode","string",res)){return void 0}else if(typeof body["permissionMode"]==="string"){if(!SUBAGENT_PERMISSION_MODES.includes(body["permissionMode"])){return sendInvalidConfig(res,`\`permissionMode\` must be one of ${JSON.stringify(SUBAGENT_PERMISSION_MODES)}`)}updates.permissionMode=body["permissionMode"]}if("maxTurns"in body){if(body["maxTurns"]===null){updates.maxTurns=void 0}else{const maxTurns=parseMaxTurns(body["maxTurns"],res);if(maxTurns===null)return void 0;updates.maxTurns=maxTurns}}if("mcpServers"in body){const mcpServers=parseRecordField(body["mcpServers"],"mcpServers",value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"an object of server names to server configuration objects",res);if(mcpServers===null)return void 0;updates.mcpServers=mcpServers}if("hooks"in body){const hooks=parseRecordField(body["hooks"],"hooks",Array.isArray,"an object of hook event names to matcher arrays",res);if(hooks===null)return void 0;updates.hooks=hooks}if(rejectIfPresentWrongType(body,"background","boolean",res)){return void 0}if(typeof body["background"]==="boolean"){updates.background=body["background"]}if("runConfig"in body){const sanitized=sanitizeRunConfig(body["runConfig"],res);if(sanitized===null)return void 0;updates.runConfig=sanitized}return updates}__name(parseAgentUpdates,"parseAgentUpdates");function parseStringArray(value,field,res){if(value===void 0)return void 0;if(!Array.isArray(value)||value.some(v=>typeof v!=="string")){res.status(422).json({error:`\`${field}\` must be an array of strings when provided`,code:"invalid_config"});return null}if(value.length>MAX_TOOLS_ENTRIES){res.status(422).json({error:`\`${field}\` exceeds the ${MAX_TOOLS_ENTRIES}-entry limit`,code:"invalid_config"});return null}if(value.some(v=>v.length>MAX_TOOL_ID_LENGTH)){res.status(422).json({error:`\`${field}\` entries must be at most ${MAX_TOOL_ID_LENGTH} characters`,code:"invalid_config"});return null}return value}__name(parseStringArray,"parseStringArray");function sendInvalidConfig(res,error){res.status(422).json({error,code:"invalid_config"});return void 0}__name(sendInvalidConfig,"sendInvalidConfig");function parseMaxTurns(value,res){if(typeof value!=="number"||!Number.isFinite(value)||!Number.isInteger(value)||value<=0){sendInvalidConfig(res,"`maxTurns` must be a positive integer");return null}return value}__name(parseMaxTurns,"parseMaxTurns");function parseRecordField(value,field,isValidEntry,expected,res){if(typeof value!=="object"||value===null||Array.isArray(value)){sendInvalidConfig(res,`\`${field}\` must be ${expected}`);return null}const entries=Object.entries(value);if(entries.length>MAX_RECORD_ENTRIES){sendInvalidConfig(res,`\`${field}\` exceeds the ${MAX_RECORD_ENTRIES}-entry limit`);return null}const output={};for(const[key,entry]of entries){if(!key||key.length>MAX_TOOL_ID_LENGTH||key==="__proto__"||key==="constructor"||key==="prototype"||!isValidEntry(entry)){sendInvalidConfig(res,`\`${field}\` must be ${expected}`);return null}output[key]=entry}return output}__name(parseRecordField,"parseRecordField");function rejectIfPresentWrongType(body,key,expected,res){if(!(key in body))return false;if(typeof body[key]===expected)return false;res.status(422).json({error:`\`${key}\` must be a ${expected} when provided`,code:"invalid_config"});return true}__name(rejectIfPresentWrongType,"rejectIfPresentWrongType");function isNoOpUpdate(existing,updates){if(updates.description!==void 0&&updates.description!==existing.description){return false}if(updates.systemPrompt!==void 0&&updates.systemPrompt!==existing.systemPrompt){return false}if(updates.tools!==void 0&&!shallowArrayEqual(updates.tools,existing.tools)){return false}if(updates.disallowedTools!==void 0&&!shallowArrayEqual(updates.disallowedTools,existing.disallowedTools)){return false}if("model"in updates&&updates.model!==existing.model){return false}if("color"in updates&&updates.color!==existing.color){return false}if("approvalMode"in updates&&updates.approvalMode!==existing.approvalMode){return false}if("permissionMode"in updates&&updates.permissionMode!==existing.permissionMode){return false}if("maxTurns"in updates&&updates.maxTurns!==existing.maxTurns){return false}if(updates.mcpServers!==void 0&&!isDeepStrictEqual(normalizedRecord(updates.mcpServers),normalizedRecord(existing.mcpServers))){return false}if(updates.hooks!==void 0&&!isDeepStrictEqual(normalizedRecord(updates.hooks),normalizedRecord(existing.hooks))){return false}if(updates.background!==void 0&&updates.background!==existing.background){return false}if(updates.runConfig!==void 0){const e=existing.runConfig??{};const u=updates.runConfig;if("max_time_minutes"in u){if(u["max_time_minutes"]!==e["max_time_minutes"])return false}if("max_turns"in u){if(u["max_turns"]!==e["max_turns"])return false}}return true}__name(isNoOpUpdate,"isNoOpUpdate");function normalizedRecord(value){if(!value||Object.keys(value).length===0)return void 0;return normalizeRecordValue(value)}__name(normalizedRecord,"normalizedRecord");function normalizeRecordValue(value){if(Array.isArray(value))return value.map(normalizeRecordValue);if(typeof value!=="object"||value===null)return value;return Object.fromEntries(Object.entries(value).filter(([,entry])=>entry!==void 0).map(([key,entry])=>[key,normalizeRecordValue(entry)]))}__name(normalizeRecordValue,"normalizeRecordValue");function shallowArrayEqual(a,b){if(a===b)return true;if(!a||!b)return false;if(a.length!==b.length)return false;for(let i=0;i<a.length;i++)if(a[i]!==b[i])return false;return true}__name(shallowArrayEqual,"shallowArrayEqual");function sanitizeRunConfig(raw,res){if(typeof raw!=="object"||raw===null||Array.isArray(raw)){res.status(422).json({error:"`runConfig` must be an object when provided",code:"invalid_config"});return null}const input=raw;const out={};if("max_time_minutes"in input){const v=input["max_time_minutes"];if(typeof v!=="number"||!Number.isFinite(v)||v<=0){res.status(422).json({error:"`runConfig.max_time_minutes` must be a positive finite number when provided",code:"invalid_config"});return null}out["max_time_minutes"]=v}if("max_turns"in input){const v=input["max_turns"];if(typeof v!=="number"||!Number.isFinite(v)||v<=0||!Number.isInteger(v)){res.status(422).json({error:"`runConfig.max_turns` must be a positive integer when provided",code:"invalid_config"});return null}out["max_turns"]=v}return out}__name(sanitizeRunConfig,"sanitizeRunConfig");function toSummary(config){const summary={kind:"agent",name:config.name,description:config.description,level:config.level,isBuiltin:config.isBuiltin===true||config.level==="builtin",hasTools:Array.isArray(config.tools)&&config.tools.length>0};if(config.tools)summary.tools=[...config.tools];if(config.disallowedTools){summary.disallowedTools=[...config.disallowedTools]}if(config.model)summary.model=config.model;if(config.color)summary.color=config.color;if(config.background!==void 0)summary.background=config.background;if(config.approvalMode)summary.approvalMode=config.approvalMode;if(config.permissionMode)summary.permissionMode=config.permissionMode;if(config.maxTurns!==void 0)summary.maxTurns=config.maxTurns;if(config.mcpServers){summary.mcpServerNames=Object.keys(config.mcpServers)}if(config.hooks)summary.hookEvents=Object.keys(config.hooks);if(config.runConfig){const runConfig={};if(typeof config.runConfig.max_time_minutes==="number"){runConfig.max_time_minutes=config.runConfig.max_time_minutes}if(typeof config.runConfig.max_turns==="number"){runConfig.max_turns=config.runConfig.max_turns}summary.runConfig=runConfig}if(config.extensionName)summary.extensionName=config.extensionName;if(config.filePath)summary.filePath=config.filePath;return summary}__name(toSummary,"toSummary");function toDetail(config){const detail={...toSummary(config),systemPrompt:config.systemPrompt};if(config.mcpServers){detail.mcpServers=redactMcpServersSetting(config.mcpServers)}if(config.hooks)detail.hooks=config.hooks;return detail}__name(toDetail,"toDetail");function createDaemonSubagentManager(boundWorkspace,safeMode=false){const stub={getSdkMode:__name(()=>false,"getSdkMode"),getProjectRoot:__name(()=>boundWorkspace,"getProjectRoot"),getActiveExtensions:__name(()=>[],"getActiveExtensions"),isSafeMode:__name(()=>safeMode,"isSafeMode"),getAgentsSettings:__name(()=>({}),"getAgentsSettings")};const guarded=new Proxy(stub,{get(target,prop){if(prop in target){return target[prop]}if(prop==="then")return void 0;throw new Error(`qwen serve workspace agents: SubagentManager touched Config.${String(prop)} which the daemon stub does not implement. Add it to createDaemonSubagentManager and audit safety.`)},has(target,prop){if(prop in target)return true;if(prop==="then")return false;throw new Error(`qwen serve workspace agents: SubagentManager probed Config.${String(prop)} via 'in' check; the daemon stub does not implement it. Add it to createDaemonSubagentManager and audit safety.`)}});return new SubagentManager(guarded)}__name(createDaemonSubagentManager,"createDaemonSubagentManager");export{mountWorkspaceAgentsRoutes,mountWorkspaceQualifiedAgentsRoutes,toSummary,toDetail,createDaemonSubagentManager};
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{cancelTask,checkReadiness,cleanTask,collectTask,listTasks,retryTask,runPlan}from"./chunk-SZBGWRES.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{collectProviderModelsForProtocol,getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-AMTFJVDD.js";import{loadSettings}from"./chunk-WI4UMN3Q.js";import{normalizeProxyUrl}from"./chunk-Z5XENA4A.js";import{isTlsVerificationDisabled}from"./chunk-ZZZAYAJW.js";import{ignoreBrokenPipe,writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();async function resolveProxy(cliProxy,settingsProxy){const proxyUrl=resolveProxyUrl(cliProxy,settingsProxy);if(proxyUrl){const{EnvHttpProxyAgent,setGlobalDispatcher}=await loadUndici();setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}))}return proxyUrl}__name(resolveProxy,"resolveProxy");function resolveProxyUrl(cliProxy,settingsProxy){return normalizeProxyUrl(cliProxy||settingsProxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"])}__name(resolveProxyUrl,"resolveProxyUrl");var DEFAULT_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1";function resolveEndpoint(env=process.env,options={}){let settings=options.settings??loadSettings().merged;const batch=settings.batch;if(batch?.model||batch?.authType||batch?.baseUrl){if(!batch.model?.trim()){throw new Error("Set batch.model to a modelProviders model ID.")}if(batch.authType&&batch.authType!=="openai"){throw new Error('batch.authType must be "openai" for DashScope Batch.')}const matches=collectProviderModelsForProtocol(settings.modelProviders,settings.providerProtocol,"openai").filter(provider2=>provider2.id===batch.model&&(!batch.baseUrl||provider2.baseUrl===batch.baseUrl));if(matches.length!==1){throw new Error("batch.model must match exactly one chat-completions modelProviders entry; use batch.baseUrl to disambiguate duplicate IDs.")}const provider=matches[0];if(!provider.baseUrl||!provider.envKey||!env[provider.envKey]){throw new Error("The Batch provider needs baseUrl and an envKey with a non-empty value in settings.env or the environment.")}settings={...settings,model:{name:provider.id,baseUrl:provider.baseUrl},modelProviders:{openai:[provider]},security:{auth:{selectedType:"openai"}}};env={[provider.envKey]:env[provider.envKey]}}const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);if(selectedAuthType!=="openai"){throw new Error(`qwen batch needs an API key (auth type "openai") for a DashScope endpoint; current auth type is "${selectedAuthType??"none"}".`)}const{apiKey,baseUrl,model,warnings,authType,generationConfig}=resolveCliGenerationConfig({argv:{},settings,selectedAuthType,env});if(authType!=="openai"){throw new Error(`qwen batch needs a model on the OpenAI-compatible chat-completions wire; "${model||"the configured model"}" resolves to auth type "${authType??"none"}".`)}if(!apiKey){throw new Error("No API key found: set OPENAI_API_KEY or security.auth.apiKey.")}const warn=options.warn??(message=>writeStderrLine(`warning: ${message}`));for(const warning of warnings??[]){warn(warning)}return{apiKey,baseUrl:(baseUrl||DEFAULT_BASE_URL).replace(/\/+$/,""),model,generationConfig}}__name(resolveEndpoint,"resolveEndpoint");async function prepareEndpoint(env=process.env,cliOptions={}){if(cliOptions.insecure)process.env["QWEN_TLS_INSECURE"]="1";if(isTlsVerificationDisabled()&&process.env["NODE_TLS_REJECT_UNAUTHORIZED"]!=="0"){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0";writeStderrLine("WARNING: TLS certificate verification is disabled (--insecure / QWEN_TLS_INSECURE); connections made by this command are vulnerable to man-in-the-middle attacks.")}await resolveProxy(cliOptions.proxy,loadSettings().merged.proxy);return resolveEndpoint(env)}__name(prepareEndpoint,"prepareEndpoint");var cliOptionsOf=__name(argv=>({proxy:argv["proxy"],insecure:argv["insecure"]}),"cliOptionsOf");async function run(fn){try{await fn()}catch(error){writeStderrLine(error instanceof Error?error.message:String(error));process.exitCode=1}await Promise.all([process.stdout,process.stderr].map(stream=>new Promise(resolve=>stream.write("",()=>resolve()))))}__name(run,"run");var LOCK_WAIT_MS=15e3;var workflowDeps=__name(ep=>({ep,cwd:process.cwd(),env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS}),"workflowDeps");var runWorkflowCommand={command:"run <plan>",describe:"Run an agent-prepared batch plan: assemble requests, submit, record the task",builder:__name(yargs=>yargs.positional("plan",{describe:"Plan JSON (usually written by the /batch-api skill): shared rules + source/target items",type:"string",demandOption:true}).option("dry-run",{describe:"Assemble and show items, frozen settings and the estimate without uploading; prints a snapshot digest",type:"boolean",default:false}).option("expect",{describe:"Submit only if the batch still matches this snapshot digest from --dry-run",type:"string"}).check(argv=>argv["dry-run"]&&argv["expect"]!==void 0?"--dry-run and --expect cannot be combined":true),"builder"),handler:__name(argv=>run(async()=>{await runPlan(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["plan"],{dryRun:argv["dry-run"],expect:argv["expect"]})}),"handler")};var collectWorkflowCommand={command:"collect <task-id>",describe:"Collect a workflow task: reconcile, download, validate, and deliver results",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id printed by `qwen batch run`",type:"string",demandOption:true}).option("wait",{describe:"Poll (over HTTP, holding no lock) until the batch settles, then collect",type:"boolean",default:false}).option("timeout",{describe:"Seconds to wait with --wait before giving up (default: none)",type:"number"}).check(argv=>argv["timeout"]===void 0||Number.isFinite(argv["timeout"])&&argv["timeout"]>0?true:"--timeout must be a positive number of seconds"),"builder"),handler:__name(argv=>run(async()=>{await collectTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{wait:argv["wait"],timeoutSeconds:argv["timeout"]})}),"handler")};var retryWorkflowCommand={command:"retry <task-id>",describe:"Resubmit only the failed items of a workflow task",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("max-output-tokens",{describe:"Output limit for the new attempt; required to resend items that were truncated",type:"number"}).check(argv=>argv["max-output-tokens"]===void 0||Number.isInteger(argv["max-output-tokens"])&&argv["max-output-tokens"]>0?true:"--max-output-tokens must be a positive integer"),"builder"),handler:__name(argv=>run(async()=>{await retryTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{maxOutputTokens:argv["max-output-tokens"]})}),"handler")};var cleanWorkflowCommand={command:"clean <task-id>",describe:"Delete a workflow task's local record (cancels nothing; refuses while a batch may be running)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("force",{describe:"Delete even if a batch may still be running or uncollected (it is not cancelled)",type:"boolean",default:false}),"builder"),handler:__name(argv=>run(async()=>{await cleanTask({env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS},argv["task-id"],{force:argv["force"]})}),"handler")};var checkWorkflowCommand={command:"check",describe:"Verify credentials and the Batch route, and show the settings a run would freeze (no billed request)",builder:__name(yargs=>yargs,"builder"),handler:__name(argv=>run(async()=>{await checkReadiness(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))))}),"handler")};var cancelWorkflowCommand={command:"cancel <task-id>",describe:"Cancel a workflow task's active batch (already-completed requests are still billed)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}),"builder"),handler:__name(argv=>run(async()=>{await cancelTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"])}),"handler")};var listWorkflowCommand={command:"list",describe:"List all recorded workflow tasks with their project",builder:__name(yargs=>yargs,"builder"),handler:__name(()=>run(async()=>{ignoreBrokenPipe();await listTasks({env:process.env,out:writeStdoutLine,err:writeStderrLine})}),"handler")};var batchCommand={command:"batch",describe:"Run many independent requests through the DashScope Batch API",builder:__name(yargs=>yargs.command(runWorkflowCommand).command(collectWorkflowCommand).command(retryWorkflowCommand).command(cancelWorkflowCommand).command(listWorkflowCommand).command(checkWorkflowCommand).command(cleanWorkflowCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{resolveProxy,resolveProxyUrl,resolveEndpoint,prepareEndpoint,listWorkflowCommand,batchCommand};
3
+ import{cancelTask,checkReadiness,cleanTask,collectTask,listTasks,retryTask,runPlan}from"./chunk-SZBGWRES.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{collectProviderModelsForProtocol,getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-SAVYMUU3.js";import{loadSettings}from"./chunk-Q5RRVBTY.js";import{normalizeProxyUrl}from"./chunk-T3CQ72HC.js";import{isTlsVerificationDisabled}from"./chunk-ZZZAYAJW.js";import{ignoreBrokenPipe,writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();async function resolveProxy(cliProxy,settingsProxy){const proxyUrl=resolveProxyUrl(cliProxy,settingsProxy);if(proxyUrl){const{EnvHttpProxyAgent,setGlobalDispatcher}=await loadUndici();setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}))}return proxyUrl}__name(resolveProxy,"resolveProxy");function resolveProxyUrl(cliProxy,settingsProxy){return normalizeProxyUrl(cliProxy||settingsProxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"])}__name(resolveProxyUrl,"resolveProxyUrl");var DEFAULT_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1";function resolveEndpoint(env=process.env,options={}){let settings=options.settings??loadSettings().merged;const batch=settings.batch;if(batch?.model||batch?.authType||batch?.baseUrl){if(!batch.model?.trim()){throw new Error("Set batch.model to a modelProviders model ID.")}if(batch.authType&&batch.authType!=="openai"){throw new Error('batch.authType must be "openai" for DashScope Batch.')}const matches=collectProviderModelsForProtocol(settings.modelProviders,settings.providerProtocol,"openai").filter(provider2=>provider2.id===batch.model&&(!batch.baseUrl||provider2.baseUrl===batch.baseUrl));if(matches.length!==1){throw new Error("batch.model must match exactly one chat-completions modelProviders entry; use batch.baseUrl to disambiguate duplicate IDs.")}const provider=matches[0];if(!provider.baseUrl||!provider.envKey||!env[provider.envKey]){throw new Error("The Batch provider needs baseUrl and an envKey with a non-empty value in settings.env or the environment.")}settings={...settings,model:{name:provider.id,baseUrl:provider.baseUrl},modelProviders:{openai:[provider]},security:{auth:{selectedType:"openai"}}};env={[provider.envKey]:env[provider.envKey]}}const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);if(selectedAuthType!=="openai"){throw new Error(`qwen batch needs an API key (auth type "openai") for a DashScope endpoint; current auth type is "${selectedAuthType??"none"}".`)}const{apiKey,baseUrl,model,warnings,authType,generationConfig}=resolveCliGenerationConfig({argv:{},settings,selectedAuthType,env});if(authType!=="openai"){throw new Error(`qwen batch needs a model on the OpenAI-compatible chat-completions wire; "${model||"the configured model"}" resolves to auth type "${authType??"none"}".`)}if(!apiKey){throw new Error("No API key found: set OPENAI_API_KEY or security.auth.apiKey.")}const warn=options.warn??(message=>writeStderrLine(`warning: ${message}`));for(const warning of warnings??[]){warn(warning)}return{apiKey,baseUrl:(baseUrl||DEFAULT_BASE_URL).replace(/\/+$/,""),model,generationConfig}}__name(resolveEndpoint,"resolveEndpoint");async function prepareEndpoint(env=process.env,cliOptions={}){if(cliOptions.insecure)process.env["QWEN_TLS_INSECURE"]="1";if(isTlsVerificationDisabled()&&process.env["NODE_TLS_REJECT_UNAUTHORIZED"]!=="0"){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0";writeStderrLine("WARNING: TLS certificate verification is disabled (--insecure / QWEN_TLS_INSECURE); connections made by this command are vulnerable to man-in-the-middle attacks.")}await resolveProxy(cliOptions.proxy,loadSettings().merged.proxy);return resolveEndpoint(env)}__name(prepareEndpoint,"prepareEndpoint");var cliOptionsOf=__name(argv=>({proxy:argv["proxy"],insecure:argv["insecure"]}),"cliOptionsOf");async function run(fn){try{await fn()}catch(error){writeStderrLine(error instanceof Error?error.message:String(error));process.exitCode=1}await Promise.all([process.stdout,process.stderr].map(stream=>new Promise(resolve=>stream.write("",()=>resolve()))))}__name(run,"run");var LOCK_WAIT_MS=15e3;var workflowDeps=__name(ep=>({ep,cwd:process.cwd(),env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS}),"workflowDeps");var runWorkflowCommand={command:"run <plan>",describe:"Run an agent-prepared batch plan: assemble requests, submit, record the task",builder:__name(yargs=>yargs.positional("plan",{describe:"Plan JSON (usually written by the /batch-api skill): shared rules + source/target items",type:"string",demandOption:true}).option("dry-run",{describe:"Assemble and show items, frozen settings and the estimate without uploading; prints a snapshot digest",type:"boolean",default:false}).option("expect",{describe:"Submit only if the batch still matches this snapshot digest from --dry-run",type:"string"}).check(argv=>argv["dry-run"]&&argv["expect"]!==void 0?"--dry-run and --expect cannot be combined":true),"builder"),handler:__name(argv=>run(async()=>{await runPlan(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["plan"],{dryRun:argv["dry-run"],expect:argv["expect"]})}),"handler")};var collectWorkflowCommand={command:"collect <task-id>",describe:"Collect a workflow task: reconcile, download, validate, and deliver results",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id printed by `qwen batch run`",type:"string",demandOption:true}).option("wait",{describe:"Poll (over HTTP, holding no lock) until the batch settles, then collect",type:"boolean",default:false}).option("timeout",{describe:"Seconds to wait with --wait before giving up (default: none)",type:"number"}).check(argv=>argv["timeout"]===void 0||Number.isFinite(argv["timeout"])&&argv["timeout"]>0?true:"--timeout must be a positive number of seconds"),"builder"),handler:__name(argv=>run(async()=>{await collectTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{wait:argv["wait"],timeoutSeconds:argv["timeout"]})}),"handler")};var retryWorkflowCommand={command:"retry <task-id>",describe:"Resubmit only the failed items of a workflow task",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("max-output-tokens",{describe:"Output limit for the new attempt; required to resend items that were truncated",type:"number"}).check(argv=>argv["max-output-tokens"]===void 0||Number.isInteger(argv["max-output-tokens"])&&argv["max-output-tokens"]>0?true:"--max-output-tokens must be a positive integer"),"builder"),handler:__name(argv=>run(async()=>{await retryTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{maxOutputTokens:argv["max-output-tokens"]})}),"handler")};var cleanWorkflowCommand={command:"clean <task-id>",describe:"Delete a workflow task's local record (cancels nothing; refuses while a batch may be running)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("force",{describe:"Delete even if a batch may still be running or uncollected (it is not cancelled)",type:"boolean",default:false}),"builder"),handler:__name(argv=>run(async()=>{await cleanTask({env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS},argv["task-id"],{force:argv["force"]})}),"handler")};var checkWorkflowCommand={command:"check",describe:"Verify credentials and the Batch route, and show the settings a run would freeze (no billed request)",builder:__name(yargs=>yargs,"builder"),handler:__name(argv=>run(async()=>{await checkReadiness(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))))}),"handler")};var cancelWorkflowCommand={command:"cancel <task-id>",describe:"Cancel a workflow task's active batch (already-completed requests are still billed)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}),"builder"),handler:__name(argv=>run(async()=>{await cancelTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"])}),"handler")};var listWorkflowCommand={command:"list",describe:"List all recorded workflow tasks with their project",builder:__name(yargs=>yargs,"builder"),handler:__name(()=>run(async()=>{ignoreBrokenPipe();await listTasks({env:process.env,out:writeStdoutLine,err:writeStderrLine})}),"handler")};var batchCommand={command:"batch",describe:"Run many independent requests through the DashScope Batch API",builder:__name(yargs=>yargs.command(runWorkflowCommand).command(collectWorkflowCommand).command(retryWorkflowCommand).command(cancelWorkflowCommand).command(listWorkflowCommand).command(checkWorkflowCommand).command(cleanWorkflowCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{resolveProxy,resolveProxyUrl,resolveEndpoint,prepareEndpoint,listWorkflowCommand,batchCommand};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team