gerege-cli 0.26.6 → 0.26.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/bundled/gerege-video/SKILL.md +22 -0
  2. package/bundled/gerege-video/scripts/video.js +137 -0
  3. package/chunks/{MaxSizedBox-QCIXIS4P.js → MaxSizedBox-LUINLOQW.js} +1 -1
  4. package/chunks/{StandaloneSessionPicker-BAFAIRT7.js → StandaloneSessionPicker-B7N4QO5D.js} +1 -1
  5. package/chunks/{acp-subagent-executor-TPVXURLW.js → acp-subagent-executor-J6H6FKUT.js} +1 -1
  6. package/chunks/{acpAgent-67UN66PB.js → acpAgent-XG6SM2VU.js} +3 -3
  7. package/chunks/{advisor-SAXMI4QZ.js → advisor-SZVPQNPA.js} +1 -1
  8. package/chunks/{agent-KV7BXY6C.js → agent-N7QF7BJS.js} +1 -1
  9. package/chunks/{agent-headless-FQX3JGG6.js → agent-headless-GLP5GUEX.js} +1 -1
  10. package/chunks/{agent-host-client-L5EHC4AC.js → agent-host-client-H4VOB3M6.js} +1 -1
  11. package/chunks/{agent-host-connections-EDBMCVQF.js → agent-host-connections-E4C3OC4M.js} +1 -1
  12. package/chunks/{anthropicContentGenerator-V7TX2NXP.js → anthropicContentGenerator-5VTWQLT5.js} +1 -1
  13. package/chunks/{autofix-pr-WP34NYHL.js → autofix-pr-HDYQDJS4.js} +1 -1
  14. package/chunks/{batch-XFVQ4BLM.js → batch-3CRVN5VJ.js} +1 -1
  15. package/chunks/{bridge-AE7AFEXB.js → bridge-NZ6WVBLQ.js} +1 -1
  16. package/chunks/{channel-settings-store-X63P5OVT.js → channel-settings-store-Z7I2JI6M.js} +1 -1
  17. package/chunks/{chunk-BCI62WSL.js → chunk-236DHGNH.js} +1 -1
  18. package/chunks/{chunk-JRTOPEM3.js → chunk-2M3ND5WN.js} +1 -1
  19. package/chunks/{chunk-LBLLWAKK.js → chunk-36A6EXHB.js} +1 -1
  20. package/chunks/{chunk-H3IR3GIE.js → chunk-3ANIQTDT.js} +1 -1
  21. package/chunks/{chunk-GSPGIGO5.js → chunk-3QTR2HAE.js} +3 -3
  22. package/chunks/{chunk-32XHDDIA.js → chunk-3TTHYXT3.js} +1 -1
  23. package/chunks/{chunk-MTDBCIDA.js → chunk-4CE4GMDL.js} +1 -1
  24. package/chunks/{chunk-T2YTHAJW.js → chunk-4FVT657Y.js} +1 -1
  25. package/chunks/{chunk-CGDFZEER.js → chunk-4HSISRRA.js} +1 -1
  26. package/chunks/{chunk-7453BHJO.js → chunk-4SZUJ5RT.js} +1 -1
  27. package/chunks/{chunk-B37YY4XU.js → chunk-57D2OB3I.js} +1 -1
  28. package/chunks/{chunk-WGFX3EL3.js → chunk-5FGBLIXB.js} +1 -1
  29. package/chunks/{chunk-I6PUY2T3.js → chunk-5HX2QGVR.js} +1 -1
  30. package/chunks/{chunk-BPFFRPWE.js → chunk-5ZNXAWOG.js} +6 -6
  31. package/chunks/{chunk-BHIDG6VZ.js → chunk-6CKX56LJ.js} +1 -1
  32. package/chunks/{chunk-GRAECADD.js → chunk-6NIQFWXP.js} +1 -1
  33. package/chunks/{chunk-ELDZ4MNL.js → chunk-6PC6MZHL.js} +1 -1
  34. package/chunks/{chunk-FEP6W4NJ.js → chunk-6VQKGKMJ.js} +1 -1
  35. package/chunks/{chunk-GBSRWT7J.js → chunk-6ZEMLEK2.js} +1 -1
  36. package/chunks/{chunk-4NDJKNN6.js → chunk-72VY2PJA.js} +1 -1
  37. package/chunks/{chunk-BAUMVH4Q.js → chunk-75I3NYBD.js} +1 -1
  38. package/chunks/{chunk-YH2XRWRF.js → chunk-76L7ZDEK.js} +1 -1
  39. package/chunks/{chunk-2JGTWRZJ.js → chunk-7XQ5D34E.js} +6 -6
  40. package/chunks/{chunk-DA6LOBSB.js → chunk-AYX75VXG.js} +1 -1
  41. package/chunks/{chunk-G6DALGGS.js → chunk-BBDFEMCF.js} +1 -1
  42. package/chunks/{chunk-VD2GSW64.js → chunk-BOTX7S66.js} +1 -1
  43. package/chunks/{chunk-M6KB5RVD.js → chunk-CY2QKKZA.js} +1 -1
  44. package/chunks/{chunk-HTAUIJB4.js → chunk-D5JWQUID.js} +1 -1
  45. package/chunks/{chunk-P3JEEDQZ.js → chunk-DMIPB7RZ.js} +1 -1
  46. package/chunks/{chunk-CF6SZJNP.js → chunk-DSKA3P2C.js} +1 -1
  47. package/chunks/{chunk-LTE4N6L3.js → chunk-DVC65H4X.js} +1 -1
  48. package/chunks/{chunk-W5Z4BWWA.js → chunk-DVJSDCMX.js} +1 -1
  49. package/chunks/{chunk-65ME4BOH.js → chunk-E6CPFQX2.js} +1 -1
  50. package/chunks/{chunk-JEDL4IKF.js → chunk-EIFBGEXJ.js} +1 -1
  51. package/chunks/{chunk-AYVCT5FF.js → chunk-EQOHDAYU.js} +1 -1
  52. package/chunks/{chunk-2TAJ5STJ.js → chunk-EZPM4DLR.js} +1 -1
  53. package/chunks/{chunk-JWNKPINR.js → chunk-F6U6T7QD.js} +1 -1
  54. package/chunks/{chunk-ET5M5WFN.js → chunk-FCGFBUHS.js} +1 -1
  55. package/chunks/{chunk-OU7CEG7Q.js → chunk-G2LTZU67.js} +1 -1
  56. package/chunks/{chunk-2N3NBTYJ.js → chunk-GMJSEK4V.js} +1 -1
  57. package/chunks/{chunk-NA4ZF2FE.js → chunk-HJMUBVXZ.js} +2 -2
  58. package/chunks/{chunk-AFO5ER23.js → chunk-HQZTAA2U.js} +1 -1
  59. package/chunks/{chunk-OK7LBM5G.js → chunk-I63TIQOI.js} +1 -1
  60. package/chunks/{chunk-OJ4K62S2.js → chunk-I65LBJN7.js} +1 -1
  61. package/chunks/{chunk-GHIFIXNX.js → chunk-IBDOC27R.js} +1 -1
  62. package/chunks/{chunk-2LWJGXTW.js → chunk-IKF2HWEV.js} +1 -1
  63. package/chunks/{chunk-AEZYXPFS.js → chunk-K6NS2HXT.js} +1 -1
  64. package/chunks/{chunk-T5DKF33F.js → chunk-KTRNYPQP.js} +1 -1
  65. package/chunks/{chunk-SKGJ26HQ.js → chunk-L3ANU5JZ.js} +1 -1
  66. package/chunks/{chunk-U3Q72OGV.js → chunk-LKPMADUO.js} +1 -1
  67. package/chunks/{chunk-MYV7GY3H.js → chunk-M56Y2B6N.js} +1 -1
  68. package/chunks/{chunk-34HC2AXI.js → chunk-N5KRBAK5.js} +2 -2
  69. package/chunks/{chunk-EXIFPXMB.js → chunk-NA2WJPOU.js} +1 -1
  70. package/chunks/{chunk-7RNOS7R4.js → chunk-NGOWLXYK.js} +1 -1
  71. package/chunks/{chunk-IZ5MWA6E.js → chunk-NL7P73ZP.js} +1 -1
  72. package/chunks/{chunk-FYBJGRX7.js → chunk-NS3QR7D3.js} +1 -1
  73. package/chunks/{chunk-XISR37DQ.js → chunk-O5JCCBMQ.js} +1 -1
  74. package/chunks/{chunk-FKL3V5BO.js → chunk-OOKFFZHF.js} +1 -1
  75. package/chunks/{chunk-VRKYBH5G.js → chunk-OTYPLLMT.js} +5 -5
  76. package/chunks/{chunk-W66WWTOP.js → chunk-P7NHWX27.js} +1 -1
  77. package/chunks/{chunk-AEKEZRIU.js → chunk-PC5QZUKR.js} +1 -1
  78. package/chunks/{chunk-NEKPQLFY.js → chunk-PS7MQL57.js} +2 -2
  79. package/chunks/{chunk-TB4AUC2L.js → chunk-PXWHOFAA.js} +1 -1
  80. package/chunks/{chunk-OOJ2AQT3.js → chunk-Q65LVCDR.js} +1 -1
  81. package/chunks/{chunk-EFIRES46.js → chunk-QDUDLELH.js} +1 -1
  82. package/chunks/{chunk-KZNYALFU.js → chunk-QF22ILPV.js} +1 -1
  83. package/chunks/{chunk-MGATL4OA.js → chunk-QW7MAG2E.js} +1 -1
  84. package/chunks/{chunk-KJGRCIVY.js → chunk-RXK6XD6F.js} +1 -1
  85. package/chunks/{chunk-W2RQIZ6B.js → chunk-SVDFCWS7.js} +1 -1
  86. package/chunks/{chunk-P62S5JGM.js → chunk-TKP3GAUI.js} +1 -1
  87. package/chunks/{chunk-BQZF3UKI.js → chunk-TUS74LFI.js} +1 -1
  88. package/chunks/{chunk-JH3V5SPA.js → chunk-U7YGHPSL.js} +1 -1
  89. package/chunks/{chunk-NONBHCXP.js → chunk-UB37RBSK.js} +1 -1
  90. package/chunks/{chunk-T53VMDXH.js → chunk-UK5SIRH4.js} +1 -1
  91. package/chunks/{chunk-3W32X2DH.js → chunk-UTTSBCFR.js} +1 -1
  92. package/chunks/{chunk-RSLTOIG5.js → chunk-UYV4ZVXY.js} +2 -2
  93. package/chunks/{chunk-FKZ46GKL.js → chunk-VC3JJL7E.js} +1 -1
  94. package/chunks/{chunk-SP6CQ3MO.js → chunk-VKWVIWLK.js} +1 -1
  95. package/chunks/{chunk-N7PWZBXV.js → chunk-VUI6STKU.js} +1 -1
  96. package/chunks/{chunk-5EXL4TKQ.js → chunk-W3YXE55M.js} +1 -1
  97. package/chunks/{chunk-NVOI6UDQ.js → chunk-WAIPC47V.js} +1 -1
  98. package/chunks/{chunk-QDCUR3JB.js → chunk-WMJ6UHDP.js} +1 -1
  99. package/chunks/{chunk-CBE6ZIHU.js → chunk-WZU2ECUD.js} +1 -1
  100. package/chunks/{chunk-ZENMAISJ.js → chunk-XAGIZY2Y.js} +1 -1
  101. package/chunks/{chunk-RXN7DUMP.js → chunk-XGZYVULJ.js} +2 -2
  102. package/chunks/{chunk-HOG66S6K.js → chunk-XJIHDVPX.js} +1 -1
  103. package/chunks/{chunk-UKLXKJKL.js → chunk-XVDIHFRH.js} +1 -1
  104. package/chunks/{chunk-76FSYQTG.js → chunk-YMEW4TTT.js} +1 -1
  105. package/chunks/{chunk-EYPLBTMI.js → chunk-Z32URWBG.js} +1 -1
  106. package/chunks/{chunk-CUP2TNJK.js → chunk-Z6HRXHJP.js} +1 -1
  107. package/chunks/{chunk-MPVQDYPH.js → chunk-ZO4F6ZWR.js} +1 -1
  108. package/chunks/{codex-subagent-executor-OLMGVPVS.js → codex-subagent-executor-DDKYNU42.js} +1 -1
  109. package/chunks/{config-utils-OWY5G5Y2.js → config-utils-S7Z2ZZ2E.js} +1 -1
  110. package/chunks/{contextCommand-IXFUZH65.js → contextCommand-7F4PGV2A.js} +1 -1
  111. package/chunks/{core-runtime-O4LC4NY3.js → core-runtime-LBH3U7ZF.js} +1 -1
  112. package/chunks/{create-sub-session-6F7C3TMT.js → create-sub-session-56DS2T6L.js} +1 -1
  113. package/chunks/{cron-create-2422NBSJ.js → cron-create-PBP3C46Q.js} +1 -1
  114. package/chunks/{daemon-git-worktree-guard-EWPQA6NO.js → daemon-git-worktree-guard-WJS6FBDA.js} +1 -1
  115. package/chunks/{daemon-status-provider-FAHOXNFW.js → daemon-status-provider-UPPAEHJ6.js} +1 -1
  116. package/chunks/{daemon-trust-policy-L3DM6AI5.js → daemon-trust-policy-4Z5HSNUX.js} +1 -1
  117. package/chunks/{daemon-trust-policy-monitor-HNPY5KJ4.js → daemon-trust-policy-monitor-WFWDOYX3.js} +1 -1
  118. package/chunks/{deferred-core-runtime-JF42NQJK.js → deferred-core-runtime-MJYNEA4N.js} +1 -1
  119. package/chunks/{edit-E5LEI2LL.js → edit-U7TGKKK3.js} +1 -1
  120. package/chunks/{enterPlanMode-3COTUV5V.js → enterPlanMode-27HC5AXN.js} +1 -1
  121. package/chunks/{environment-XBBIB3VA.js → environment-PHWY6C4P.js} +1 -1
  122. package/chunks/{errors-LNMQ7TUK.js → errors-F2EYYFI3.js} +1 -1
  123. package/chunks/{execution-tool-QDDKJD2K.js → execution-tool-O4KJ5SMM.js} +1 -1
  124. package/chunks/{execution-worker-TXGZRZXE.js → execution-worker-AMFXZ7JD.js} +1 -1
  125. package/chunks/{exitPlanMode-Z7QEMWPE.js → exitPlanMode-LDYL43PB.js} +1 -1
  126. package/chunks/{fast-path-M6K2RACY.js → fast-path-HTODEVOR.js} +1 -1
  127. package/chunks/{glob-N2QT4U7U.js → glob-NKQJJZND.js} +1 -1
  128. package/chunks/{goal-tools-CUSQD3DG.js → goal-tools-47I455VV.js} +1 -1
  129. package/chunks/{handleAutoUpdate-QF2YQHF6.js → handleAutoUpdate-MJKTDJUO.js} +1 -1
  130. package/chunks/{i18n-AGOA6MUI.js → i18n-TCOB4TC5.js} +1 -1
  131. package/chunks/{initializer-FRKYDUSX.js → initializer-NLYOGZZS.js} +1 -1
  132. package/chunks/{installationInfo-OKA4WXAS.js → installationInfo-TF2RSJOG.js} +1 -1
  133. package/chunks/{interactive-mod-session-MWYN5IFK.js → interactive-mod-session-5F7R3KSA.js} +1 -1
  134. package/chunks/{list-DE7VUIR2.js → list-U2AEVLFP.js} +1 -1
  135. package/chunks/{llm-N3JGJHYC.js → llm-EV2QTQBU.js} +4 -4
  136. package/chunks/{llm-content-generator-VMUBA7OJ.js → llm-content-generator-ZXUSPPG2.js} +1 -1
  137. package/chunks/{loadedSettingsAdapter-5C36OZ7N.js → loadedSettingsAdapter-TLRI22X7.js} +1 -1
  138. package/chunks/{local-BE624O3A.js → local-ZTSBSKWV.js} +1 -1
  139. package/chunks/{local-execution-environment-OPGM7Y6L.js → local-execution-environment-F263PSIM.js} +1 -1
  140. package/chunks/{loggingContentGenerator-2MHAI6JR.js → loggingContentGenerator-2XHSIJQD.js} +1 -1
  141. package/chunks/{loop-wakeup-BDLATBXH.js → loop-wakeup-5ET3JHUT.js} +1 -1
  142. package/chunks/{manage-memory-BBCEIIWB.js → manage-memory-MJEQ47H2.js} +1 -1
  143. package/chunks/{managed-execution-engine-SRFALTCX.js → managed-execution-engine-ODPR5OEH.js} +1 -1
  144. package/chunks/{managed-local-serve-ICNAS3E6.js → managed-local-serve-S5R4Z5OL.js} +1 -1
  145. package/chunks/managed-npm-update-BUI5APGY.js +8 -0
  146. package/chunks/{managed-runtime-attestation-worker-ZRDWKXCI.js → managed-runtime-attestation-worker-BQP4E7LQ.js} +1 -1
  147. package/chunks/{managed-runtime-bootstrap-6NTGZXQL.js → managed-runtime-bootstrap-SRBDFSKK.js} +1 -1
  148. package/chunks/{managed-runtime-session-worker-RKQBBFR6.js → managed-runtime-session-worker-UI23BTYJ.js} +1 -1
  149. package/chunks/{managed-runtime-ssh-worker-FCGV6FSW.js → managed-runtime-ssh-worker-HU4CIJRK.js} +1 -1
  150. package/chunks/{managed-session-authority-C7IW6TJX.js → managed-session-authority-XSSTLAEY.js} +1 -1
  151. package/chunks/{mcp-VC4CJPE5.js → mcp-WLHDOKP7.js} +1 -1
  152. package/chunks/{memory-S6OJA3ZD.js → memory-OUUHPSDD.js} +1 -1
  153. package/chunks/{model-call-collection-MJZWRQSU.js → model-call-collection-4A2EB76B.js} +1 -1
  154. package/chunks/{model-configuration-SKU6L3QI.js → model-configuration-4CGUFKEP.js} +1 -1
  155. package/chunks/{modelConfigUtils-TJCB6NXT.js → modelConfigUtils-HUEERWBA.js} +1 -1
  156. package/chunks/{monitor-M3PNLCYP.js → monitor-FXL5UNMP.js} +1 -1
  157. package/chunks/{nonInteractiveCli-MR7JLAWU.js → nonInteractiveCli-W7M2O43W.js} +1 -1
  158. package/chunks/{nonInteractiveToolExecutor-YKA6JMTY.js → nonInteractiveToolExecutor-EMLI363Q.js} +1 -1
  159. package/chunks/{notebook-edit-ENTFB5D7.js → notebook-edit-R5RSLSSH.js} +1 -1
  160. package/chunks/{omni-6YBX4R6K.js → omni-DNZGITTE.js} +1 -1
  161. package/chunks/{openaiContentGenerator-XRXX33FY.js → openaiContentGenerator-PKOPYMHR.js} +1 -1
  162. package/chunks/{openaiResponsesContentGenerator-L6ONEHMR.js → openaiResponsesContentGenerator-MHH2MF3V.js} +1 -1
  163. package/chunks/{pidfile-XR4JF2Z6.js → pidfile-5ZNJWMKG.js} +1 -1
  164. package/chunks/{processUtils-GQYNJRBJ.js → processUtils-JIHQDASW.js} +1 -1
  165. package/chunks/{prompt-terminal-ledger-7BM7YDLG.js → prompt-terminal-ledger-L3LZ5SLR.js} +1 -1
  166. package/chunks/{qwenContentGenerator-QSA32XEL.js → qwenContentGenerator-QCZL7HJJ.js} +1 -1
  167. package/chunks/{reactive-degrade-TFNBAAPZ.js → reactive-degrade-YUXOUQG4.js} +1 -1
  168. package/chunks/{read-file-VD7OFO2E.js → read-file-FBNU3AVX.js} +1 -1
  169. package/chunks/{resumeHistoryUtils-2B4KPI7G.js → resumeHistoryUtils-5FPRTI4A.js} +1 -1
  170. package/chunks/{review-C365WGCW.js → review-NLFYSNM3.js} +1 -1
  171. package/chunks/{ripGrep-D7WPMBXR.js → ripGrep-JUAPC5LD.js} +1 -1
  172. package/chunks/{run-qwen-serve-NZWQHWQA.js → run-qwen-serve-JP64UQ3Y.js} +1 -1
  173. package/chunks/{runtime-J6SPBSCS.js → runtime-D2QUYM6U.js} +1 -1
  174. package/chunks/{sandboxConfig-QS2XBPZG.js → sandboxConfig-7VZJQV6H.js} +1 -1
  175. package/chunks/{scheduled-tasks-YNNIOOPM.js → scheduled-tasks-PC6EH75E.js} +1 -1
  176. package/chunks/{scheduler-KCMSPHON.js → scheduler-RUV2FNDR.js} +1 -1
  177. package/chunks/{search-memory-EUBJ7IAV.js → search-memory-YJTJ7BRU.js} +1 -1
  178. package/chunks/{send-message-CWWZUPSK.js → send-message-EEEFFTHX.js} +1 -1
  179. package/chunks/{serve-4CB4BWJ5.js → serve-KMIZDYON.js} +1 -1
  180. package/chunks/{server-JNANUIGC.js → server-DUPK3V7B.js} +3 -3
  181. package/chunks/{session-3LQLXPUA.js → session-CW5YMFMP.js} +1 -1
  182. package/chunks/{session-attachments-root-BWIVWFHJ.js → session-attachments-root-5H5GFHLI.js} +1 -1
  183. package/chunks/{session-execution-engine-selector-5OLRX57L.js → session-execution-engine-selector-MVXM2HZW.js} +1 -1
  184. package/chunks/{session-pr-refresh-RLF3EXS3.js → session-pr-refresh-4UPONX4L.js} +1 -1
  185. package/chunks/{sessionService-U7ACD2HP.js → sessionService-GGCYISSL.js} +1 -1
  186. package/chunks/{settings-FTGWYTUH.js → settings-AASJCESS.js} +1 -1
  187. package/chunks/{shell-E4RENYQC.js → shell-V4WWLW3Q.js} +1 -1
  188. package/chunks/{skill-OLNPHRWB.js → skill-NDEBB7VX.js} +1 -1
  189. package/chunks/{skill-settings-R2BV2GEK.js → skill-settings-YAI3GYU5.js} +1 -1
  190. package/chunks/{spawnChannel-LOPAR5T2.js → spawnChannel-6JKVJAXZ.js} +1 -1
  191. package/chunks/{standalone-update-IGDX2RGN.js → standalone-update-NJP5OCKJ.js} +1 -1
  192. package/chunks/{start-opentui-ui-33QLBNRC.js → start-opentui-ui-M4B4SXRM.js} +1 -1
  193. package/chunks/{startInteractiveUI-RQKHD7MM.js → startInteractiveUI-O4JUDEAU.js} +1 -1
  194. package/chunks/{team-create-HAVKHNU5.js → team-create-NLJ7QBLD.js} +1 -1
  195. package/chunks/{team-plan-approval-7MCQX67C.js → team-plan-approval-XKYPVWNG.js} +1 -1
  196. package/chunks/{terminal-image-renderer-XT5JVEO6.js → terminal-image-renderer-47TD747D.js} +1 -1
  197. package/chunks/{theme-manager-DR5EYGLT.js → theme-manager-AANEBPLJ.js} +1 -1
  198. package/chunks/{tool-call-LZHZ5RVH.js → tool-call-ETH3LS7Y.js} +1 -1
  199. package/chunks/{tool-result-media-XCXCF4YC.js → tool-result-media-EFOEPAF2.js} +1 -1
  200. package/chunks/{tool-search-K6S3ON7M.js → tool-search-J3CF5PRN.js} +1 -1
  201. package/chunks/{total-session-admission-LGSS2VWS.js → total-session-admission-3DC52PLQ.js} +1 -1
  202. package/chunks/{trustedFolders-IIR2UZRL.js → trustedFolders-4KPWZZKB.js} +1 -1
  203. package/chunks/{update-relaunch-WVIFX5CN.js → update-relaunch-A67BS7QS.js} +1 -1
  204. package/chunks/{updateCheck-CMEWLLZJ.js → updateCheck-X623JRSY.js} +1 -1
  205. package/chunks/{upload-config-TCCFCNCD.js → upload-config-X2CR3F26.js} +1 -1
  206. package/chunks/{useAutoAcceptIndicator-5RTTH3OW.js → useAutoAcceptIndicator-INIOQGJH.js} +1 -1
  207. package/chunks/{validateNonInterActiveAuth-AO336KDX.js → validateNonInterActiveAuth-XJ2U5CLB.js} +1 -1
  208. package/chunks/{version-JYWKKMNP.js → version-MFHRMM7W.js} +1 -1
  209. package/chunks/{web-fetch-HWTAWXFM.js → web-fetch-3GEJ62DH.js} +1 -1
  210. package/chunks/{web-search-HAI5LW3G.js → web-search-WJZO3Q3A.js} +1 -1
  211. package/chunks/{workflow-BZ2YFGF6.js → workflow-ML7ITCMH.js} +1 -1
  212. package/chunks/{workflow-ancestor-trust-26TFXFPO.js → workflow-ancestor-trust-M3VFMS73.js} +1 -1
  213. package/chunks/{workspace-agents-DLI4JQJZ.js → workspace-agents-YFZMV7EF.js} +1 -1
  214. package/chunks/{workspace-providers-status-64C7DJZU.js → workspace-providers-status-3COKLBCI.js} +1 -1
  215. package/chunks/{workspace-recovery-worker-IFRT3KKP.js → workspace-recovery-worker-QURA3WFZ.js} +1 -1
  216. package/chunks/{workspace-registration-store-MYKJM2SK.js → workspace-registration-store-F3AGIOBW.js} +1 -1
  217. package/chunks/{workspace-registry-GZJRONAY.js → workspace-registry-QUBL3RW6.js} +1 -1
  218. package/chunks/{workspace-runtime-coordinator-44KW6HSN.js → workspace-runtime-coordinator-22TSDHXX.js} +1 -1
  219. package/chunks/{workspace-service-YHTSZYYD.js → workspace-service-UUENTHNO.js} +1 -1
  220. package/chunks/{workspace-skills-status-NEB62X24.js → workspace-skills-status-NNQQBBCJ.js} +1 -1
  221. package/chunks/{workspace-trust-reconciler-HZLOOZWM.js → workspace-trust-reconciler-3CMMNCGG.js} +1 -1
  222. package/chunks/{write-file-HD5LHXGL.js → write-file-DEAFIK4C.js} +1 -1
  223. package/chunks/{zoom-image-W4BMRC5T.js → zoom-image-YYO22PQG.js} +1 -1
  224. package/cli-entry.js +2 -3
  225. package/cli.js +2 -2
  226. package/execution-worker.js +1 -1
  227. package/export-transcript-document.js +1 -1
  228. package/gerege.mjs +11 -0
  229. package/package.json +2 -12
  230. package/chunks/managed-npm-update-CTL6LH5Z.js +0 -8
  231. package/opentui-assets/@opentui/core/assets/javascript/highlights.scm +0 -205
  232. package/opentui-assets/@opentui/core/assets/javascript/tree-sitter-javascript.wasm +0 -0
  233. package/opentui-assets/@opentui/core/assets/markdown/highlights.scm +0 -150
  234. package/opentui-assets/@opentui/core/assets/markdown/injections.scm +0 -27
  235. package/opentui-assets/@opentui/core/assets/markdown/tree-sitter-markdown.wasm +0 -0
  236. package/opentui-assets/@opentui/core/assets/markdown_inline/highlights.scm +0 -115
  237. package/opentui-assets/@opentui/core/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
  238. package/opentui-assets/@opentui/core/assets/typescript/highlights.scm +0 -604
  239. package/opentui-assets/@opentui/core/assets/typescript/tree-sitter-typescript.wasm +0 -0
  240. package/opentui-assets/@opentui/core/assets/zig/highlights.scm +0 -284
  241. package/opentui-assets/@opentui/core/assets/zig/tree-sitter-zig.wasm +0 -0
  242. package/opentui-assets/@opentui/core/parser.worker.js +0 -4566
  243. package/opentui-assets/@opentui/core-darwin-arm64/libopentui.dylib +0 -0
  244. package/opentui-assets/@opentui/core-darwin-x64/libopentui.dylib +0 -0
  245. package/opentui-assets/@opentui/core-linux-arm64/libopentui.so +0 -0
  246. package/opentui-assets/@opentui/core-linux-x64/libopentui.so +0 -0
  247. package/opentui-assets/web-tree-sitter/tree-sitter.wasm +0 -0
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{redactMcpServersSetting,restoreRedactedMcpServersSetting}from"./chunk-44U2VNWI.js";import{safeLogValue}from"./chunk-SVGTUGV2.js";import{requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeFromParam,sendGenerationClosedError}from"./chunk-TB4AUC2L.js";import{STATUS_SCHEMA_VERSION}from"./chunk-LUDNUVSA.js";import{isServeDebugMode}from"./chunk-CUNEBE5E.js";import{loadSettings}from"./chunk-2TAJ5STJ.js";import{BuiltinAgentRegistry,SubagentManager}from"./chunk-2JGTWRZJ.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-PXWHOFAA.js";import{STATUS_SCHEMA_VERSION}from"./chunk-LUDNUVSA.js";import{isServeDebugMode}from"./chunk-CUNEBE5E.js";import{loadSettings}from"./chunk-EZPM4DLR.js";import{BuiltinAgentRegistry,SubagentManager}from"./chunk-7XQ5D34E.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{registerCleanup}from"./chunk-AYVCT5FF.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var MAX_PROFILES=5;var RATE_LIMIT_MS=3e4;var MIN_FREE_BYTES_AFTER_WRITE=256*1024*1024;var DEFAULT_SAMPLING_INTERVAL_US=1e3;var ESTIMATED_PROFILE_BYTES=10*1024*1024;var state="idle";var session=null;var initialized=false;var signalHandlerRegistered=false;var lastWriteByDir=new Map;function initCpuProfiler(){if(initialized)return;initialized=true;registerSignalHandler();registerCleanup(async()=>{if(state==="recording"){const result=await stopCpuProfile();if(result.ok){process.stderr.write(`[cpu-profiler] Profile written: ${result.filePath}
3
+ import{registerCleanup}from"./chunk-EQOHDAYU.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var MAX_PROFILES=5;var RATE_LIMIT_MS=3e4;var MIN_FREE_BYTES_AFTER_WRITE=256*1024*1024;var DEFAULT_SAMPLING_INTERVAL_US=1e3;var ESTIMATED_PROFILE_BYTES=10*1024*1024;var state="idle";var session=null;var initialized=false;var signalHandlerRegistered=false;var lastWriteByDir=new Map;function initCpuProfiler(){if(initialized)return;initialized=true;registerSignalHandler();registerCleanup(async()=>{if(state==="recording"){const result=await stopCpuProfile();if(result.ok){process.stderr.write(`[cpu-profiler] Profile written: ${result.filePath}
4
4
  `)}}});const enabled=process.env["QWEN_CODE_CPU_PROFILE"]==="1";if(!enabled)return;void startCpuProfile().then(result=>{if(!result.ok){process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}
5
5
  `)}})}__name(initCpuProfiler,"initCpuProfiler");async function startCpuProfile(opts){if(state!=="idle"){return{ok:false,error:state==="recording"?"CPU profiling is already in progress.":"CPU profiler is currently stopping. Please wait a moment and try again."}}state="recording";try{const inspectorSession=await getOrCreateSession();await inspectorSession.post("Profiler.enable");await inspectorSession.post("Profiler.setSamplingInterval",{interval:opts?.samplingInterval??DEFAULT_SAMPLING_INTERVAL_US});await inspectorSession.post("Profiler.start");return{ok:true}}catch(error){state="idle";disconnectSession();return{ok:false,error:formatError(error)}}}__name(startCpuProfile,"startCpuProfile");async function stopCpuProfile(options){if(state!=="recording"){return{ok:false,error:state==="idle"?"CPU profiler is not recording.":"CPU profiler is already stopping."}}const outputDir=options?.outputDir??defaultOutputDir();const now=options?.now??new Date;const rateLimitMs=options?.rateLimitMs??RATE_LIMIT_MS;const maxProfiles=options?.maxProfiles??MAX_PROFILES;try{enforceRateLimit(outputDir,now,rateLimitMs)}catch(error){state="idle";if(session){session.post("Profiler.stop").catch(()=>{});session.post("Profiler.disable").catch(()=>{})}disconnectSession();return{ok:false,error:formatError(error)}}state="stopping";try{if(!session){throw new Error("Inspector session lost unexpectedly during Profiler.stop; the profile data could not be retrieved.")}const result=await session.post("Profiler.stop");if(!result.profile){throw new Error("V8 Profiler.stop returned an empty profile; recording may have been interrupted.")}await session.post("Profiler.disable");fs.mkdirSync(outputDir,{recursive:true,mode:448});try{fs.chmodSync(outputDir,448)}catch{}checkDiskSpace(outputDir);const filePath=path.join(outputDir,`qwen-code-cpu-${process.pid}-${formatTimestamp(now)}.cpuprofile`);try{fs.writeFileSync(filePath,JSON.stringify(result.profile),{mode:384})}catch(writeError){try{fs.rmSync(filePath,{force:true})}catch{}throw writeError}recordWrite(outputDir,now);cleanupOldProfiles(outputDir,maxProfiles);state="idle";return{ok:true,filePath}}catch(error){state="idle";disconnectSession();return{ok:false,error:formatError(error)}}}__name(stopCpuProfile,"stopCpuProfile");function isCpuProfileRecording(){return state==="recording"}__name(isCpuProfileRecording,"isCpuProfileRecording");function registerSignalHandler(){if(signalHandlerRegistered)return;if(process.platform==="win32")return;signalHandlerRegistered=true;process.on("SIGUSR1",handleSigusr1)}__name(registerSignalHandler,"registerSignalHandler");function defaultOutputDir(){return path.join(os.homedir(),".qwen","cpu-profiles")}__name(defaultOutputDir,"defaultOutputDir");function formatTimestamp(now){return now.toISOString().replace(/[:.]/g,"-")}__name(formatTimestamp,"formatTimestamp");function formatError(error){return error instanceof Error?error.message:String(error)}__name(formatError,"formatError");var sessionFactory=null;async function getOrCreateSession(){if(session)return session;if(sessionFactory){session=await sessionFactory();return session}const inspectorModule=await import("node:inspector/promises");const newSession=new inspectorModule.Session;newSession.connect();session=newSession;return session}__name(getOrCreateSession,"getOrCreateSession");function disconnectSession(){if(session){try{session.disconnect()}catch{}session=null}}__name(disconnectSession,"disconnectSession");function handleSigusr1(){if(state==="idle"){void startCpuProfile().then(result=>{if(result.ok){process.stderr.write(`[cpu-profiler] Recording started (PID ${process.pid}). Send SIGUSR1 again to stop.
6
6
  `)}else{process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{readConfigFile}from"./chunk-2TAJ5STJ.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-DOLUT3XC.js";import{normalizeClaudeMcpServer}from"./chunk-2JGTWRZJ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var PROJECT_MCP_FILENAME=".mcp.json";function loadProjectMcpServers(projectRoot,options={}){const filePath=path.join(projectRoot,PROJECT_MCP_FILENAME);let raw;try{raw=options.strict?readConfigFile(filePath):fs.readFileSync(filePath,"utf-8")}catch(e){if(!options.strict)return{servers:{},path:void 0,errors:[]};return{servers:{},path:filePath,errors:[`Failed to read ${filePath}: ${e.message}`]}}if(raw===void 0)return{servers:{},path:void 0,errors:[]};let parsed;try{parsed=JSON.parse((0,import_strip_json_comments.default)(stripUtf8Bom(raw)))}catch(e){return{servers:{},path:filePath,errors:[`Failed to parse ${filePath}: ${e.message}`]}}const mcpServers=parsed?.mcpServers;if(!mcpServers||typeof mcpServers!=="object"||Array.isArray(mcpServers)){return{servers:{},path:filePath,errors:[`${filePath} has no "mcpServers" object`]}}const servers=Object.create(null);const errors=[];for(const[name,value]of Object.entries(mcpServers)){if(!value||typeof value!=="object"||Array.isArray(value)){errors.push(`${filePath}: server "${name}" is not an object \u2014 skipped`);continue}servers[name]={...normalizeClaudeMcpServer(value),scope:"project"}}return{servers,path:filePath,errors}}__name(loadProjectMcpServers,"loadProjectMcpServers");export{loadProjectMcpServers};
3
+ import{readConfigFile}from"./chunk-EZPM4DLR.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-DOLUT3XC.js";import{normalizeClaudeMcpServer}from"./chunk-7XQ5D34E.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var PROJECT_MCP_FILENAME=".mcp.json";function loadProjectMcpServers(projectRoot,options={}){const filePath=path.join(projectRoot,PROJECT_MCP_FILENAME);let raw;try{raw=options.strict?readConfigFile(filePath):fs.readFileSync(filePath,"utf-8")}catch(e){if(!options.strict)return{servers:{},path:void 0,errors:[]};return{servers:{},path:filePath,errors:[`Failed to read ${filePath}: ${e.message}`]}}if(raw===void 0)return{servers:{},path:void 0,errors:[]};let parsed;try{parsed=JSON.parse((0,import_strip_json_comments.default)(stripUtf8Bom(raw)))}catch(e){return{servers:{},path:filePath,errors:[`Failed to parse ${filePath}: ${e.message}`]}}const mcpServers=parsed?.mcpServers;if(!mcpServers||typeof mcpServers!=="object"||Array.isArray(mcpServers)){return{servers:{},path:filePath,errors:[`${filePath} has no "mcpServers" object`]}}const servers=Object.create(null);const errors=[];for(const[name,value]of Object.entries(mcpServers)){if(!value||typeof value!=="object"||Array.isArray(value)){errors.push(`${filePath}: server "${name}" is not an object \u2014 skipped`);continue}servers[name]={...normalizeClaudeMcpServer(value),scope:"project"}}return{servers,path:filePath,errors}}__name(loadProjectMcpServers,"loadProjectMcpServers");export{loadProjectMcpServers};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{effectiveSessionScope,multiSessionCompatibilityError,parseMessageRoutingConfig,parseSessionRotationConfig}from"./chunk-MMQY4FJL.js";import{UNSAFE_OBJECT_KEYS,getPlugin}from"./chunk-NY56CL2X.js";import{CHANNEL_OUTPUT_MODE_FIELD,parseChannelOutputMode}from"./chunk-QN7NYEE3.js";import{loadSettings,saveSettings}from"./chunk-2TAJ5STJ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import{isDeepStrictEqual}from"node:util";var ChannelSettingsError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="ChannelSettingsError"}static{__name(this,"ChannelSettingsError")}};function revisionOf(channels,startupNames){return createHash("sha256").update(JSON.stringify({channels,startupNames})).digest("hex")}__name(revisionOf,"revisionOf");function applySecretUpdate(current,update){validateSecretUpdate(update);if(update.operation==="preserve")return current;if(update.operation==="clear")return void 0;if(typeof update.value!=="string"||update.value.length===0){throw invalidSecret("Secret replacements must be non-empty strings.")}return update.value}__name(applySecretUpdate,"applySecretUpdate");function invalidSecret(message){return new ChannelSettingsError("channel_settings_invalid_secret",message)}__name(invalidSecret,"invalidSecret");function invalidConfig(message){return new ChannelSettingsError("channel_settings_invalid_config",message)}__name(invalidConfig,"invalidConfig");function assertSafeChannelName(name){if(UNSAFE_OBJECT_KEYS.has(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is not allowed.`)}}__name(assertSafeChannelName,"assertSafeChannelName");function assertUpsertChannelName(name){assertSafeChannelName(name);if(isAllStartupName(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is reserved for startup selection.`)}}__name(assertUpsertChannelName,"assertUpsertChannelName");function isAllStartupName(name){return name.trim()==="all"}__name(isAllStartupName,"isAllStartupName");function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord,"isRecord");function isEnvironmentReference(value){return/^\$[A-Za-z_][A-Za-z0-9_]*$/.test(value)}__name(isEnvironmentReference,"isEnvironmentReference");function assertStringRecord(key,value,allowedKeys){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){if(!allowedKeys.has(nestedKey)||typeof nestedValue!=="string"){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}}__name(assertStringRecord,"assertStringRecord");function assertSharedField(key,value,previous){if(key==="messageRoutes"||key==="defaultMessageRoute"){return true}if(key==="multiSession"){if(typeof value!=="boolean"){throw invalidConfig(`Channel field "${key}" must be a boolean.`)}return true}if(key==="sessionRotation"){try{parseSessionRotationConfig("settings",value)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}return true}if(key==="groupSenderPolicy"||key==="allowedGroupUsers"){throw invalidConfig(`Channel field "${key}" moved to groups["*"].${key==="groupSenderPolicy"?"senders":"allowedUsers"}.`)}const enumValues={privatePolicy:new Set(["disabled","allowlist","pairing","open"]),senderPolicy:new Set(["allowlist","pairing","open"]),dmPolicy:new Set(["open","disabled"]),groupPolicy:new Set(["disabled","allowlist","pairing","open"]),sessionScope:new Set(["user","thread","chat_thread","single"]),dispatchMode:new Set(["steer","followup","collect"])};if(Object.hasOwn(enumValues,key)){if(typeof value!=="string"||!enumValues[key].has(value)){throw invalidConfig(`Channel field "${key}" has an invalid value.`)}return true}if(["model","cwd","approvalMode","instructions"].includes(key)){if(typeof value!=="string"){throw invalidConfig(`Channel field "${key}" must be a string.`)}return true}if(key==="allowedUsers"||key==="operators"){if(!Array.isArray(value)||value.some(item=>typeof item!=="string")){throw invalidConfig(`Channel field "${key}" must be a string array.`)}return true}if(key==="groups"){if(!isRecord(value)){if(containsUnsafeObjectKey(value)||!isDeepStrictEqual(previous,value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}return true}const previousGroups=isRecord(previous)?previous:{};for(const[groupId,groupConfig]of Object.entries(value)){if(UNSAFE_OBJECT_KEYS.has(groupId)||!isRecord(groupConfig)){throw invalidConfig(`Channel field "${key}.${groupId}" is invalid.`)}const previousGroup=isRecord(previousGroups[groupId])?previousGroups[groupId]:{};for(const[nestedKey,nestedValue]of Object.entries(groupConfig)){const known=["requireMention","dispatchMode","groupHistoryLimit","senders","allowedUsers"].includes(nestedKey);const valid=nestedKey==="requireMention"&&typeof nestedValue==="boolean"||nestedKey==="dispatchMode"&&typeof nestedValue==="string"&&["collect","steer","followup"].includes(nestedValue)||nestedKey==="groupHistoryLimit"&&typeof nestedValue==="number"&&Number.isFinite(nestedValue)||nestedKey==="senders"&&typeof nestedValue==="string"&&["open","allowlist"].includes(nestedValue)||nestedKey==="allowedUsers"&&Array.isArray(nestedValue)&&nestedValue.every(item=>typeof item==="string");if(known&&!valid&&!(nestedKey!=="senders"&&Object.hasOwn(previousGroup,nestedKey)&&isDeepStrictEqual(previousGroup[nestedKey],nestedValue)&&!containsUnsafeObjectKey(nestedValue))){throw invalidConfig(`Channel field "${key}.${groupId}.${nestedKey}" is invalid.`)}if(!known){assertPreservedUnknownField(`${key}.${groupId}`,nestedKey,nestedValue,previousGroup)}}}return true}if(key==="groupHistoryLimit"){if(typeof value!=="number"||!Number.isFinite(value)){throw invalidConfig(`Channel field "${key}" must be a number.`)}return true}if(key==="identity"){assertStringRecord(key,value,new Set(["id","displayName","description"]));return true}if(key==="memoryScope"){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){const valid=nestedKey==="namespace"&&typeof nestedValue==="string"||nestedKey==="mode"&&nestedValue==="metadata-only";if(!valid){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}return true}return false}__name(assertSharedField,"assertSharedField");function containsUnsafeObjectKey(value){if(Array.isArray(value)){return value.some(item=>containsUnsafeObjectKey(item))}if(!isRecord(value))return false;return Object.entries(value).some(([key,nested])=>UNSAFE_OBJECT_KEYS.has(key)||containsUnsafeObjectKey(nested))}__name(containsUnsafeObjectKey,"containsUnsafeObjectKey");function assertDescriptorValue(field,value,path=field.key,previous){if(field.kind==="object"){if(isDeepStrictEqual(previous,value)&&!containsUnsafeObjectKey(value)){return}if(!isRecord(value)){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}const previousRecord=isRecord(previous)?previous:{};const properties=new Map(field.properties.map(property=>[property.key,property]));for(const[key,nestedValue]of Object.entries(value)){const property=properties.get(key);if(!property){assertPreservedUnknownField(path,key,nestedValue,previousRecord);continue}assertDescriptorValue(property,nestedValue,`${path}.${key}`,Object.hasOwn(previousRecord,key)?previousRecord[key]:void 0)}assertRequiredFields(field.properties,value,path);return}const invalidEnvironment=typeof value==="string"&&isEnvironmentReference(value)&&!field.envResolvable;if(invalidEnvironment){throw invalidConfig(`Channel field "${path}" does not support environment references.`)}const valid=(field.kind==="string"||field.kind==="secret")&&typeof value==="string"&&value.length>0||field.kind==="boolean"&&typeof value==="boolean"||field.kind==="number"&&typeof value==="number"&&Number.isFinite(value)&&(field.exclusiveMinimum===void 0||value>field.exclusiveMinimum)||field.kind==="enum"&&typeof value==="string"&&field.options?.some(option=>option.value===value)===true||field.kind==="string-list"&&Array.isArray(value)&&value.every(item=>typeof item==="string")||field.kind==="record"&&isRecord(value)&&Object.values(value).every(v=>typeof v==="string")&&!containsUnsafeObjectKey(value);if(!valid){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}}__name(assertDescriptorValue,"assertDescriptorValue");function assertRequiredFields(fields,values,path){for(const field of fields){if(!field.required)continue;const value=Object.hasOwn(values,field.key)?values[field.key]:void 0;if(value===void 0||value===null||value===""){const fieldPath=path?`${path}.${field.key}`:field.key;throw invalidConfig(`Channel field "${fieldPath}" is required.`)}}}__name(assertRequiredFields,"assertRequiredFields");function assertPreservedUnknownField(path,key,value,previous){const fieldPath=path?`${path}.${key}`:key;if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}if(containsUnsafeObjectKey(value)){throw invalidConfig(`Channel field "${fieldPath}" cannot use a reserved key.`)}if(Object.hasOwn(previous,key)&&isDeepStrictEqual(previous[key],value)){return}throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}__name(assertPreservedUnknownField,"assertPreservedUnknownField");function assertManagedConfig(config,previous,fields){const descriptorFields=new Map(fields.map(field=>[field.key,field]));for(const[key,value]of Object.entries(config)){if(key==="type")continue;const field=descriptorFields.get(key);if(field){assertDescriptorValue(field,value,field.key,Object.hasOwn(previous,key)?previous[key]:void 0);continue}if(assertSharedField(key,value,Object.hasOwn(previous,key)?previous[key]:void 0)){continue}assertPreservedUnknownField(void 0,key,value,previous)}assertRequiredFields(fields,config)}__name(assertManagedConfig,"assertManagedConfig");function validateSecretUpdate(update){if(!isRecord(update)){throw invalidSecret("Secret updates must be objects.")}const operation=update["operation"];const keys=Object.keys(update).sort();const valid=(operation==="preserve"||operation==="clear")&&keys.length===1&&keys[0]==="operation"||operation==="replace"&&keys.length===2&&keys[0]==="operation"&&keys[1]==="value"&&typeof update["value"]==="string"&&update["value"].length>0;if(!valid){throw invalidSecret("Secret updates contain an invalid operation.")}}__name(validateSecretUpdate,"validateSecretUpdate");function assertValidChannelSecretUpdates(updates){if(!isRecord(updates)){throw invalidSecret("Secret updates must be objects.")}for(const[key,update]of Object.entries(updates)){if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidSecret(`Secret update ${JSON.stringify(key)} is invalid.`)}validateSecretUpdate(update)}}__name(assertValidChannelSecretUpdates,"assertValidChannelSecretUpdates");function channelSettingsScope(workspaceCwd){const loaded=loadSettings(workspaceCwd,{skipLoadEnvironment:true});return loaded.workspaceSettingsActive?loaded.workspace:loaded.user}__name(channelSettingsScope,"channelSettingsScope");function channelRecordMap(value){const rawChannels=isRecord(value)?value:{};const channels={};for(const[name,config]of Object.entries(rawChannels)){if(UNSAFE_OBJECT_KEYS.has(name))continue;if(isRecord(config))channels[name]=config}return channels}__name(channelRecordMap,"channelRecordMap");function snapshotFrom(values){return{revision:revisionOf(values.channels,values.startupNames),channels:{...values.channels},startupNames:[...values.startupNames]}}__name(snapshotFrom,"snapshotFrom");function workspaceValues(workspaceCwd){const scope=channelSettingsScope(workspaceCwd);const settings=scope.settings;const startupNames=Array.isArray(settings.serve?.channels)?settings.serve.channels.filter(name=>typeof name==="string"):[];return{channels:channelRecordMap(settings.channels),storedChannels:channelRecordMap(scope.originalSettings.channels),startupNames}}__name(workspaceValues,"workspaceValues");var WorkspaceChannelSettingsStore=class{constructor(workspaceCwd){this.workspaceCwd=workspaceCwd}static{__name(this,"WorkspaceChannelSettingsStore")}snapshot(){return snapshotFrom(workspaceValues(this.workspaceCwd))}async upsert(name,options){assertUpsertChannelName(name);const secretUpdates=options.secrets===void 0?{}:options.secrets;assertValidChannelSecretUpdates(secretUpdates);const plugin=await getPlugin(options.config.type);if(!plugin?.management){throw new ChannelSettingsError("channel_settings_unmanageable",`Channel type "${options.config.type}" does not provide safe management metadata.`)}const secretKeys=new Set(plugin.management.fields.filter(field=>field.kind==="secret").map(field=>field.key));const envResolvableKeys=new Set(plugin.management.fields.filter(field=>field.envResolvable).map(field=>field.key));for(const key of Object.keys(secretUpdates)){if(!secretKeys.has(key)){throw invalidSecret(`Channel type "${options.config.type}" does not declare "${key}" as a secret.`)}}for(const key of secretKeys){if(Object.hasOwn(options.config,key)){throw invalidSecret(`Secret "${key}" must use an explicit preserve, replace, or clear operation.`)}}const{current,storedChannels}=this.assertRevision(options.expectedRevision);const storedPrevious=current.channels[name]??{};const hasPreviousOfType=storedPrevious["type"]===options.config.type;const previous=hasPreviousOfType?storedPrevious:{};const storedOnDisk=storedChannels[name]??{};const previousOnDisk=hasPreviousOfType?storedOnDisk:{};const nextConfig={...options.config};const storedReferences={};for(const key of secretKeys){const update=secretUpdates[key]??{operation:"preserve"};const value=applySecretUpdate(previous[key],update);if(value!==void 0)nextConfig[key]=value;if(update.operation==="preserve"&&previousOnDisk[key]!==void 0&&envResolvableKeys.has(key)){storedReferences[key]=previousOnDisk[key]}}for(const field of plugin.management.fields){const key=field.key;if(!field.envResolvable||secretKeys.has(key))continue;const onDisk=previousOnDisk[key];if(typeof onDisk!=="string"||!isEnvironmentReference(onDisk)){continue}if(nextConfig[key]!==previous[key])continue;storedReferences[key]=onDisk}try{parseChannelOutputMode(name,nextConfig["outputMode"],plugin.supportsOutputMode===true)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}assertManagedConfig(nextConfig,previous,plugin.supportsOutputMode===true?[...plugin.management.fields,CHANNEL_OUTPUT_MODE_FIELD]:plugin.management.fields);const multiSessionError=multiSessionCompatibilityError(name,{multiSession:nextConfig["multiSession"]===true,sessionRotation:parseSessionRotationConfig(name,nextConfig["sessionRotation"]),sessionScope:effectiveSessionScope(nextConfig,nextConfig["multiSession"]===true,plugin),groupHistoryLimit:nextConfig["groupHistoryLimit"],groups:isRecord(nextConfig["groups"])?nextConfig["groups"]:{},webhooks:nextConfig["webhooks"]});if(multiSessionError)throw invalidConfig(multiSessionError);try{const routing=parseMessageRoutingConfig(name,nextConfig);if(routing.messageRoutes!==void 0)nextConfig["messageRoutes"]=routing.messageRoutes;if(routing.defaultMessageRoute!==void 0)nextConfig["defaultMessageRoute"]=routing.defaultMessageRoute}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}let crossFieldError;try{crossFieldError=plugin.management.validateConfig?.(nextConfig);if(crossFieldError instanceof Promise){void crossFieldError.catch(()=>{})}}catch(error){throw invalidConfig(`Channel validateConfig failed: ${error instanceof Error?error.message:String(error)}`)}if(crossFieldError!==void 0){throw invalidConfig(typeof crossFieldError==="string"?crossFieldError:"Channel validateConfig must return a string error message.")}const channels={...storedChannels,[name]:{...nextConfig,...storedReferences}};saveSettings(channelSettingsScope(this.workspaceCwd),{channels},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async remove(name,options){assertSafeChannelName(name);const{current,storedChannels}=this.assertRevision(options.expectedRevision);const configured=Object.hasOwn(current.channels,name);if(!configured){if(!current.startupNames.includes(name))return current;saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:current.startupNames.filter(startupName=>startupName!==name)}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}const channels={...storedChannels};delete channels[name];const hasAllSentinel=current.startupNames.some(isAllStartupName);const startupNames=hasAllSentinel?Object.keys(channels).some(channelName=>!isAllStartupName(channelName))?["all"]:[]:current.startupNames.filter(startupName=>startupName!==name);saveSettings(channelSettingsScope(this.workspaceCwd),{channels,serve:{channels:startupNames}},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async setStartupNames(names,options){for(const name of names){assertSafeChannelName(name)}this.assertRevision(options.expectedRevision);saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:[...names]}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}assertRevision(expectedRevision){const values=workspaceValues(this.workspaceCwd);const current=snapshotFrom(values);if(current.revision!==expectedRevision){throw new ChannelSettingsError("channel_settings_conflict","Channel settings changed; reload before trying again.")}return{current,storedChannels:values.storedChannels}}};export{ChannelSettingsError,assertValidChannelSecretUpdates,WorkspaceChannelSettingsStore};
3
+ import{effectiveSessionScope,multiSessionCompatibilityError,parseMessageRoutingConfig,parseSessionRotationConfig}from"./chunk-MMQY4FJL.js";import{UNSAFE_OBJECT_KEYS,getPlugin}from"./chunk-NY56CL2X.js";import{CHANNEL_OUTPUT_MODE_FIELD,parseChannelOutputMode}from"./chunk-QN7NYEE3.js";import{loadSettings,saveSettings}from"./chunk-EZPM4DLR.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import{isDeepStrictEqual}from"node:util";var ChannelSettingsError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="ChannelSettingsError"}static{__name(this,"ChannelSettingsError")}};function revisionOf(channels,startupNames){return createHash("sha256").update(JSON.stringify({channels,startupNames})).digest("hex")}__name(revisionOf,"revisionOf");function applySecretUpdate(current,update){validateSecretUpdate(update);if(update.operation==="preserve")return current;if(update.operation==="clear")return void 0;if(typeof update.value!=="string"||update.value.length===0){throw invalidSecret("Secret replacements must be non-empty strings.")}return update.value}__name(applySecretUpdate,"applySecretUpdate");function invalidSecret(message){return new ChannelSettingsError("channel_settings_invalid_secret",message)}__name(invalidSecret,"invalidSecret");function invalidConfig(message){return new ChannelSettingsError("channel_settings_invalid_config",message)}__name(invalidConfig,"invalidConfig");function assertSafeChannelName(name){if(UNSAFE_OBJECT_KEYS.has(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is not allowed.`)}}__name(assertSafeChannelName,"assertSafeChannelName");function assertUpsertChannelName(name){assertSafeChannelName(name);if(isAllStartupName(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is reserved for startup selection.`)}}__name(assertUpsertChannelName,"assertUpsertChannelName");function isAllStartupName(name){return name.trim()==="all"}__name(isAllStartupName,"isAllStartupName");function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord,"isRecord");function isEnvironmentReference(value){return/^\$[A-Za-z_][A-Za-z0-9_]*$/.test(value)}__name(isEnvironmentReference,"isEnvironmentReference");function assertStringRecord(key,value,allowedKeys){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){if(!allowedKeys.has(nestedKey)||typeof nestedValue!=="string"){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}}__name(assertStringRecord,"assertStringRecord");function assertSharedField(key,value,previous){if(key==="messageRoutes"||key==="defaultMessageRoute"){return true}if(key==="multiSession"){if(typeof value!=="boolean"){throw invalidConfig(`Channel field "${key}" must be a boolean.`)}return true}if(key==="sessionRotation"){try{parseSessionRotationConfig("settings",value)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}return true}if(key==="groupSenderPolicy"||key==="allowedGroupUsers"){throw invalidConfig(`Channel field "${key}" moved to groups["*"].${key==="groupSenderPolicy"?"senders":"allowedUsers"}.`)}const enumValues={privatePolicy:new Set(["disabled","allowlist","pairing","open"]),senderPolicy:new Set(["allowlist","pairing","open"]),dmPolicy:new Set(["open","disabled"]),groupPolicy:new Set(["disabled","allowlist","pairing","open"]),sessionScope:new Set(["user","thread","chat_thread","single"]),dispatchMode:new Set(["steer","followup","collect"])};if(Object.hasOwn(enumValues,key)){if(typeof value!=="string"||!enumValues[key].has(value)){throw invalidConfig(`Channel field "${key}" has an invalid value.`)}return true}if(["model","cwd","approvalMode","instructions"].includes(key)){if(typeof value!=="string"){throw invalidConfig(`Channel field "${key}" must be a string.`)}return true}if(key==="allowedUsers"||key==="operators"){if(!Array.isArray(value)||value.some(item=>typeof item!=="string")){throw invalidConfig(`Channel field "${key}" must be a string array.`)}return true}if(key==="groups"){if(!isRecord(value)){if(containsUnsafeObjectKey(value)||!isDeepStrictEqual(previous,value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}return true}const previousGroups=isRecord(previous)?previous:{};for(const[groupId,groupConfig]of Object.entries(value)){if(UNSAFE_OBJECT_KEYS.has(groupId)||!isRecord(groupConfig)){throw invalidConfig(`Channel field "${key}.${groupId}" is invalid.`)}const previousGroup=isRecord(previousGroups[groupId])?previousGroups[groupId]:{};for(const[nestedKey,nestedValue]of Object.entries(groupConfig)){const known=["requireMention","dispatchMode","groupHistoryLimit","senders","allowedUsers"].includes(nestedKey);const valid=nestedKey==="requireMention"&&typeof nestedValue==="boolean"||nestedKey==="dispatchMode"&&typeof nestedValue==="string"&&["collect","steer","followup"].includes(nestedValue)||nestedKey==="groupHistoryLimit"&&typeof nestedValue==="number"&&Number.isFinite(nestedValue)||nestedKey==="senders"&&typeof nestedValue==="string"&&["open","allowlist"].includes(nestedValue)||nestedKey==="allowedUsers"&&Array.isArray(nestedValue)&&nestedValue.every(item=>typeof item==="string");if(known&&!valid&&!(nestedKey!=="senders"&&Object.hasOwn(previousGroup,nestedKey)&&isDeepStrictEqual(previousGroup[nestedKey],nestedValue)&&!containsUnsafeObjectKey(nestedValue))){throw invalidConfig(`Channel field "${key}.${groupId}.${nestedKey}" is invalid.`)}if(!known){assertPreservedUnknownField(`${key}.${groupId}`,nestedKey,nestedValue,previousGroup)}}}return true}if(key==="groupHistoryLimit"){if(typeof value!=="number"||!Number.isFinite(value)){throw invalidConfig(`Channel field "${key}" must be a number.`)}return true}if(key==="identity"){assertStringRecord(key,value,new Set(["id","displayName","description"]));return true}if(key==="memoryScope"){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){const valid=nestedKey==="namespace"&&typeof nestedValue==="string"||nestedKey==="mode"&&nestedValue==="metadata-only";if(!valid){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}return true}return false}__name(assertSharedField,"assertSharedField");function containsUnsafeObjectKey(value){if(Array.isArray(value)){return value.some(item=>containsUnsafeObjectKey(item))}if(!isRecord(value))return false;return Object.entries(value).some(([key,nested])=>UNSAFE_OBJECT_KEYS.has(key)||containsUnsafeObjectKey(nested))}__name(containsUnsafeObjectKey,"containsUnsafeObjectKey");function assertDescriptorValue(field,value,path=field.key,previous){if(field.kind==="object"){if(isDeepStrictEqual(previous,value)&&!containsUnsafeObjectKey(value)){return}if(!isRecord(value)){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}const previousRecord=isRecord(previous)?previous:{};const properties=new Map(field.properties.map(property=>[property.key,property]));for(const[key,nestedValue]of Object.entries(value)){const property=properties.get(key);if(!property){assertPreservedUnknownField(path,key,nestedValue,previousRecord);continue}assertDescriptorValue(property,nestedValue,`${path}.${key}`,Object.hasOwn(previousRecord,key)?previousRecord[key]:void 0)}assertRequiredFields(field.properties,value,path);return}const invalidEnvironment=typeof value==="string"&&isEnvironmentReference(value)&&!field.envResolvable;if(invalidEnvironment){throw invalidConfig(`Channel field "${path}" does not support environment references.`)}const valid=(field.kind==="string"||field.kind==="secret")&&typeof value==="string"&&value.length>0||field.kind==="boolean"&&typeof value==="boolean"||field.kind==="number"&&typeof value==="number"&&Number.isFinite(value)&&(field.exclusiveMinimum===void 0||value>field.exclusiveMinimum)||field.kind==="enum"&&typeof value==="string"&&field.options?.some(option=>option.value===value)===true||field.kind==="string-list"&&Array.isArray(value)&&value.every(item=>typeof item==="string")||field.kind==="record"&&isRecord(value)&&Object.values(value).every(v=>typeof v==="string")&&!containsUnsafeObjectKey(value);if(!valid){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}}__name(assertDescriptorValue,"assertDescriptorValue");function assertRequiredFields(fields,values,path){for(const field of fields){if(!field.required)continue;const value=Object.hasOwn(values,field.key)?values[field.key]:void 0;if(value===void 0||value===null||value===""){const fieldPath=path?`${path}.${field.key}`:field.key;throw invalidConfig(`Channel field "${fieldPath}" is required.`)}}}__name(assertRequiredFields,"assertRequiredFields");function assertPreservedUnknownField(path,key,value,previous){const fieldPath=path?`${path}.${key}`:key;if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}if(containsUnsafeObjectKey(value)){throw invalidConfig(`Channel field "${fieldPath}" cannot use a reserved key.`)}if(Object.hasOwn(previous,key)&&isDeepStrictEqual(previous[key],value)){return}throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}__name(assertPreservedUnknownField,"assertPreservedUnknownField");function assertManagedConfig(config,previous,fields){const descriptorFields=new Map(fields.map(field=>[field.key,field]));for(const[key,value]of Object.entries(config)){if(key==="type")continue;const field=descriptorFields.get(key);if(field){assertDescriptorValue(field,value,field.key,Object.hasOwn(previous,key)?previous[key]:void 0);continue}if(assertSharedField(key,value,Object.hasOwn(previous,key)?previous[key]:void 0)){continue}assertPreservedUnknownField(void 0,key,value,previous)}assertRequiredFields(fields,config)}__name(assertManagedConfig,"assertManagedConfig");function validateSecretUpdate(update){if(!isRecord(update)){throw invalidSecret("Secret updates must be objects.")}const operation=update["operation"];const keys=Object.keys(update).sort();const valid=(operation==="preserve"||operation==="clear")&&keys.length===1&&keys[0]==="operation"||operation==="replace"&&keys.length===2&&keys[0]==="operation"&&keys[1]==="value"&&typeof update["value"]==="string"&&update["value"].length>0;if(!valid){throw invalidSecret("Secret updates contain an invalid operation.")}}__name(validateSecretUpdate,"validateSecretUpdate");function assertValidChannelSecretUpdates(updates){if(!isRecord(updates)){throw invalidSecret("Secret updates must be objects.")}for(const[key,update]of Object.entries(updates)){if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidSecret(`Secret update ${JSON.stringify(key)} is invalid.`)}validateSecretUpdate(update)}}__name(assertValidChannelSecretUpdates,"assertValidChannelSecretUpdates");function channelSettingsScope(workspaceCwd){const loaded=loadSettings(workspaceCwd,{skipLoadEnvironment:true});return loaded.workspaceSettingsActive?loaded.workspace:loaded.user}__name(channelSettingsScope,"channelSettingsScope");function channelRecordMap(value){const rawChannels=isRecord(value)?value:{};const channels={};for(const[name,config]of Object.entries(rawChannels)){if(UNSAFE_OBJECT_KEYS.has(name))continue;if(isRecord(config))channels[name]=config}return channels}__name(channelRecordMap,"channelRecordMap");function snapshotFrom(values){return{revision:revisionOf(values.channels,values.startupNames),channels:{...values.channels},startupNames:[...values.startupNames]}}__name(snapshotFrom,"snapshotFrom");function workspaceValues(workspaceCwd){const scope=channelSettingsScope(workspaceCwd);const settings=scope.settings;const startupNames=Array.isArray(settings.serve?.channels)?settings.serve.channels.filter(name=>typeof name==="string"):[];return{channels:channelRecordMap(settings.channels),storedChannels:channelRecordMap(scope.originalSettings.channels),startupNames}}__name(workspaceValues,"workspaceValues");var WorkspaceChannelSettingsStore=class{constructor(workspaceCwd){this.workspaceCwd=workspaceCwd}static{__name(this,"WorkspaceChannelSettingsStore")}snapshot(){return snapshotFrom(workspaceValues(this.workspaceCwd))}async upsert(name,options){assertUpsertChannelName(name);const secretUpdates=options.secrets===void 0?{}:options.secrets;assertValidChannelSecretUpdates(secretUpdates);const plugin=await getPlugin(options.config.type);if(!plugin?.management){throw new ChannelSettingsError("channel_settings_unmanageable",`Channel type "${options.config.type}" does not provide safe management metadata.`)}const secretKeys=new Set(plugin.management.fields.filter(field=>field.kind==="secret").map(field=>field.key));const envResolvableKeys=new Set(plugin.management.fields.filter(field=>field.envResolvable).map(field=>field.key));for(const key of Object.keys(secretUpdates)){if(!secretKeys.has(key)){throw invalidSecret(`Channel type "${options.config.type}" does not declare "${key}" as a secret.`)}}for(const key of secretKeys){if(Object.hasOwn(options.config,key)){throw invalidSecret(`Secret "${key}" must use an explicit preserve, replace, or clear operation.`)}}const{current,storedChannels}=this.assertRevision(options.expectedRevision);const storedPrevious=current.channels[name]??{};const hasPreviousOfType=storedPrevious["type"]===options.config.type;const previous=hasPreviousOfType?storedPrevious:{};const storedOnDisk=storedChannels[name]??{};const previousOnDisk=hasPreviousOfType?storedOnDisk:{};const nextConfig={...options.config};const storedReferences={};for(const key of secretKeys){const update=secretUpdates[key]??{operation:"preserve"};const value=applySecretUpdate(previous[key],update);if(value!==void 0)nextConfig[key]=value;if(update.operation==="preserve"&&previousOnDisk[key]!==void 0&&envResolvableKeys.has(key)){storedReferences[key]=previousOnDisk[key]}}for(const field of plugin.management.fields){const key=field.key;if(!field.envResolvable||secretKeys.has(key))continue;const onDisk=previousOnDisk[key];if(typeof onDisk!=="string"||!isEnvironmentReference(onDisk)){continue}if(nextConfig[key]!==previous[key])continue;storedReferences[key]=onDisk}try{parseChannelOutputMode(name,nextConfig["outputMode"],plugin.supportsOutputMode===true)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}assertManagedConfig(nextConfig,previous,plugin.supportsOutputMode===true?[...plugin.management.fields,CHANNEL_OUTPUT_MODE_FIELD]:plugin.management.fields);const multiSessionError=multiSessionCompatibilityError(name,{multiSession:nextConfig["multiSession"]===true,sessionRotation:parseSessionRotationConfig(name,nextConfig["sessionRotation"]),sessionScope:effectiveSessionScope(nextConfig,nextConfig["multiSession"]===true,plugin),groupHistoryLimit:nextConfig["groupHistoryLimit"],groups:isRecord(nextConfig["groups"])?nextConfig["groups"]:{},webhooks:nextConfig["webhooks"]});if(multiSessionError)throw invalidConfig(multiSessionError);try{const routing=parseMessageRoutingConfig(name,nextConfig);if(routing.messageRoutes!==void 0)nextConfig["messageRoutes"]=routing.messageRoutes;if(routing.defaultMessageRoute!==void 0)nextConfig["defaultMessageRoute"]=routing.defaultMessageRoute}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}let crossFieldError;try{crossFieldError=plugin.management.validateConfig?.(nextConfig);if(crossFieldError instanceof Promise){void crossFieldError.catch(()=>{})}}catch(error){throw invalidConfig(`Channel validateConfig failed: ${error instanceof Error?error.message:String(error)}`)}if(crossFieldError!==void 0){throw invalidConfig(typeof crossFieldError==="string"?crossFieldError:"Channel validateConfig must return a string error message.")}const channels={...storedChannels,[name]:{...nextConfig,...storedReferences}};saveSettings(channelSettingsScope(this.workspaceCwd),{channels},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async remove(name,options){assertSafeChannelName(name);const{current,storedChannels}=this.assertRevision(options.expectedRevision);const configured=Object.hasOwn(current.channels,name);if(!configured){if(!current.startupNames.includes(name))return current;saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:current.startupNames.filter(startupName=>startupName!==name)}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}const channels={...storedChannels};delete channels[name];const hasAllSentinel=current.startupNames.some(isAllStartupName);const startupNames=hasAllSentinel?Object.keys(channels).some(channelName=>!isAllStartupName(channelName))?["all"]:[]:current.startupNames.filter(startupName=>startupName!==name);saveSettings(channelSettingsScope(this.workspaceCwd),{channels,serve:{channels:startupNames}},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async setStartupNames(names,options){for(const name of names){assertSafeChannelName(name)}this.assertRevision(options.expectedRevision);saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:[...names]}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}assertRevision(expectedRevision){const values=workspaceValues(this.workspaceCwd);const current=snapshotFrom(values);if(current.revision!==expectedRevision){throw new ChannelSettingsError("channel_settings_conflict","Channel settings changed; reload before trying again.")}return{current,storedChannels:values.storedChannels}}};export{ChannelSettingsError,assertValidChannelSecretUpdates,WorkspaceChannelSettingsStore};
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{getPackageJson}from"./chunk-O4EDHV64.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function getCliVersion(){const pkgJson=await getPackageJson();return"0.26.6"}__name(getCliVersion,"getCliVersion");function formatVersionLabel(version){return/^\d/.test(version)?`v${version}`:version}__name(formatVersionLabel,"formatVersionLabel");export{getCliVersion,formatVersionLabel};
3
+ import{getPackageJson}from"./chunk-O4EDHV64.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function getCliVersion(){const pkgJson=await getPackageJson();return"0.26.8"}__name(getCliVersion,"getCliVersion");function formatVersionLabel(version){return/^\d/.test(version)?`v${version}`:version}__name(formatVersionLabel,"formatVersionLabel");export{getCliVersion,formatVersionLabel};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC