gerege-cli 0.26.7 → 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 (246) 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-LSNOJEKM.js → MaxSizedBox-LUINLOQW.js} +1 -1
  4. package/chunks/{StandaloneSessionPicker-KSYGPMEV.js → StandaloneSessionPicker-B7N4QO5D.js} +1 -1
  5. package/chunks/{acp-subagent-executor-NSW2MFUI.js → acp-subagent-executor-J6H6FKUT.js} +1 -1
  6. package/chunks/{acpAgent-3DTOHTDM.js → acpAgent-XG6SM2VU.js} +3 -3
  7. package/chunks/{advisor-7JGQPS7X.js → advisor-SZVPQNPA.js} +1 -1
  8. package/chunks/{agent-PNKQJGDO.js → agent-N7QF7BJS.js} +1 -1
  9. package/chunks/{agent-headless-7D33X7QQ.js → agent-headless-GLP5GUEX.js} +1 -1
  10. package/chunks/{agent-host-client-3R2MAUVE.js → agent-host-client-H4VOB3M6.js} +1 -1
  11. package/chunks/{agent-host-connections-2D7DECAE.js → agent-host-connections-E4C3OC4M.js} +1 -1
  12. package/chunks/{anthropicContentGenerator-MGTJJGEQ.js → anthropicContentGenerator-5VTWQLT5.js} +1 -1
  13. package/chunks/{autofix-pr-OIHHZSPQ.js → autofix-pr-HDYQDJS4.js} +1 -1
  14. package/chunks/{batch-6UDAMPAA.js → batch-3CRVN5VJ.js} +1 -1
  15. package/chunks/{bridge-QXVXPNJ6.js → bridge-NZ6WVBLQ.js} +1 -1
  16. package/chunks/{channel-settings-store-P4W4R5SJ.js → channel-settings-store-Z7I2JI6M.js} +1 -1
  17. package/chunks/{chunk-HVP4UF2Q.js → chunk-236DHGNH.js} +1 -1
  18. package/chunks/{chunk-GA35LMSX.js → chunk-2M3ND5WN.js} +1 -1
  19. package/chunks/{chunk-IZXHCHJD.js → chunk-36A6EXHB.js} +1 -1
  20. package/chunks/{chunk-QHYSRPQR.js → chunk-3ANIQTDT.js} +1 -1
  21. package/chunks/{chunk-WK666FGZ.js → chunk-3QTR2HAE.js} +3 -3
  22. package/chunks/{chunk-3EZ5GCUT.js → chunk-3TTHYXT3.js} +1 -1
  23. package/chunks/{chunk-YWK3E4WJ.js → chunk-4CE4GMDL.js} +1 -1
  24. package/chunks/{chunk-VUNHJ74J.js → chunk-4FVT657Y.js} +1 -1
  25. package/chunks/{chunk-BY46PCWY.js → chunk-4HSISRRA.js} +1 -1
  26. package/chunks/{chunk-2LMSDH6P.js → chunk-4SZUJ5RT.js} +1 -1
  27. package/chunks/{chunk-53IB4U4E.js → chunk-57D2OB3I.js} +1 -1
  28. package/chunks/{chunk-QTKPC24L.js → chunk-5FGBLIXB.js} +1 -1
  29. package/chunks/{chunk-5TWAP4OG.js → chunk-5HX2QGVR.js} +1 -1
  30. package/chunks/{chunk-K7GN4CMV.js → chunk-5ZNXAWOG.js} +6 -6
  31. package/chunks/{chunk-QTVSPQZQ.js → chunk-6CKX56LJ.js} +1 -1
  32. package/chunks/{chunk-4W27Z3OL.js → chunk-6NIQFWXP.js} +1 -1
  33. package/chunks/{chunk-6YFNUVJR.js → chunk-6PC6MZHL.js} +1 -1
  34. package/chunks/{chunk-DQQN2HOP.js → chunk-6VQKGKMJ.js} +1 -1
  35. package/chunks/{chunk-MXZXQUVP.js → chunk-6ZEMLEK2.js} +1 -1
  36. package/chunks/{chunk-RT6J7PV4.js → chunk-72VY2PJA.js} +1 -1
  37. package/chunks/{chunk-EEPNACXJ.js → chunk-75I3NYBD.js} +1 -1
  38. package/chunks/{chunk-ATTJQLQV.js → chunk-76L7ZDEK.js} +1 -1
  39. package/chunks/{chunk-T3CQ72HC.js → chunk-7XQ5D34E.js} +6 -6
  40. package/chunks/{chunk-4AKTP4MM.js → chunk-AYX75VXG.js} +1 -1
  41. package/chunks/{chunk-MDCA4I63.js → chunk-BBDFEMCF.js} +1 -1
  42. package/chunks/{chunk-N4ZQC5HB.js → chunk-BOTX7S66.js} +1 -1
  43. package/chunks/{chunk-UVMLWDRU.js → chunk-CY2QKKZA.js} +1 -1
  44. package/chunks/{chunk-W2CV36HT.js → chunk-D5JWQUID.js} +1 -1
  45. package/chunks/{chunk-WEPC42YR.js → chunk-DMIPB7RZ.js} +1 -1
  46. package/chunks/{chunk-BVV7UXES.js → chunk-DSKA3P2C.js} +1 -1
  47. package/chunks/{chunk-SAVYMUU3.js → chunk-DVC65H4X.js} +1 -1
  48. package/chunks/{chunk-MS2XCBPP.js → chunk-DVJSDCMX.js} +1 -1
  49. package/chunks/{chunk-4QOVM2LL.js → chunk-E6CPFQX2.js} +1 -1
  50. package/chunks/{chunk-LYFRGP42.js → chunk-EIFBGEXJ.js} +1 -1
  51. package/chunks/{chunk-3ICJI5KW.js → chunk-EQOHDAYU.js} +1 -1
  52. package/chunks/{chunk-Q5RRVBTY.js → chunk-EZPM4DLR.js} +1 -1
  53. package/chunks/{chunk-ISQMHOCC.js → chunk-F6U6T7QD.js} +1 -1
  54. package/chunks/{chunk-WCI33URB.js → chunk-FCGFBUHS.js} +1 -1
  55. package/chunks/{chunk-CK3OKTTL.js → chunk-G2LTZU67.js} +1 -1
  56. package/chunks/{chunk-WSI4G7XC.js → chunk-GMJSEK4V.js} +1 -1
  57. package/chunks/{chunk-QONPET6Y.js → chunk-HJMUBVXZ.js} +2 -2
  58. package/chunks/{chunk-H5EXNXGW.js → chunk-HQZTAA2U.js} +1 -1
  59. package/chunks/{chunk-5R2JIZID.js → chunk-I63TIQOI.js} +1 -1
  60. package/chunks/{chunk-IY7M5HKF.js → chunk-I65LBJN7.js} +1 -1
  61. package/chunks/{chunk-H34KVVI4.js → chunk-IBDOC27R.js} +1 -1
  62. package/chunks/{chunk-N6EFYQ7M.js → chunk-IKF2HWEV.js} +1 -1
  63. package/chunks/{chunk-CDKBM72V.js → chunk-K6NS2HXT.js} +1 -1
  64. package/chunks/{chunk-BIPPD7W6.js → chunk-KTRNYPQP.js} +1 -1
  65. package/chunks/{chunk-DTX2OVQW.js → chunk-L3ANU5JZ.js} +1 -1
  66. package/chunks/{chunk-WXK7Z45R.js → chunk-LKPMADUO.js} +1 -1
  67. package/chunks/{chunk-4VR4DUUD.js → chunk-M56Y2B6N.js} +1 -1
  68. package/chunks/{chunk-YY4GWNTU.js → chunk-N5KRBAK5.js} +2 -2
  69. package/chunks/{chunk-DVUKYOCJ.js → chunk-NA2WJPOU.js} +1 -1
  70. package/chunks/{chunk-O3TUZQP4.js → chunk-NGOWLXYK.js} +1 -1
  71. package/chunks/{chunk-F7622ZRQ.js → chunk-NL7P73ZP.js} +1 -1
  72. package/chunks/{chunk-U5YOAOU3.js → chunk-NS3QR7D3.js} +1 -1
  73. package/chunks/{chunk-FTF2NFLB.js → chunk-O5JCCBMQ.js} +1 -1
  74. package/chunks/{chunk-DEJ47KJE.js → chunk-OOKFFZHF.js} +1 -1
  75. package/chunks/{chunk-4A663FE6.js → chunk-OTYPLLMT.js} +5 -5
  76. package/chunks/{chunk-NPAENNRO.js → chunk-P7NHWX27.js} +1 -1
  77. package/chunks/{chunk-HXTYFGSQ.js → chunk-PC5QZUKR.js} +1 -1
  78. package/chunks/{chunk-RULGA7WE.js → chunk-PS7MQL57.js} +2 -2
  79. package/chunks/{chunk-FKUDVIME.js → chunk-PXWHOFAA.js} +1 -1
  80. package/chunks/{chunk-6WV5RKYB.js → chunk-Q65LVCDR.js} +1 -1
  81. package/chunks/{chunk-ULLW2AYD.js → chunk-QDUDLELH.js} +1 -1
  82. package/chunks/{chunk-PMBI46K4.js → chunk-QF22ILPV.js} +1 -1
  83. package/chunks/{chunk-LY4XTBL4.js → chunk-QW7MAG2E.js} +1 -1
  84. package/chunks/{chunk-IIHUDJX7.js → chunk-RXK6XD6F.js} +1 -1
  85. package/chunks/{chunk-QSPXKBUX.js → chunk-SVDFCWS7.js} +1 -1
  86. package/chunks/{chunk-NHPKD7LY.js → chunk-TKP3GAUI.js} +1 -1
  87. package/chunks/{chunk-WF7Q3ZSQ.js → chunk-TUS74LFI.js} +1 -1
  88. package/chunks/{chunk-OZFZBGZG.js → chunk-U7YGHPSL.js} +1 -1
  89. package/chunks/{chunk-G4MWPXNY.js → chunk-UB37RBSK.js} +1 -1
  90. package/chunks/{chunk-4LC4INFI.js → chunk-UK5SIRH4.js} +1 -1
  91. package/chunks/{chunk-7HFFTOAD.js → chunk-UTTSBCFR.js} +1 -1
  92. package/chunks/{chunk-IQMKQKKD.js → chunk-UYV4ZVXY.js} +2 -2
  93. package/chunks/{chunk-E3KWSRJN.js → chunk-VC3JJL7E.js} +1 -1
  94. package/chunks/{chunk-FRVXSKL4.js → chunk-VKWVIWLK.js} +1 -1
  95. package/chunks/{chunk-L7LO3YRT.js → chunk-VUI6STKU.js} +1 -1
  96. package/chunks/{chunk-VK7LOUOJ.js → chunk-W3YXE55M.js} +1 -1
  97. package/chunks/{chunk-JHC22BZH.js → chunk-WAIPC47V.js} +1 -1
  98. package/chunks/{chunk-P2MZZMCS.js → chunk-WMJ6UHDP.js} +1 -1
  99. package/chunks/{chunk-6JAXAFX7.js → chunk-WZU2ECUD.js} +1 -1
  100. package/chunks/{chunk-HJLRKM3W.js → chunk-XAGIZY2Y.js} +1 -1
  101. package/chunks/{chunk-2J2BQ3PL.js → chunk-XGZYVULJ.js} +2 -2
  102. package/chunks/{chunk-QVHDM6N7.js → chunk-XJIHDVPX.js} +1 -1
  103. package/chunks/{chunk-ZFOEVHWG.js → chunk-XVDIHFRH.js} +1 -1
  104. package/chunks/{chunk-F5SLLEJY.js → chunk-YMEW4TTT.js} +1 -1
  105. package/chunks/{chunk-NYBYDW6R.js → chunk-Z32URWBG.js} +1 -1
  106. package/chunks/{chunk-WMLYHZZX.js → chunk-Z6HRXHJP.js} +1 -1
  107. package/chunks/{chunk-UM5KBBYP.js → chunk-ZO4F6ZWR.js} +1 -1
  108. package/chunks/{codex-subagent-executor-GPTKVP7H.js → codex-subagent-executor-DDKYNU42.js} +1 -1
  109. package/chunks/{config-utils-6B5FHBSF.js → config-utils-S7Z2ZZ2E.js} +1 -1
  110. package/chunks/{contextCommand-FGRDE3GA.js → contextCommand-7F4PGV2A.js} +1 -1
  111. package/chunks/{core-runtime-OFEHSKDB.js → core-runtime-LBH3U7ZF.js} +1 -1
  112. package/chunks/{create-sub-session-D2KEWVHQ.js → create-sub-session-56DS2T6L.js} +1 -1
  113. package/chunks/{cron-create-RFGGKTL7.js → cron-create-PBP3C46Q.js} +1 -1
  114. package/chunks/{daemon-git-worktree-guard-AV752IOZ.js → daemon-git-worktree-guard-WJS6FBDA.js} +1 -1
  115. package/chunks/{daemon-status-provider-GHQBRDMC.js → daemon-status-provider-UPPAEHJ6.js} +1 -1
  116. package/chunks/{daemon-trust-policy-24ENJNTQ.js → daemon-trust-policy-4Z5HSNUX.js} +1 -1
  117. package/chunks/{daemon-trust-policy-monitor-NMSQAGWV.js → daemon-trust-policy-monitor-WFWDOYX3.js} +1 -1
  118. package/chunks/{deferred-core-runtime-5BAMFFOI.js → deferred-core-runtime-MJYNEA4N.js} +1 -1
  119. package/chunks/{edit-XCECLEH3.js → edit-U7TGKKK3.js} +1 -1
  120. package/chunks/{enterPlanMode-SEN2PMRM.js → enterPlanMode-27HC5AXN.js} +1 -1
  121. package/chunks/{environment-CCPQJYKS.js → environment-PHWY6C4P.js} +1 -1
  122. package/chunks/{errors-Y6HHUTGK.js → errors-F2EYYFI3.js} +1 -1
  123. package/chunks/{execution-tool-HADWGMIG.js → execution-tool-O4KJ5SMM.js} +1 -1
  124. package/chunks/{execution-worker-GZS7WOQL.js → execution-worker-AMFXZ7JD.js} +1 -1
  125. package/chunks/{exitPlanMode-76B5HDLT.js → exitPlanMode-LDYL43PB.js} +1 -1
  126. package/chunks/{fast-path-OEV7LQYV.js → fast-path-HTODEVOR.js} +1 -1
  127. package/chunks/{glob-NLWCQRMS.js → glob-NKQJJZND.js} +1 -1
  128. package/chunks/{goal-tools-43XV33BT.js → goal-tools-47I455VV.js} +1 -1
  129. package/chunks/{handleAutoUpdate-JDQWGSSP.js → handleAutoUpdate-MJKTDJUO.js} +1 -1
  130. package/chunks/{i18n-JW6BVEGF.js → i18n-TCOB4TC5.js} +1 -1
  131. package/chunks/{initializer-UT6JLZ3O.js → initializer-NLYOGZZS.js} +1 -1
  132. package/chunks/{installationInfo-LKWDV3S2.js → installationInfo-TF2RSJOG.js} +1 -1
  133. package/chunks/{interactive-mod-session-2KWKYVPC.js → interactive-mod-session-5F7R3KSA.js} +1 -1
  134. package/chunks/{list-BKINK3S2.js → list-U2AEVLFP.js} +1 -1
  135. package/chunks/{llm-3RWXAVM2.js → llm-EV2QTQBU.js} +4 -4
  136. package/chunks/{llm-content-generator-MDRBSH73.js → llm-content-generator-ZXUSPPG2.js} +1 -1
  137. package/chunks/{loadedSettingsAdapter-WWJUKWUN.js → loadedSettingsAdapter-TLRI22X7.js} +1 -1
  138. package/chunks/{local-TT4FLCTR.js → local-ZTSBSKWV.js} +1 -1
  139. package/chunks/{local-execution-environment-OBA6VWYL.js → local-execution-environment-F263PSIM.js} +1 -1
  140. package/chunks/{loggingContentGenerator-CK7IKYQH.js → loggingContentGenerator-2XHSIJQD.js} +1 -1
  141. package/chunks/{loop-wakeup-4MSRX3DY.js → loop-wakeup-5ET3JHUT.js} +1 -1
  142. package/chunks/{manage-memory-PX5PZJKZ.js → manage-memory-MJEQ47H2.js} +1 -1
  143. package/chunks/{managed-execution-engine-WMAUR3ZK.js → managed-execution-engine-ODPR5OEH.js} +1 -1
  144. package/chunks/{managed-local-serve-X7REHGB4.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-F4AT53M5.js → managed-runtime-attestation-worker-BQP4E7LQ.js} +1 -1
  147. package/chunks/{managed-runtime-bootstrap-3BP5JRJX.js → managed-runtime-bootstrap-SRBDFSKK.js} +1 -1
  148. package/chunks/{managed-runtime-session-worker-2PO7J5UK.js → managed-runtime-session-worker-UI23BTYJ.js} +1 -1
  149. package/chunks/{managed-runtime-ssh-worker-4N7EMRSV.js → managed-runtime-ssh-worker-HU4CIJRK.js} +1 -1
  150. package/chunks/{managed-session-authority-MYOYTUM2.js → managed-session-authority-XSSTLAEY.js} +1 -1
  151. package/chunks/{mcp-5OTEMZ7P.js → mcp-WLHDOKP7.js} +1 -1
  152. package/chunks/{memory-TNW7RSAV.js → memory-OUUHPSDD.js} +1 -1
  153. package/chunks/{model-call-collection-KNTWFZQS.js → model-call-collection-4A2EB76B.js} +1 -1
  154. package/chunks/{model-configuration-U5C5P5UQ.js → model-configuration-4CGUFKEP.js} +1 -1
  155. package/chunks/{modelConfigUtils-R4KFI2WK.js → modelConfigUtils-HUEERWBA.js} +1 -1
  156. package/chunks/{monitor-RD2PFK42.js → monitor-FXL5UNMP.js} +1 -1
  157. package/chunks/{nonInteractiveCli-QQ72HZSH.js → nonInteractiveCli-W7M2O43W.js} +1 -1
  158. package/chunks/{nonInteractiveToolExecutor-QPQYR6IS.js → nonInteractiveToolExecutor-EMLI363Q.js} +1 -1
  159. package/chunks/{notebook-edit-YLRN3UZT.js → notebook-edit-R5RSLSSH.js} +1 -1
  160. package/chunks/{omni-CUJ52EW5.js → omni-DNZGITTE.js} +1 -1
  161. package/chunks/{openaiContentGenerator-6B5MAU54.js → openaiContentGenerator-PKOPYMHR.js} +1 -1
  162. package/chunks/{openaiResponsesContentGenerator-I245I3R7.js → openaiResponsesContentGenerator-MHH2MF3V.js} +1 -1
  163. package/chunks/{pidfile-P2HIGAUA.js → pidfile-5ZNJWMKG.js} +1 -1
  164. package/chunks/{processUtils-JSKN5UGS.js → processUtils-JIHQDASW.js} +1 -1
  165. package/chunks/{prompt-terminal-ledger-F5TSXVGU.js → prompt-terminal-ledger-L3LZ5SLR.js} +1 -1
  166. package/chunks/{qwenContentGenerator-IEDZONWG.js → qwenContentGenerator-QCZL7HJJ.js} +1 -1
  167. package/chunks/{reactive-degrade-FYZBJCF6.js → reactive-degrade-YUXOUQG4.js} +1 -1
  168. package/chunks/{read-file-VNZNSD6X.js → read-file-FBNU3AVX.js} +1 -1
  169. package/chunks/{resumeHistoryUtils-IDPE6N2N.js → resumeHistoryUtils-5FPRTI4A.js} +1 -1
  170. package/chunks/{review-TBJRZWTD.js → review-NLFYSNM3.js} +1 -1
  171. package/chunks/{ripGrep-4W5B5FOE.js → ripGrep-JUAPC5LD.js} +1 -1
  172. package/chunks/{run-qwen-serve-44X262G5.js → run-qwen-serve-JP64UQ3Y.js} +1 -1
  173. package/chunks/{runtime-6H6LKD73.js → runtime-D2QUYM6U.js} +1 -1
  174. package/chunks/{sandboxConfig-SQXDRGVN.js → sandboxConfig-7VZJQV6H.js} +1 -1
  175. package/chunks/{scheduled-tasks-62IZKHJG.js → scheduled-tasks-PC6EH75E.js} +1 -1
  176. package/chunks/{scheduler-QUCXJYRL.js → scheduler-RUV2FNDR.js} +1 -1
  177. package/chunks/{search-memory-TC2Z34QN.js → search-memory-YJTJ7BRU.js} +1 -1
  178. package/chunks/{send-message-TFZX7KI7.js → send-message-EEEFFTHX.js} +1 -1
  179. package/chunks/{serve-WSICDFGG.js → serve-KMIZDYON.js} +1 -1
  180. package/chunks/{server-GYYVTNGY.js → server-DUPK3V7B.js} +3 -3
  181. package/chunks/{session-KF3O23ZJ.js → session-CW5YMFMP.js} +1 -1
  182. package/chunks/{session-attachments-root-7HFUSONH.js → session-attachments-root-5H5GFHLI.js} +1 -1
  183. package/chunks/{session-execution-engine-selector-NVILT6BR.js → session-execution-engine-selector-MVXM2HZW.js} +1 -1
  184. package/chunks/{session-pr-refresh-3KDFTDEV.js → session-pr-refresh-4UPONX4L.js} +1 -1
  185. package/chunks/{sessionService-XRTFLPDW.js → sessionService-GGCYISSL.js} +1 -1
  186. package/chunks/{settings-QPPK6WXE.js → settings-AASJCESS.js} +1 -1
  187. package/chunks/{shell-WYQDZWL7.js → shell-V4WWLW3Q.js} +1 -1
  188. package/chunks/{skill-FYPT6AU7.js → skill-NDEBB7VX.js} +1 -1
  189. package/chunks/{skill-settings-OGFI5KZF.js → skill-settings-YAI3GYU5.js} +1 -1
  190. package/chunks/{spawnChannel-ANOOVPG7.js → spawnChannel-6JKVJAXZ.js} +1 -1
  191. package/chunks/{standalone-update-45WTDY4E.js → standalone-update-NJP5OCKJ.js} +1 -1
  192. package/chunks/{start-opentui-ui-TL5WK33V.js → start-opentui-ui-M4B4SXRM.js} +1 -1
  193. package/chunks/{startInteractiveUI-N2IREVBM.js → startInteractiveUI-O4JUDEAU.js} +1 -1
  194. package/chunks/{team-create-R77PRZ5U.js → team-create-NLJ7QBLD.js} +1 -1
  195. package/chunks/{team-plan-approval-6DCRKB5I.js → team-plan-approval-XKYPVWNG.js} +1 -1
  196. package/chunks/{terminal-image-renderer-TB7EX2WW.js → terminal-image-renderer-47TD747D.js} +1 -1
  197. package/chunks/{theme-manager-RQDXJGVR.js → theme-manager-AANEBPLJ.js} +1 -1
  198. package/chunks/{tool-call-LVB4NCDT.js → tool-call-ETH3LS7Y.js} +1 -1
  199. package/chunks/{tool-result-media-LRBB2KS6.js → tool-result-media-EFOEPAF2.js} +1 -1
  200. package/chunks/{tool-search-OG73QAQZ.js → tool-search-J3CF5PRN.js} +1 -1
  201. package/chunks/{total-session-admission-A4CUF6AD.js → total-session-admission-3DC52PLQ.js} +1 -1
  202. package/chunks/{trustedFolders-LSGOYTU2.js → trustedFolders-4KPWZZKB.js} +1 -1
  203. package/chunks/{update-relaunch-OGC6BZO7.js → update-relaunch-A67BS7QS.js} +1 -1
  204. package/chunks/{updateCheck-7J3GXTER.js → updateCheck-X623JRSY.js} +1 -1
  205. package/chunks/{upload-config-ML5XEJIF.js → upload-config-X2CR3F26.js} +1 -1
  206. package/chunks/{useAutoAcceptIndicator-6DH6GQ2X.js → useAutoAcceptIndicator-INIOQGJH.js} +1 -1
  207. package/chunks/{validateNonInterActiveAuth-KJDAGZCM.js → validateNonInterActiveAuth-XJ2U5CLB.js} +1 -1
  208. package/chunks/{version-7JN2YXL2.js → version-MFHRMM7W.js} +1 -1
  209. package/chunks/{web-fetch-42ZR4FEZ.js → web-fetch-3GEJ62DH.js} +1 -1
  210. package/chunks/{web-search-74NLPMZJ.js → web-search-WJZO3Q3A.js} +1 -1
  211. package/chunks/{workflow-WNPHX42I.js → workflow-ML7ITCMH.js} +1 -1
  212. package/chunks/{workflow-ancestor-trust-HGF6G7LQ.js → workflow-ancestor-trust-M3VFMS73.js} +1 -1
  213. package/chunks/{workspace-agents-3YFBFAK3.js → workspace-agents-YFZMV7EF.js} +1 -1
  214. package/chunks/{workspace-providers-status-EPJI6KRV.js → workspace-providers-status-3COKLBCI.js} +1 -1
  215. package/chunks/{workspace-recovery-worker-T3FK5YOD.js → workspace-recovery-worker-QURA3WFZ.js} +1 -1
  216. package/chunks/{workspace-registration-store-VEXYBDMA.js → workspace-registration-store-F3AGIOBW.js} +1 -1
  217. package/chunks/{workspace-registry-NRZYTP2X.js → workspace-registry-QUBL3RW6.js} +1 -1
  218. package/chunks/{workspace-runtime-coordinator-USNSTP2V.js → workspace-runtime-coordinator-22TSDHXX.js} +1 -1
  219. package/chunks/{workspace-service-USATWO56.js → workspace-service-UUENTHNO.js} +1 -1
  220. package/chunks/{workspace-skills-status-M5JTSFDL.js → workspace-skills-status-NNQQBBCJ.js} +1 -1
  221. package/chunks/{workspace-trust-reconciler-ZUZ2O5WC.js → workspace-trust-reconciler-3CMMNCGG.js} +1 -1
  222. package/chunks/{write-file-UMJVKE4S.js → write-file-DEAFIK4C.js} +1 -1
  223. package/chunks/{zoom-image-76XYHQ3Z.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/package.json +2 -12
  229. package/chunks/managed-npm-update-6HUVAJH7.js +0 -8
  230. package/opentui-assets/@opentui/core/assets/javascript/highlights.scm +0 -205
  231. package/opentui-assets/@opentui/core/assets/javascript/tree-sitter-javascript.wasm +0 -0
  232. package/opentui-assets/@opentui/core/assets/markdown/highlights.scm +0 -150
  233. package/opentui-assets/@opentui/core/assets/markdown/injections.scm +0 -27
  234. package/opentui-assets/@opentui/core/assets/markdown/tree-sitter-markdown.wasm +0 -0
  235. package/opentui-assets/@opentui/core/assets/markdown_inline/highlights.scm +0 -115
  236. package/opentui-assets/@opentui/core/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
  237. package/opentui-assets/@opentui/core/assets/typescript/highlights.scm +0 -604
  238. package/opentui-assets/@opentui/core/assets/typescript/tree-sitter-typescript.wasm +0 -0
  239. package/opentui-assets/@opentui/core/assets/zig/highlights.scm +0 -284
  240. package/opentui-assets/@opentui/core/assets/zig/tree-sitter-zig.wasm +0 -0
  241. package/opentui-assets/@opentui/core/parser.worker.js +0 -4566
  242. package/opentui-assets/@opentui/core-darwin-arm64/libopentui.dylib +0 -0
  243. package/opentui-assets/@opentui/core-darwin-x64/libopentui.dylib +0 -0
  244. package/opentui-assets/@opentui/core-linux-arm64/libopentui.so +0 -0
  245. package/opentui-assets/@opentui/core-linux-x64/libopentui.so +0 -0
  246. 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{HOSTNAME_RE,isOwnerRepo,normalizeGhHostForUrl}from"./chunk-UPWFKIG7.js";import{GIT_TIMEOUT_MS,git,gitOpt,gitProbe,gitRaw,redirectedAncestor,refExists,releaseWorktree,repoRoot,sanitizedGitEnv}from"./chunk-4LC4INFI.js";import{normalizeSegment}from"./chunk-CTMNGGOU.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{atomicWriteFileSync}from"./chunk-BMHYEQTI.js";import{writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{lstatSync as lstatSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{homedir}from"node:os";import{closeSync,constants,existsSync,fstatSync,linkSync,lstatSync,mkdirSync,openSync,readFileSync,readlinkSync,realpathSync,renameSync,rmSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,resolve}from"node:path";var REPLY_MARKER="<!-- qwen-autofix-pr:v1 -->";var WATCH_INTERVALS=[1,2,5,10,15,30,60];var MAX_NEEDS_HUMAN=20;var MAX_INSTRUCTIONS_CHARS=2e3;function rerunFloors(state){return[...state.rerunChecks??[],...(state.heldChecks??[]).map(entry=>entry.replace(/^\d+:/,""))]}__name(rerunFloors,"rerunFloors");var MAX_PUSHES=10;var MAX_CHECK_FIX_PUSHES=3;var MAX_FAILING_CHECKS=100;function withKnownHead(state,head){if(state.pushedShas.includes(head)||!state.failingChecks?.length){return{...state,lastKnownHeadSha:head}}const lastPush=state.pushedShas.at(-1);return{...state,lastKnownHeadSha:head,failingChecks:state.failingChecks.map(record=>({identity:record.identity,check:record.check,head:record.head,pushes:0,...lastPush===void 0?{}:{lastPush}}))}}__name(withKnownHead,"withKnownHead");function checkAttemptKey(check,headSha,attempt){return`${check}@${headSha}@${attempt}`}__name(checkAttemptKey,"checkAttemptKey");function watchRoot(){if(process.env["QWEN_CODE_SERVE"]==="1"){return git("rev-parse","--show-toplevel")}return repoRoot()}__name(watchRoot,"watchRoot");function parseWorktreePaths(nulOutput){const paths=[];for(const field of nulOutput.split("\0")){if(field.startsWith("worktree ")){paths.push(field.slice("worktree ".length))}}return paths}__name(parseWorktreePaths,"parseWorktreePaths");function cloneWorktreeRoots(){const z=gitOpt("worktree","list","--porcelain","-z");if(z!==null)return parseWorktreePaths(z);return[repoRoot()]}__name(cloneWorktreeRoots,"cloneWorktreeRoots");function findWatchRoot(prNumber){assertPositiveInteger(prNumber,"PR number");let found=null;for(const root of vouchedScanRoots(cloneWorktreeRoots())){const paths=autofixPrPaths(root,prNumber);let hasState;try{hasState=isRegularFile(paths.statePath)}catch{continue}if(!hasState)continue;if(found===null||!existsSync(autofixPrPaths(found,prNumber).worktreePath)&&existsSync(paths.worktreePath)){found=root}}return found}__name(findWatchRoot,"findWatchRoot");function resolveWatchRoot(prNumber){return findWatchRoot(prNumber)??watchRoot()}__name(resolveWatchRoot,"resolveWatchRoot");function anchorStoreRoot(){return process.env["QWEN_AUTOFIX_ANCHOR_DIR"]??join(homedir(),".qwen","autofix-anchors")}__name(anchorStoreRoot,"anchorStoreRoot");function anchorPath(repository,prNumber,cloneRoot){assertPositiveInteger(prNumber,"PR number");const slug=[normalizeGhHostForUrl(repository.host).replace(/:/g,"@"),normalizeSegment(repository.owner),normalizeSegment(repository.repo)].join("+").replace(/[^a-z0-9._@+-]/g,"_");const cloneKey=createHash("sha256").update(resolve(cloneRoot)).digest("hex").slice(0,16);return join(anchorStoreRoot(),slug,`${cloneKey}-pr-${prNumber}.json`)}__name(anchorPath,"anchorPath");function writeAnchor(repository,prNumber,trustRoot){const path=anchorPath(repository,prNumber,trustRoot);mkdirSync(dirname(path),{recursive:true});const anchor={trustRoot,...repository};atomicWriteFileSync(path,`${JSON.stringify(anchor,null,2)}
3
+ import{HOSTNAME_RE,isOwnerRepo,normalizeGhHostForUrl}from"./chunk-UPWFKIG7.js";import{GIT_TIMEOUT_MS,git,gitOpt,gitProbe,gitRaw,redirectedAncestor,refExists,releaseWorktree,repoRoot,sanitizedGitEnv}from"./chunk-UK5SIRH4.js";import{normalizeSegment}from"./chunk-CTMNGGOU.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{atomicWriteFileSync}from"./chunk-BMHYEQTI.js";import{writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{lstatSync as lstatSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{homedir}from"node:os";import{closeSync,constants,existsSync,fstatSync,linkSync,lstatSync,mkdirSync,openSync,readFileSync,readlinkSync,realpathSync,renameSync,rmSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,resolve}from"node:path";var REPLY_MARKER="<!-- qwen-autofix-pr:v1 -->";var WATCH_INTERVALS=[1,2,5,10,15,30,60];var MAX_NEEDS_HUMAN=20;var MAX_INSTRUCTIONS_CHARS=2e3;function rerunFloors(state){return[...state.rerunChecks??[],...(state.heldChecks??[]).map(entry=>entry.replace(/^\d+:/,""))]}__name(rerunFloors,"rerunFloors");var MAX_PUSHES=10;var MAX_CHECK_FIX_PUSHES=3;var MAX_FAILING_CHECKS=100;function withKnownHead(state,head){if(state.pushedShas.includes(head)||!state.failingChecks?.length){return{...state,lastKnownHeadSha:head}}const lastPush=state.pushedShas.at(-1);return{...state,lastKnownHeadSha:head,failingChecks:state.failingChecks.map(record=>({identity:record.identity,check:record.check,head:record.head,pushes:0,...lastPush===void 0?{}:{lastPush}}))}}__name(withKnownHead,"withKnownHead");function checkAttemptKey(check,headSha,attempt){return`${check}@${headSha}@${attempt}`}__name(checkAttemptKey,"checkAttemptKey");function watchRoot(){if(process.env["QWEN_CODE_SERVE"]==="1"){return git("rev-parse","--show-toplevel")}return repoRoot()}__name(watchRoot,"watchRoot");function parseWorktreePaths(nulOutput){const paths=[];for(const field of nulOutput.split("\0")){if(field.startsWith("worktree ")){paths.push(field.slice("worktree ".length))}}return paths}__name(parseWorktreePaths,"parseWorktreePaths");function cloneWorktreeRoots(){const z=gitOpt("worktree","list","--porcelain","-z");if(z!==null)return parseWorktreePaths(z);return[repoRoot()]}__name(cloneWorktreeRoots,"cloneWorktreeRoots");function findWatchRoot(prNumber){assertPositiveInteger(prNumber,"PR number");let found=null;for(const root of vouchedScanRoots(cloneWorktreeRoots())){const paths=autofixPrPaths(root,prNumber);let hasState;try{hasState=isRegularFile(paths.statePath)}catch{continue}if(!hasState)continue;if(found===null||!existsSync(autofixPrPaths(found,prNumber).worktreePath)&&existsSync(paths.worktreePath)){found=root}}return found}__name(findWatchRoot,"findWatchRoot");function resolveWatchRoot(prNumber){return findWatchRoot(prNumber)??watchRoot()}__name(resolveWatchRoot,"resolveWatchRoot");function anchorStoreRoot(){return process.env["QWEN_AUTOFIX_ANCHOR_DIR"]??join(homedir(),".qwen","autofix-anchors")}__name(anchorStoreRoot,"anchorStoreRoot");function anchorPath(repository,prNumber,cloneRoot){assertPositiveInteger(prNumber,"PR number");const slug=[normalizeGhHostForUrl(repository.host).replace(/:/g,"@"),normalizeSegment(repository.owner),normalizeSegment(repository.repo)].join("+").replace(/[^a-z0-9._@+-]/g,"_");const cloneKey=createHash("sha256").update(resolve(cloneRoot)).digest("hex").slice(0,16);return join(anchorStoreRoot(),slug,`${cloneKey}-pr-${prNumber}.json`)}__name(anchorPath,"anchorPath");function writeAnchor(repository,prNumber,trustRoot){const path=anchorPath(repository,prNumber,trustRoot);mkdirSync(dirname(path),{recursive:true});const anchor={trustRoot,...repository};atomicWriteFileSync(path,`${JSON.stringify(anchor,null,2)}
4
4
  `,NO_FOLLOW)}__name(writeAnchor,"writeAnchor");function readAnchor(repository,prNumber){const path=anchorPath(repository,prNumber,repoRoot());if(!isRegularFile(path))return null;try{const parsed=JSON.parse(readRegularFile(path)??"null");if(parsed&&typeof parsed.trustRoot==="string"&&typeof parsed.host==="string"&&typeof parsed.owner==="string"&&typeof parsed.repo==="string"){return parsed}return null}catch{return null}}__name(readAnchor,"readAnchor");function trustAnchor(state){const anchor=readAnchor(state,state.prNumber);if(!anchor){throw new Error(`PR #${state.prNumber} has no confirmed trust anchor; re-run \`qwen autofix-pr prepare ${state.prNumber}\` (or resume it) to confirm the clone before its worktree can be validated`)}return anchor.trustRoot}__name(trustAnchor,"trustAnchor");function vouchedScanRoots(roots){if(roots.length===0)return[];const main=roots[0];const notNested=roots.filter(r=>!roots.some(other=>other!==r&&isWithinRoot(r,join(other,".qwen","tmp"))));let genuineCommon;let genuineWorktrees;try{const dotGit=join(main,".git");genuineCommon=realpathSync(existsSync(dotGit)?dotGit:main);genuineWorktrees=realpathSync(join(genuineCommon,"worktrees"))}catch{return notNested.slice(0,1)}return notNested.filter(r=>r===main||vouchesForClone(r,genuineCommon,genuineWorktrees))}__name(vouchedScanRoots,"vouchedScanRoots");function vouchesForClone(root,genuineCommon,genuineWorktrees){const dotGit=join(root,".git");let st;try{st=lstatSync(dotGit)}catch{return false}if(st.isDirectory()){try{return realpathSync(dotGit)===genuineCommon}catch{return false}}if(!st.isFile())return false;let text;try{text=readFileSync(dotGit,"utf8")}catch{return false}if(!text.startsWith("gitdir: "))return false;const pointer=text.slice("gitdir: ".length).replace(/[\r\n]+$/,"");let entry;try{entry=realpathSync(isAbsolute(pointer)?pointer:join(root,pointer))}catch{return false}if(dirname(entry)!==genuineWorktrees)return false;let back;try{back=readFileSync(join(entry,"gitdir"),"utf8").replace(/[\r\n]+$/,"")}catch{return false}try{return realpathSync(isAbsolute(back)?back:join(entry,back))===realpathSync(dotGit)}catch{return false}}__name(vouchesForClone,"vouchesForClone");function assertPositiveInteger(value,what){if(!Number.isInteger(value)||value<1){throw new TypeError(`${what} must be a positive integer, got ${value}`)}}__name(assertPositiveInteger,"assertPositiveInteger");function statePaths(root,state){const paths=autofixPrPaths(root,state.prNumber);return state.inPlace?{...paths,worktreePath:state.worktreePath,branch:state.branch}:paths}__name(statePaths,"statePaths");function autofixPrPaths(root,prNumber){assertPositiveInteger(prNumber,"PR number");const tmp=join(root,".qwen","tmp");return{worktreePath:join(tmp,`autofix-pr-${prNumber}`),statePath:join(tmp,`autofix-pr-${prNumber}-state.json`),gatePath:join(tmp,`autofix-pr-${prNumber}-gate.json`),checkedPath:join(tmp,`autofix-pr-${prNumber}-gate.checked`),snapshotPath:join(tmp,`autofix-pr-${prNumber}-snapshot.json`),repliesPath:join(tmp,`autofix-pr-${prNumber}-replies.json`),lockPath:join(tmp,`autofix-pr-${prNumber}.lock`),instructionsPath:join(tmp,`autofix-pr-${prNumber}-instructions.txt`),fixPath:join(tmp,`autofix-pr-${prNumber}-fix.json`),branch:`qwen-autofix/pr-${prNumber}`,headRef:`refs/qwen-autofix/pr-${prNumber}/head`}}__name(autofixPrPaths,"autofixPrPaths");function isRegularFile(path){return lstatSync(path,{throwIfNoEntry:false})?.isFile()===true}__name(isRegularFile,"isRegularFile");function readRegularFile(path){let fd;try{fd=openSync(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0))}catch(err){if(err.code==="ENOENT")return null;throw err}try{if(!fstatSync(fd).isFile()){throw new Error(`${path} is not a regular file`)}return readFileSync(fd,"utf8")}finally{closeSync(fd)}}__name(readRegularFile,"readRegularFile");function readGateCursor(gatePath){if(lstatSync(gatePath,{throwIfNoEntry:false})===void 0){return null}if(!isRegularFile(gatePath)){throw new Error(`${gatePath} is not a regular file`)}const text=readRegularFile(gatePath);if(text===null)return null;const parsed=JSON.parse(text);if(parsed.version!==1){throw new Error(`unsupported autofix-pr gate cursor version in ${gatePath}: ${String(parsed.version)}`)}return{...parsed,reportedTruncated:parsed.reportedTruncated??[]}}__name(readGateCursor,"readGateCursor");function writeGateCursor(gatePath,cursor){atomicWriteFileSync(gatePath,`${JSON.stringify(cursor,null,2)}
5
5
  `,{noFollow:true})}__name(writeGateCursor,"writeGateCursor");function sameRepository(a,b){return normalizeGhHostForUrl(a.host)===normalizeGhHostForUrl(b.host)&&normalizeSegment(a.owner)===normalizeSegment(b.owner)&&normalizeSegment(a.repo)===normalizeSegment(b.repo)}__name(sameRepository,"sameRepository");var SHA_RE=/^[0-9a-f]{40,64}$/;function isBranchName(name){return!(name===""||name==="@"||name.startsWith("-")||name.endsWith("/")||name.endsWith(".")||[...name].some(char=>char.charCodeAt(0)<=32||char==="\x7F")||/[~^:?*[\\]/.test(name)||name.includes("..")||name.includes("@{")||name.includes("//")||name.split("/").some(part=>part.startsWith(".")||part.endsWith(".lock")))}__name(isBranchName,"isBranchName");var SHELL_SPECIAL=/[;&|$`<>()'"{}!#]/;function isCommandSafeName(name){return!SHELL_SPECIAL.test(name)}__name(isCommandSafeName,"isCommandSafeName");function stringList(value){return Array.isArray(value)?value.filter(item=>typeof item==="string"):[]}__name(stringList,"stringList");var isStringList=__name(value=>Array.isArray(value)&&value.every(item=>typeof item==="string"),"isStringList");var isRunList=__name(value=>Array.isArray(value)&&value.every(item=>Number.isInteger(item)),"isRunList");function isPendingPost(value){const post=value;return typeof post==="object"&&post!==null&&(post.where==="summary"||Number.isInteger(post.where))&&isStringList(post.handled)&&typeof post.bodyHash==="string"&&typeof post.sha==="string"&&(post.needsHuman===void 0||isStringList(post.needsHuman))}__name(isPendingPost,"isPendingPost");function stateDefect(state){const word=__name(value=>typeof value==="string"&&value!==""&&!value.startsWith("-"),"word");if(!word(state.remote)||!isBranchName(state.remote)||!isCommandSafeName(state.remote)){return"remote"}if(!word(state.pushTarget))return"pushTarget";if(!word(state.headRefName)||!isBranchName(state.headRefName)){return"headRefName"}if(!word(state.baseRefName)||!isBranchName(state.baseRefName)||!isCommandSafeName(state.baseRefName)){return"baseRefName"}if(!isOwnerRepo(`${state.owner}/${state.repo}`))return"owner/repo";if(typeof state.host!=="string"||!HOSTNAME_RE.test(state.host)){return"host"}if(!Number.isInteger(state.prNumber)||state.prNumber<1){return"prNumber"}if(typeof state.lastKnownHeadSha!=="string"||!SHA_RE.test(state.lastKnownHeadSha)){return"lastKnownHeadSha"}if(!Array.isArray(state.pushedShas)||!state.pushedShas.every(sha=>typeof sha==="string"&&SHA_RE.test(sha))){return"pushedShas"}if(!isStringList(state.handledCommentIds))return"handledCommentIds";if(!isStringList(state.postedCommentIds))return"postedCommentIds";if(state.handledChecks!==void 0&&!isStringList(state.handledChecks)){return"handledChecks"}if(state.rerunChecks!==void 0&&!isStringList(state.rerunChecks)){return"rerunChecks"}if(state.deferredRuns!==void 0&&!isRunList(state.deferredRuns)){return"deferredRuns"}if(state.heldChecks!==void 0&&!isStringList(state.heldChecks)){return"heldChecks"}if(state.pendingPosts!==void 0&&!(Array.isArray(state.pendingPosts)&&state.pendingPosts.every(isPendingPost))){return"pendingPosts"}if(state.pushCount!==void 0&&!(Number.isInteger(state.pushCount)&&state.pushCount>=0)){return"pushCount"}if(state.watch!==void 0&&!isWatchOptions(state.watch)){return"watch"}if(state.needsHuman!==void 0&&!(Array.isArray(state.needsHuman)&&state.needsHuman.every(isNeedsHumanItem))){return"needsHuman"}if(state.reportedNeedsHuman!==void 0&&!(typeof state.reportedNeedsHuman==="object"&&state.reportedNeedsHuman!==null&&typeof state.reportedNeedsHuman.sha==="string"&&SHA_RE.test(state.reportedNeedsHuman.sha)&&isStringList(state.reportedNeedsHuman.texts))){return"reportedNeedsHuman"}if(state.preparedAt!==void 0&&typeof state.preparedAt!=="string"){return"preparedAt"}if(state.ended!==void 0&&!(typeof state.ended==="object"&&state.ended!==null&&typeof state.ended.at==="string"&&typeof state.ended.reason==="string")){return"ended"}if(state.failingChecks!==void 0&&!(Array.isArray(state.failingChecks)&&state.failingChecks.every(isFailingCheck))){return"failingChecks"}return null}__name(stateDefect,"stateDefect");function isFailingCheck(value){const check=value;return typeof check==="object"&&check!==null&&typeof check.identity==="string"&&typeof check.check==="string"&&typeof check.head==="string"&&Number.isInteger(check.pushes)&&check.pushes>=0&&SHA_RE.test(check.head)&&(check.lastPush===void 0||SHA_RE.test(check.lastPush))&&(check.unanswered===void 0||Array.isArray(check.unanswered)&&check.unanswered.every(entry=>typeof entry==="object"&&entry!==null&&typeof entry.sha==="string"&&SHA_RE.test(entry.sha)&&Number.isInteger(entry.pushes)&&entry.pushes>=0))}__name(isFailingCheck,"isFailingCheck");function isWatchOptions(value){const watch=value;return typeof watch==="object"&&watch!==null&&WATCH_INTERVALS.includes(watch.every)&&typeof watch.reply==="boolean"&&typeof watch.instructions==="string"&&watch.instructions.length<=MAX_INSTRUCTIONS_CHARS&&!/[\p{Cc}\p{Cf}\u2028\u2029]/u.test(watch.instructions)&&(watch.task===void 0||/^[0-9a-f]{12}$/.test(watch.task))}__name(isWatchOptions,"isWatchOptions");function isNeedsHumanItem(value){const item=value;return typeof item==="object"&&item!==null&&typeof item.sha==="string"&&typeof item.at==="string"&&typeof item.text==="string"}__name(isNeedsHumanItem,"isNeedsHumanItem");function readState(statePath){const entry=lstatSync(statePath,{throwIfNoEntry:false});if(entry===void 0)return null;if(!entry.isFile()){throw new Error(`${statePath} is not a regular file; \`qwen autofix-pr cleanup <pr> --force\` discards it.`)}let text;try{text=readRegularFile(statePath)}catch{throw new Error(`${statePath} is not a regular file; \`qwen autofix-pr cleanup <pr> --force\` discards it.`)}if(text===null)return null;const parsed=JSON.parse(text);if(parsed.version!==1){throw new Error(`unsupported autofix-pr state version in ${statePath}: ${String(parsed.version)}`)}const defect=stateDefect(parsed);if(defect){throw new Error(`${statePath} has an invalid ${defect}; run \`qwen autofix-pr cleanup ${String(parsed.prNumber)} --force\` and prepare the watch again.`)}const{watch,ended,needsHuman,reportedNeedsHuman,failingChecks}=parsed;return{...parsed,...watch?{watch:{every:watch.every,reply:watch.reply,instructions:watch.instructions,...watch.task!==void 0?{task:watch.task}:{}}}:{},...ended?{ended:{at:ended.at,reason:ended.reason}}:{},...needsHuman?{needsHuman:needsHuman.map(({sha,at,text:text2})=>({sha,at,text:text2}))}:{},...reportedNeedsHuman?{reportedNeedsHuman:{sha:reportedNeedsHuman.sha,texts:[...reportedNeedsHuman.texts]}}:{},...failingChecks?{failingChecks:failingChecks.map(({identity,check,head,pushes,lastPush,unanswered})=>({identity,check,head,pushes,...lastPush===void 0?{}:{lastPush},...unanswered===void 0?{}:{unanswered:unanswered.map(({sha,pushes:pushes2})=>({sha,pushes:pushes2}))}}))}:{}}}__name(readState,"readState");var NO_FOLLOW={noFollow:true};function writeState(statePath,state){atomicWriteFileSync(statePath,`${JSON.stringify(state,null,2)}
6
6
  `,NO_FOLLOW)}__name(writeState,"writeState");function historyPath(paths,repository){const slug=[normalizeGhHostForUrl(repository.host).replace(/:/g,"@"),normalizeSegment(repository.owner),normalizeSegment(repository.repo)].join("+").replace(/[^a-z0-9._@+-]/g,"_");return join(dirname(paths.statePath),`${historyPrefix(paths)}${slug}.history.json`)}__name(historyPath,"historyPath");function historyPrefix(paths){return basename(paths.statePath).replace(/-state\.json$/,"-history-")}__name(historyPrefix,"historyPrefix");function readHistory(path){if(lstatSync(path,{throwIfNoEntry:false})===void 0)return null;if(!isRegularFile(path))throw new Error(`${path} is not a regular file`);const parsed=JSON.parse(readFileSync(path,"utf8"));if(parsed.version!==1){throw new Error(`unsupported autofix-pr history version in ${path}: ${String(parsed.version)}`)}return{...parsed,handledCommentIds:stringList(parsed.handledCommentIds),postedCommentIds:stringList(parsed.postedCommentIds),handledChecks:stringList(parsed.handledChecks),rerunChecks:stringList(parsed.rerunChecks),handledConflictSha:typeof parsed.handledConflictSha==="string"&&SHA_RE.test(parsed.handledConflictSha)?parsed.handledConflictSha:null,pendingPosts:Array.isArray(parsed.pendingPosts)?parsed.pendingPosts.filter(isPendingPost):[],deferredRuns:Array.isArray(parsed.deferredRuns)?parsed.deferredRuns.filter(run=>Number.isInteger(run)):[],heldChecks:stringList(parsed.heldChecks)}}__name(readHistory,"readHistory");function keepHistory(paths,state){const path=historyPath(paths,state);let earlier=null;try{earlier=readHistory(path)}catch{}if(earlier&&!sameRepository(earlier,state))earlier=null;const union=__name((a,b)=>[...new Set([...stringList(a),...stringList(b)])],"union");const history={version:1,host:state.host,owner:state.owner,repo:state.repo,prNumber:state.prNumber,handledCommentIds:union(earlier?.handledCommentIds,state.handledCommentIds),postedCommentIds:union(earlier?.postedCommentIds,state.postedCommentIds),handledChecks:union(earlier?.handledChecks,state.handledChecks),rerunChecks:union(earlier?.rerunChecks,state.rerunChecks),handledConflictSha:state.handledConflictSha??earlier?.handledConflictSha??null,pendingPosts:state.pendingPosts??earlier?.pendingPosts??[],deferredRuns:state.deferredRuns??earlier?.deferredRuns??[],heldChecks:state.heldChecks??earlier?.heldChecks??[]};const entry=lstatSync(path,{throwIfNoEntry:false});if(entry&&!entry.isFile()&&!entry.isSymbolicLink()){rmSync(path,{recursive:true,force:true})}atomicWriteFileSync(path,`${JSON.stringify(history,null,2)}
@@ -2,7 +2,7 @@
2
2
  "use strict";
3
3
  import{resolvePolicyToolSettings}from"./chunk-IV3HAIUN.js";import{MEDIA_MEMORY_FILE_NAME}from"./chunk-XFMPZINJ.js";import{DEFAULT_OMNI_PROCESSING_LIMITS,conditionUsesNamespace,evaluateFixedPolicyCondition}from"./chunk-HN5UYLPU.js";import{OmniJsonCacheFile}from"./chunk-AMGUAA4G.js";import{OBJECT_EXTENSION_RE}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile}from"./chunk-ZBHL2CXR.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var AUDIO_TOKENS_PER_SECOND=7;var VISUAL_PIXELS_PER_TOKEN=32*32*2;function usable(value){return value!==void 0&&Number.isFinite(value)&&value>0}__name(usable,"usable");function estimateRawResourceTokens(media){const unavailable={estimatedTokenCount:0,method:"raw-resource-v1",status:"unavailable"};switch(media.modality){case"audio":{const durationMs=media.metadata.durationMs;if(!usable(durationMs))return unavailable;return{estimatedTokenCount:Math.ceil(durationMs/1e3*AUDIO_TOKENS_PER_SECOND),method:"raw-resource-v1",status:"ok"}}case"image":{const{width,height,frameCount}=media.metadata;if(!usable(width)||!usable(height))return unavailable;const frames=usable(frameCount)?frameCount:1;return{estimatedTokenCount:Math.ceil(width*height*frames/VISUAL_PIXELS_PER_TOKEN),method:"raw-resource-v1",status:"ok"}}case"video":{const{width,height,durationMs,frameRate}=media.metadata;if(!usable(width)||!usable(height)||!usable(durationMs)||!usable(frameRate)){return unavailable}const frameCount=Math.ceil(durationMs/1e3*frameRate);return{estimatedTokenCount:Math.ceil(width*height*frameCount/VISUAL_PIXELS_PER_TOKEN),method:"raw-resource-v1",status:"ok"}}default:return unavailable}}__name(estimateRawResourceTokens,"estimateRawResourceTokens");init_esbuild_shims();import{createHash}from"node:crypto";import path from"node:path";var MAX_CACHED_DISCLOSURE_LENGTH=2048;var FINGERPRINT_EXCLUDED_KEYS=new Set(["inputPath","outputDir","resourceId"]);function stableStringify(value){if(Array.isArray(value)){return`[${value.map(stableStringify).join(",")}]`}if(typeof value==="object"&&value!==null){const record=value;const body=Object.keys(record).sort().map(k=>`${JSON.stringify(k)}:${stableStringify(record[k])}`).join(",");return`{${body}}`}return JSON.stringify(value)??"null"}__name(stableStringify,"stableStringify");function computePolicyFingerprint(toolName,args,toolVersion="1"){const tunables={};for(const[k,v]of Object.entries(args)){if(!FINGERPRINT_EXCLUDED_KEYS.has(k)&&v!==void 0){tunables[k]=v}}return createHash("sha256").update(`${toolName}
4
4
  ${stableStringify(tunables)}
5
- ${toolVersion}`).digest("hex")}__name(computePolicyFingerprint,"computePolicyFingerprint");var OmniDegradationCache=class{static{__name(this,"OmniDegradationCache")}file;constructor(omniRootDir){this.file=new OmniJsonCacheFile(path.join(omniRootDir,"policy-cache.json"),"omni:policy-cache")}key(originalSha256,policyFingerprint){return`${originalSha256}|${policyFingerprint}`}async get(originalSha256,policyFingerprint){return this.file.access(null,entries=>{const key=this.key(originalSha256,policyFingerprint);const entry=entries[key];if(!entry)return{result:null};if(!/^[0-9a-f]{64}$/.test(entry.degradedSha256)||typeof entry.extension!=="string"||!OBJECT_EXTENSION_RE.test(entry.extension)||typeof entry.disclosure!=="string"||entry.disclosure.length===0||entry.disclosure.length>MAX_CACHED_DISCLOSURE_LENGTH||typeof entry.mimeType!=="string"||entry.mimeType.length===0||entry.role!==void 0&&(typeof entry.role!=="string"||entry.role.length===0)){delete entries[key];return{result:null,changed:true}}return{result:entry}})}async put(originalSha256,policyFingerprint,entry){return this.file.access(void 0,entries=>{entries[this.key(originalSha256,policyFingerprint)]={...entry,createdAt:new Date().toISOString()};return{result:void 0,changed:true}})}async removeByOriginalSha256(originalSha256){return this.file.access(void 0,entries=>{const prefix=`${originalSha256}|`;let changed=false;for(const k of Object.keys(entries)){if(k.startsWith(prefix)){delete entries[k];changed=true}}return{result:void 0,changed}})}async removeByDegradedSha256(degradedSha256){return this.file.access(void 0,entries=>{let changed=false;for(const[k,v]of Object.entries(entries)){if(v.degradedSha256===degradedSha256){delete entries[k];changed=true}}return{result:void 0,changed}})}};init_esbuild_shims();var DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES=1024*1024*1024;var OmniTransportGuardError=class extends Error{static{__name(this,"OmniTransportGuardError")}sessionResourceId;constructor(message,options){super(message,options);this.name="OmniTransportGuardError"}};function effectiveMaxUploadFileBytes(config){const configured=config.getOmniMaxUploadFileBytes?.();return configured!==void 0&&configured>0?configured:DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES}__name(effectiveMaxUploadFileBytes,"effectiveMaxUploadFileBytes");function assertWithinByteLimit(config,sizeBytes,displayName){const maxBytes=effectiveMaxUploadFileBytes(config);if(sizeBytes>maxBytes){throw new OmniTransportGuardError(`${displayName} exceeds the omni upload limit: ${sizeBytes} bytes > ${maxBytes} bytes (omni.processing.transportGuard.maxUploadFileBytes). Reduce the file size before retrying.`)}}__name(assertWithinByteLimit,"assertWithinByteLimit");function assertWithinDurationLimit(config,media,displayName){const maxSeconds=config.getOmniMaxDurationSeconds?.();if(maxSeconds===void 0||maxSeconds<=0)return;const durationMs=media.metadata.durationMs;if(durationMs===void 0||!Number.isFinite(durationMs))return;const seconds=durationMs/1e3;if(seconds>maxSeconds){throw new OmniTransportGuardError(`${displayName} exceeds the omni duration limit: ${Math.round(seconds)}s > ${maxSeconds}s (omni.processing.transportGuard.maxDurationSeconds). Clip a shorter span \u2014 downscaling cannot bring a long file within a duration limit.`)}}__name(assertWithinDurationLimit,"assertWithinDurationLimit");function assertWithinTokenLimit(config,media,displayName){const estimate=estimateRawResourceTokens(media);const maxTokens=config.getOmniMaxEstimatedTokens?.();if(maxTokens===void 0||maxTokens<=0)return estimate;if(estimate.status!=="ok")return estimate;if(estimate.estimatedTokenCount>maxTokens){throw new OmniTransportGuardError(`${displayName} exceeds the omni estimated-token limit: ~${estimate.estimatedTokenCount} tokens (${estimate.method}) > ${maxTokens} (omni.processing.transportGuard.maxEstimatedTokens). Reduce duration/resolution or raise the limit.`)}return estimate}__name(assertWithinTokenLimit,"assertWithinTokenLimit");init_esbuild_shims();import fs from"node:fs/promises";import path2 from"node:path";var debugLogger=createDebugLogger("omni:gc");var OBJECT_NAME_RE=/^([0-9a-f]{64})\.[A-Za-z0-9][A-Za-z0-9.]*$/;var SKIPPED={ran:false,deletedObjects:0,deletedBytes:0,remainingBytes:0,derivationsSuspended:false};var gcOnce=new Map;var suspendedRoots=new Set;function effectiveOmniStorageMaxTotalBytes(config){const configured=config.getOmniStorageMaxTotalBytes();const floor=10*effectiveMaxUploadFileBytes(config);if(configured<floor){debugLogger.warn(`omni.storage.maxTotalBytes (${configured}) is below 10\xD7 the transport guard's single-media limit; using ${floor} bytes instead (the budget must hold at least ten normal uploads).`);return floor}return configured}__name(effectiveOmniStorageMaxTotalBytes,"effectiveOmniStorageMaxTotalBytes");function isOmniDerivationSuspended(omniRootDir){return suspendedRoots.has(path2.resolve(omniRootDir))}__name(isOmniDerivationSuspended,"isOmniDerivationSuspended");async function settleOmniGc(omniRootDir){const existing=gcOnce.get(path2.resolve(omniRootDir));if(existing)await existing}__name(settleOmniGc,"settleOmniGc");async function isRealDirectory(p){try{return(await fs.lstat(p)).isDirectory()}catch{return false}}__name(isRealDirectory,"isRealDirectory");async function listObjects(objectsDir){const out=[];if(!await isRealDirectory(objectsDir))return out;let shards;try{shards=await fs.readdir(objectsDir)}catch{return out}for(const shard of shards){const shardDir=path2.join(objectsDir,shard);if(!await isRealDirectory(shardDir))continue;let names;try{names=await fs.readdir(shardDir)}catch{continue}for(const name of names){const match=OBJECT_NAME_RE.exec(name);if(!match)continue;const filePath=path2.join(shardDir,name);try{const st=await fs.lstat(filePath);if(!st.isFile())continue;out.push({sha256:match[1],filePath,mtimeMs:st.mtimeMs,sizeBytes:st.size})}catch{}}}return out}__name(listObjects,"listObjects");async function deleteObject(object,options){try{await fs.rm(object.filePath,{force:true})}catch(err){debugLogger.debug(`gc: failed to delete ${object.sha256}: ${err instanceof Error?err.message:err}`);return false}try{await options.uploadCache?.removeBySha256(object.sha256)}catch{}try{await options.degradationCache?.removeByOriginalSha256(object.sha256);await options.degradationCache?.removeByDegradedSha256(object.sha256)}catch{}debugLogger.debug(`gc: deleted unreferenced object ${object.sha256} (${object.sizeBytes} bytes)`);return true}__name(deleteObject,"deleteObject");function runOmniGcOnce(options){const rootKey=path2.resolve(options.store.getOmniRootDir());const existing=gcOnce.get(rootKey);if(existing)return existing;const run=sweep(options,rootKey).catch(err=>{debugLogger.debug(`gc: run failed, skipped: ${err instanceof Error?err.message:err}`);return SKIPPED});gcOnce.set(rootKey,run);return run}__name(runOmniGcOnce,"runOmniGcOnce");async function recentlyRecoveredFromCorruption(omniRootDir,retentionDays,nowMs){const prefix=`${MEDIA_MEMORY_FILE_NAME}.corrupt-`;let names;try{names=await fs.readdir(omniRootDir)}catch{return false}const cutoff=nowMs-retentionDays*24*36e5;for(const name of names){if(!name.startsWith(prefix))continue;const stamp=Number(name.slice(prefix.length));if(Number.isFinite(stamp)&&stamp>=cutoff)return true;try{const st=await fs.lstat(path2.join(omniRootDir,name));if(st.mtimeMs>=cutoff)return true}catch{return true}}return false}__name(recentlyRecoveredFromCorruption,"recentlyRecoveredFromCorruption");async function sweep(options,rootKey){const nowMsForGuard=options.nowMs??Date.now();const refs=await options.memoryService.collectManagedRefs();if(refs===null){debugLogger.debug("gc: memory snapshot unreadable, skipping run");return SKIPPED}if(await recentlyRecoveredFromCorruption(options.store.getOmniRootDir(),options.retentionDays,nowMsForGuard)){debugLogger.debug("gc: memory ledger recently recovered from corruption, skipping run");return SKIPPED}const objectsDir=options.store.getObjectsDir();for(const fileRef of options.registry?.activeFileRefs()??[]){const name=path2.basename(fileRef);const match=OBJECT_NAME_RE.exec(name);if(match&&fileRef.startsWith(objectsDir))refs.add(match[1])}const nowMs=options.nowMs??Date.now();const cutoffMs=nowMs-options.retentionDays*24*36e5;const objects=await listObjects(objectsDir);let deletedObjects=0;let deletedBytes=0;const survivors=[];const touchedSinceListing=__name(async(object,freshCutoffMs)=>{try{return(await fs.lstat(object.filePath)).mtimeMs>=freshCutoffMs}catch{return true}},"touchedSinceListing");for(const object of objects){if(refs.has(object.sha256)||object.mtimeMs>=cutoffMs){survivors.push(object);continue}if(await touchedSinceListing(object,cutoffMs)){survivors.push(object);continue}if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes}else{survivors.push(object)}}let remainingBytes=survivors.reduce((sum,o)=>sum+o.sizeBytes,0);if(remainingBytes>options.maxTotalBytes){const freshRefs=await options.memoryService.collectManagedRefs();if(freshRefs===null){debugLogger.debug("gc: ledger unreadable at budget pass, skipping budget deletions")}else{const unreferenced=survivors.filter(o=>!refs.has(o.sha256)&&!freshRefs.has(o.sha256)).sort((a,b)=>a.mtimeMs-b.mtimeMs);for(const object of unreferenced){if(remainingBytes<=options.maxTotalBytes)break;if(await touchedSinceListing(object,nowMs))continue;if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes;remainingBytes-=object.sizeBytes}}}}const derivationsSuspended=remainingBytes>options.maxTotalBytes;if(derivationsSuspended){suspendedRoots.add(rootKey);debugLogger.warn(`omni object store over budget with only referenced objects left (${remainingBytes} > ${options.maxTotalBytes} bytes); new policy derivations are suspended for this session. Raise omni.storage.maxTotalBytes or delete memory records you no longer need \u2014 either change takes effect at the next session start (the GC runs once per process).`)}else{suspendedRoots.delete(rootKey)}if(deletedObjects>0){debugLogger.debug(`gc: removed ${deletedObjects} object(s) / ${deletedBytes} bytes; ${remainingBytes} bytes remain`)}return{ran:true,deletedObjects,deletedBytes,remainingBytes,derivationsSuspended}}__name(sweep,"sweep");init_esbuild_shims();import{createHash as createHash2,randomBytes}from"node:crypto";import fs2 from"node:fs/promises";import path3 from"node:path";var debugLogger2=createDebugLogger("omni:policy");var MAX_FILE_ARTIFACT_BYTES=256*1024;var OmniPolicyExecutionError=class extends Error{constructor(message,policyId,options){super(message,options);this.policyId=policyId;this.name="OmniPolicyExecutionError"}static{__name(this,"OmniPolicyExecutionError")}};function resolveArtifactSelector(artifacts,kind,role){if(role!==void 0){const byRole=artifacts[`role:${role}`];if(byRole)return byRole}const byKind=artifacts[`kind:${kind}`];if(byKind)return byKind;return artifacts["*"]??"retain"}__name(resolveArtifactSelector,"resolveArtifactSelector");function resourceConditionContext(recognized,shared){const resource={};const set=__name((field,value)=>{if(typeof value==="number"&&!Number.isNaN(value)){resource[field]=value}},"set");const m=recognized.metadata;set("sizeBytes",recognized.sizeBytes);set("durationMs",m.durationMs);set("width",m.width);set("height",m.height);set("maxWidth",m.width);set("maxHeight",m.height);set("frameRate",m.frameRate);set("frameCount",m.frameCount);set("bitRate",m.bitRate);set("sampleRateHz",m.sampleRateHz);set("channels",m.channels);const estimate=estimateRawResourceTokens(recognized);if(estimate.status==="ok"){set("estimatedTokenCount",estimate.estimatedTokenCount)}return{resource,...shared}}__name(resourceConditionContext,"resourceConditionContext");var MEMORY_ROLE_FIELDS={transcript:"hasTranscript",ocr:"hasOcr",caption:"hasCaption",summary:"hasSummary",keyframe:"hasKeyframes",clip:"hasClip"};async function memoryConditionNamespace(memory,binding){if(!memory||!binding)return void 0;const roles=await memory.service.collectVersionOutputRoles(binding);if(!roles)return void 0;const namespace={};for(const field of Object.values(MEMORY_ROLE_FIELDS)){namespace[field]=0}for(const role of roles){const field=MEMORY_ROLE_FIELDS[role];if(field)namespace[field]=1}return namespace}__name(memoryConditionNamespace,"memoryConditionNamespace");function requestConditionNamespace(items){let total=0;for(const item of items){if(!item.deliver)continue;const estimate=estimateRawResourceTokens(item.recognized);if(estimate.status!=="ok")return void 0;total+=estimate.estimatedTokenCount}return{totalEstimatedMediaTokens:total}}__name(requestConditionNamespace,"requestConditionNamespace");function sortPolicies(policies){return[...policies].sort((a,b)=>b.priority-a.priority||a.id.localeCompare(b.id))}__name(sortPolicies,"sortPolicies");var resourceGates=new Map;async function acquireResourceSlot(rootDir,limit){const effectiveLimit=Math.max(1,Math.floor(limit));let gate=resourceGates.get(rootDir);if(!gate){gate={active:0,waiters:[]};resourceGates.set(rootDir,gate)}const heldGate=gate;if(heldGate.active>=effectiveLimit){await new Promise(resolve=>heldGate.waiters.push(resolve))}else{heldGate.active++}let released=false;return()=>{if(released)return;released=true;const next=heldGate.waiters.shift();if(next){next();return}heldGate.active--;if(heldGate.active===0&&heldGate.waiters.length===0){resourceGates.delete(rootDir)}}}__name(acquireResourceSlot,"acquireResourceSlot");async function runFixedPolicies(config,source,options){const policies=sortPolicies(options.policies);const limits=options.limits??DEFAULT_OMNI_PROCESSING_LIMITS;const releaseSlot=await acquireResourceSlot(options.store.getOmniRootDir(),limits.maxConcurrentResources);try{return await runFixedPoliciesUnbounded(config,source,options,{policies,limits})}finally{releaseSlot()}}__name(runFixedPolicies,"runFixedPolicies");async function runFixedPoliciesUnbounded(config,source,options,normalized){const{policies,limits}=normalized;const cache=options.degradationCache??new OmniDegradationCache(options.store.getOmniRootDir());const records=[];const fileDeliveries=[];const items=[{filePath:source.filePath,recognized:source.recognized,label:source.displayName,origin:source.origin,sha256:source.sha256,memoryBinding:options.memory?.sourceBinding,lineageRuns:new Map,depth:0,deliver:true,process:true}];let runsUsed=0;let artifactsProduced=0;let derivedBytesProduced=0;let budgetExhausted=false;const stopOnBudget=__name((policy,item,reason)=>{budgetExhausted=true;records.push({policyId:policy.id,toolName:policy.toolName,outcome:"budget_exhausted",resource:item.label,error:reason});debugLogger2.debug(`per-root policy budget exhausted on ${item.label}: ${reason}; no further derivation for this root (committed deliveries stand)`)},"stopOnBudget");for(let i=0;i<items.length&&!budgetExhausted;i++){const item=items[i];if(!item.process)continue;if(item.recognized.modality==="image"&&(item.recognized.metadata.frameCount??1)>1){debugLogger2.debug(`animated image ${item.label} (${item.recognized.metadata.frameCount} frames) excluded from policy matching (D9)`);continue}const needsMemoryNamespace=policies.some(policy=>policy.when&&conditionUsesNamespace(policy.when,"memory"));const sharedConditionContext={request:options.conditionContext?.request??requestConditionNamespace(items),session:options.conditionContext?.session,memory:needsMemoryNamespace?await memoryConditionNamespace(options.memory,item.memoryBinding):void 0};for(const policy of policies){if(!policy.mediaTypes.includes(item.recognized.modality))continue;if(!policy.origins.includes(item.origin))continue;const runs=item.lineageRuns.get(policy.id)??0;if(runs>=policy.maxRunsPerLineage)continue;if(policy.when){const evaluation=evaluateFixedPolicyCondition(policy.when,resourceConditionContext(item.recognized,sharedConditionContext));if(evaluation.outcome==="no_match")continue;if(evaluation.outcome==="unavailable"&&policy.onConditionUnavailable==="skip"){records.push({policyId:policy.id,toolName:policy.toolName,outcome:"condition_unavailable",resource:item.label,missingFields:evaluation.missingFields});continue}}if(runsUsed>=limits.maxPolicyRunsPerRoot){stopOnBudget(policy,item,`maxPolicyRunsPerRoot (${limits.maxPolicyRunsPerRoot}) reached`);break}runsUsed++;item.lineageRuns.set(policy.id,runs+1);try{const execution=await executePolicy(config,item,policy,options.store,cache,options.signal,options.memory&&item.memoryBinding?{service:options.memory.service,source:item.memoryBinding}:void 0);records.push({policyId:policy.id,toolName:policy.toolName,outcome:execution.outcome,resource:item.label});if(execution.outcome==="no_op")continue;if(policy.output.source==="omit")item.deliver=false;const childDepth=item.depth+1;const depthAllowsReprocess=childDepth<limits.maxLineageDepth;if(policy.output.reprocessMedia&&!depthAllowsReprocess){debugLogger2.debug(`maxLineageDepth (${limits.maxLineageDepth}) reached under ${item.label}; derivatives deliver but do not re-enter policy matching`)}for(const derived of execution.derived){artifactsProduced++;derivedBytesProduced+=derived.recognized.sizeBytes;items.push({...derived,label:`${item.label} \u2192 ${policy.id}`,origin:"policy",lineageRuns:new Map(item.lineageRuns),depth:childDepth,deliver:resolveArtifactSelector(policy.output.artifacts,derived.recognized.modality,derived.role)==="include",process:policy.output.reprocessMedia&&depthAllowsReprocess})}for(const file of execution.derivedFiles){artifactsProduced++;derivedBytesProduced+=file.sizeBytes;if(resolveArtifactSelector(policy.output.artifacts,"file",file.role)==="include"){fileDeliveries.push(file)}}if(artifactsProduced>limits.maxArtifactsPerRoot){stopOnBudget(policy,item,`maxArtifactsPerRoot (${limits.maxArtifactsPerRoot}) exceeded`);break}if(derivedBytesProduced>limits.maxDerivedBytesPerRoot){stopOnBudget(policy,item,`maxDerivedBytesPerRoot (${limits.maxDerivedBytesPerRoot}) exceeded`);break}}catch(err){if(options.signal?.aborted)throw err;const message=err instanceof Error?err.message:String(err);records.push({policyId:policy.id,toolName:policy.toolName,outcome:"failed",resource:item.label,error:message});debugLogger2.debug(`fixed policy ${policy.id} (${policy.toolName}) failed on ${item.label}: ${message}`);if(policy.onFailure==="abort"||policy.stage==="transport_guard"){throw new OmniPolicyExecutionError(`Fixed policy ${policy.id} failed: ${message}`,policy.id,{cause:err})}}}}return{deliveries:items.filter(item=>item.deliver).map(item=>({filePath:item.filePath,recognized:item.recognized,sha256:item.sha256,disclosure:item.disclosure,degraded:item.degraded,memoryBinding:item.memoryBinding})),fileDeliveries,records}}__name(runFixedPoliciesUnbounded,"runFixedPoliciesUnbounded");async function executePolicy(config,item,policy,store,cache,signal,memory){const tool=config.getToolRegistry().getTool(policy.toolName);const descriptor=tool?.mediaPolicyDescriptor;if(!descriptor){throw new Error(`tool ${policy.toolName} is not a registered media-policy tool`)}item.sha256??=await hashFileSha256(item.filePath,signal);const settingsDefaults=resolvePolicyToolSettings(config,policy.toolName);const effectiveArguments={...settingsDefaults,...policy.arguments};const fingerprint=computePolicyFingerprint(policy.toolName,effectiveArguments,descriptor.version);const startedAt=new Date().toISOString();if(memory){const reusable=await memory.service.findReusableOutputs(item.sha256,fingerprint);const rebuilt=reusable?await rebuildReusedOutputs(reusable,descriptor,store,signal):void 0;if(rebuilt){debugLogger2.debug(`memory reuse hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026 outputs=${rebuilt.outputs.length} (tool not executed)`);const commit=await memory.service.commitPolicySucceeded({invocationId:"memory-reuse",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:rebuilt.outputs});return{outcome:"succeeded",derived:rebuilt.derived.map(d=>({...d,memoryBinding:commit?.mediaBindings.get(d.sha256)})),derivedFiles:rebuilt.derivedFiles}}}const hit=await cache.get(item.sha256,fingerprint);if(hit){try{const objectPath=store.objectPathFor(hit.degradedSha256,hit.extension);const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(stat?.isFile()&&!stat.isSymbolicLink()){const actualSha256=await hashFileSha256(objectPath,signal);if(actualSha256===hit.degradedSha256){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(declared){debugLogger2.debug(`degradation cache hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026`);const commit=memory?await memory.service.commitPolicySucceeded({invocationId:"cache-hit",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:[{kind:"media",objectPath,sha256:hit.degradedSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:hit.role,disclosure:hit.disclosure}]}):void 0;return{outcome:"cache_hit",derived:[{filePath:objectPath,recognized,sha256:hit.degradedSha256,disclosure:hit.disclosure,degraded:true,role:hit.role,memoryBinding:commit?.mediaBindings.get(hit.degradedSha256)}],derivedFiles:[]}}debugLogger2.debug(`degradation cache hit for policy=${policy.id} recognized as undeclared media type ${recognized.detectedMimeType}; dropping the entry and re-transcoding`)}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`degradation cache hit could not be verified for policy=${policy.id}: ${err instanceof Error?err.message:String(err)}; dropping the entry and re-transcoding`)}await cache.removeByDegradedSha256(hit.degradedSha256)}await settleOmniGc(store.getOmniRootDir());if(isOmniDerivationSuspended(store.getOmniRootDir())){throw new Error(`omni object store is over its byte budget with only memory-referenced objects left; new policy derivations are suspended. Raise omni.storage.maxTotalBytes or delete memory records you no longer need, then start a new session \u2014 the budget is re-evaluated once per process.`)}const invocationId=randomBytes(8).toString("hex");const stagingDir=await store.createStagingDir(invocationId);let failure;try{const request={callId:invocationId,name:policy.toolName,args:{...effectiveArguments,inputPath:item.filePath,outputDir:stagingDir},isClientInitiated:true,prompt_id:`omni-fixed-policy-${invocationId}`,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage}};const{executeToolCall}=await import("./nonInteractiveToolExecutor-QPQYR6IS.js");const response=await executeToolCall(config,request,signal??new AbortController().signal,{recordToolResult:false});if(response.error){throw new Error(response.error.message,{cause:response.error})}const batch=response.policyArtifacts;if(!batch||batch.artifacts.length===0){throw new Error(`tool ${policy.toolName} succeeded but produced no policy artifacts`)}const validated=await Promise.all(batch.artifacts.map(artifact=>validateArtifact(artifact,descriptor,stagingDir,signal)));assertRequiredOutputsPresent(descriptor,validated,policy.toolName);if(validated.every(a=>a.sha256===item.sha256)){return{outcome:"no_op",derived:[],derivedFiles:[]}}const promoted=await Promise.all(validated.map(async artifact=>{const mimeType=artifact.kind==="media"?artifact.recognized.detectedMimeType:artifact.mimeType;const put=await store.putFile(artifact.absolutePath,artifact.sha256,extensionForMime(mimeType),signal);return{artifact,objectPath:put.objectPath}}));const derived=[];const derivedFiles=[];for(const{artifact,objectPath}of promoted){if(artifact.kind==="media"){derived.push({filePath:objectPath,recognized:artifact.recognized,sha256:artifact.sha256,disclosure:artifact.disclosure,degraded:artifact.lossy,role:artifact.role})}else{derivedFiles.push({filePath:objectPath,role:artifact.role,mimeType:artifact.mimeType,text:artifact.text,sha256:artifact.sha256,sizeBytes:artifact.sizeBytes,disclosure:artifact.disclosure})}}if(memory){const outputs=promoted.map(({artifact,objectPath})=>artifact.kind==="media"?{kind:"media",objectPath,sha256:artifact.sha256,mediaType:artifact.recognized.modality,metadata:artifact.recognized.metadata,sizeBytes:artifact.recognized.sizeBytes,mimeType:artifact.recognized.detectedMimeType,role:artifact.role,disclosure:artifact.disclosure}:{kind:"text",objectPath,sha256:artifact.sha256,mimeType:artifact.mimeType,text:artifact.text,sizeBytes:artifact.sizeBytes,role:artifact.role,disclosure:artifact.disclosure});const commit=await memory.service.commitPolicySucceeded({invocationId,source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs});if(commit){for(const entry of derived){entry.memoryBinding=commit.mediaBindings.get(entry.sha256)}}}if(validated.length===1&&validated[0].kind==="media"&&validated[0].disclosure){await cache.put(item.sha256,fingerprint,{degradedSha256:validated[0].sha256,extension:extensionForMime(validated[0].recognized.detectedMimeType),disclosure:validated[0].disclosure,mimeType:validated[0].recognized.detectedMimeType,...validated[0].role!==void 0?{role:validated[0].role}:{}})}return{outcome:"succeeded",derived,derivedFiles}}catch(err){failure=err;throw err}finally{if(failure===void 0||signal?.aborted){await store.removeStagingDir(invocationId).catch(()=>{})}else{try{await store.quarantineInvocation(invocationId,{policyId:policy.id,toolName:policy.toolName,reason:failure instanceof Error?failure.message:String(failure)})}catch{await store.removeStagingDir(invocationId).catch(()=>{})}}}}__name(executePolicy,"executePolicy");async function rebuildReusedOutputs(reusable,descriptor,store,signal){const outputs=[];const derived=[];const derivedFiles=[];try{for(const record of reusable.outputs){const objectPath=record.objectPath??store.objectPathFor(record.sha256,extensionForMime(record.mimeType));const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink())return void 0;if(await hashFileSha256(objectPath,signal)!==record.sha256){return void 0}if(record.kind==="media"){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!declared)return void 0;outputs.push({kind:"media",objectPath,sha256:record.sha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:record.role,disclosure:record.disclosure});derived.push({filePath:objectPath,recognized,sha256:record.sha256,disclosure:record.disclosure,degraded:record.disclosure!==void 0,role:record.role})}else{const text=await fs2.readFile(objectPath,"utf8");outputs.push({kind:"text",objectPath,sha256:record.sha256,mimeType:record.mimeType,text,sizeBytes:record.sizeBytes,role:record.role,disclosure:record.disclosure});derivedFiles.push({filePath:objectPath,role:record.role,mimeType:record.mimeType,text,sha256:record.sha256,sizeBytes:record.sizeBytes,disclosure:record.disclosure})}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`memory reuse could not be verified, re-deriving: ${err instanceof Error?err.message:String(err)}`);return void 0}return{outputs,derived,derivedFiles}}__name(rebuildReusedOutputs,"rebuildReusedOutputs");async function validateArtifact(artifact,descriptor,stagingDir,signal){if(artifact.storage!=="workspace"||!artifact.workspacePath){throw new Error(`policy artifact "${artifact.title}" is not a workspace file`)}const absolutePath=path3.resolve(stagingDir,artifact.workspacePath);if(!absolutePath.startsWith(stagingDir+path3.sep)){throw new Error(`policy artifact "${artifact.title}" escapes the staging directory`)}const stat=await fs2.lstat(absolutePath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink()){throw new Error(`policy artifact "${artifact.title}" is missing or not a regular file`)}const rawRole=artifact.metadata?.["omniRole"];const role=typeof rawRole==="string"&&rawRole?rawRole:void 0;const rawDisclosure=artifact.metadata?.["omniDisclosure"];const disclosure=typeof rawDisclosure==="string"&&rawDisclosure?rawDisclosure:void 0;if(artifact.kind==="file"){const spec2=descriptor.outputs.find(o=>o.kind==="file"&&(o.role===void 0||o.role===role)&&artifact.mimeType!==void 0&&o.mimeTypes?.includes(artifact.mimeType));if(!spec2){throw new Error(`policy artifact "${artifact.title}" (file, role ${role??"none"}, ${artifact.mimeType??"no mimeType"}) matches no declared file output`)}if(stat.size>MAX_FILE_ARTIFACT_BYTES){throw new Error(`policy artifact "${artifact.title}" exceeds the file-artifact size budget (${stat.size} > ${MAX_FILE_ARTIFACT_BYTES} bytes)`)}const bytes=await fs2.readFile(absolutePath);let text;try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new Error(`policy artifact "${artifact.title}" is not valid UTF-8 text`)}if(spec2.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"file",absolutePath,mimeType:artifact.mimeType,text,sizeBytes:bytes.byteLength,sha256:createHash2("sha256").update(bytes).digest("hex"),disclosure,lossy:spec2.lossy===true,role}}const recognized=await recognizeMediaFile(absolutePath,{signal});const spec=descriptor.outputs.find(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!spec){throw new Error(`policy artifact "${artifact.title}" has undeclared media type ${recognized.detectedMimeType}`)}if(artifact.kind!==recognized.modality){throw new Error(`policy artifact "${artifact.title}" declares kind ${String(artifact.kind)} but contains ${recognized.modality} content`)}if(spec.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"media",absolutePath,recognized,sha256:await hashFileSha256(absolutePath,signal),disclosure,lossy:spec.lossy===true,role}}__name(validateArtifact,"validateArtifact");function assertRequiredOutputsPresent(descriptor,validated,toolName){for(const spec of descriptor.outputs){if(!spec.required)continue;let produced;if(spec.kind==="media"){produced=validated.some(a=>a.kind==="media"&&spec.mimeTypes?.includes(a.recognized.detectedMimeType))}else if(spec.kind==="file"){produced=validated.some(a=>a.kind==="file"&&(spec.role===void 0||a.role===spec.role)&&spec.mimeTypes?.includes(a.mimeType))}else{continue}if(!produced){throw new Error(`tool ${toolName} did not produce its required ${spec.kind} ${spec.mimeTypes?.join("/")??spec.role??""} output`)}}}__name(assertRequiredOutputsPresent,"assertRequiredOutputsPresent");export{estimateRawResourceTokens,computePolicyFingerprint,OmniDegradationCache,DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES,OmniTransportGuardError,effectiveMaxUploadFileBytes,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveOmniStorageMaxTotalBytes,runOmniGcOnce,OmniPolicyExecutionError,runFixedPolicies,validateArtifact,assertRequiredOutputsPresent};
5
+ ${toolVersion}`).digest("hex")}__name(computePolicyFingerprint,"computePolicyFingerprint");var OmniDegradationCache=class{static{__name(this,"OmniDegradationCache")}file;constructor(omniRootDir){this.file=new OmniJsonCacheFile(path.join(omniRootDir,"policy-cache.json"),"omni:policy-cache")}key(originalSha256,policyFingerprint){return`${originalSha256}|${policyFingerprint}`}async get(originalSha256,policyFingerprint){return this.file.access(null,entries=>{const key=this.key(originalSha256,policyFingerprint);const entry=entries[key];if(!entry)return{result:null};if(!/^[0-9a-f]{64}$/.test(entry.degradedSha256)||typeof entry.extension!=="string"||!OBJECT_EXTENSION_RE.test(entry.extension)||typeof entry.disclosure!=="string"||entry.disclosure.length===0||entry.disclosure.length>MAX_CACHED_DISCLOSURE_LENGTH||typeof entry.mimeType!=="string"||entry.mimeType.length===0||entry.role!==void 0&&(typeof entry.role!=="string"||entry.role.length===0)){delete entries[key];return{result:null,changed:true}}return{result:entry}})}async put(originalSha256,policyFingerprint,entry){return this.file.access(void 0,entries=>{entries[this.key(originalSha256,policyFingerprint)]={...entry,createdAt:new Date().toISOString()};return{result:void 0,changed:true}})}async removeByOriginalSha256(originalSha256){return this.file.access(void 0,entries=>{const prefix=`${originalSha256}|`;let changed=false;for(const k of Object.keys(entries)){if(k.startsWith(prefix)){delete entries[k];changed=true}}return{result:void 0,changed}})}async removeByDegradedSha256(degradedSha256){return this.file.access(void 0,entries=>{let changed=false;for(const[k,v]of Object.entries(entries)){if(v.degradedSha256===degradedSha256){delete entries[k];changed=true}}return{result:void 0,changed}})}};init_esbuild_shims();var DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES=1024*1024*1024;var OmniTransportGuardError=class extends Error{static{__name(this,"OmniTransportGuardError")}sessionResourceId;constructor(message,options){super(message,options);this.name="OmniTransportGuardError"}};function effectiveMaxUploadFileBytes(config){const configured=config.getOmniMaxUploadFileBytes?.();return configured!==void 0&&configured>0?configured:DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES}__name(effectiveMaxUploadFileBytes,"effectiveMaxUploadFileBytes");function assertWithinByteLimit(config,sizeBytes,displayName){const maxBytes=effectiveMaxUploadFileBytes(config);if(sizeBytes>maxBytes){throw new OmniTransportGuardError(`${displayName} exceeds the omni upload limit: ${sizeBytes} bytes > ${maxBytes} bytes (omni.processing.transportGuard.maxUploadFileBytes). Reduce the file size before retrying.`)}}__name(assertWithinByteLimit,"assertWithinByteLimit");function assertWithinDurationLimit(config,media,displayName){const maxSeconds=config.getOmniMaxDurationSeconds?.();if(maxSeconds===void 0||maxSeconds<=0)return;const durationMs=media.metadata.durationMs;if(durationMs===void 0||!Number.isFinite(durationMs))return;const seconds=durationMs/1e3;if(seconds>maxSeconds){throw new OmniTransportGuardError(`${displayName} exceeds the omni duration limit: ${Math.round(seconds)}s > ${maxSeconds}s (omni.processing.transportGuard.maxDurationSeconds). Clip a shorter span \u2014 downscaling cannot bring a long file within a duration limit.`)}}__name(assertWithinDurationLimit,"assertWithinDurationLimit");function assertWithinTokenLimit(config,media,displayName){const estimate=estimateRawResourceTokens(media);const maxTokens=config.getOmniMaxEstimatedTokens?.();if(maxTokens===void 0||maxTokens<=0)return estimate;if(estimate.status!=="ok")return estimate;if(estimate.estimatedTokenCount>maxTokens){throw new OmniTransportGuardError(`${displayName} exceeds the omni estimated-token limit: ~${estimate.estimatedTokenCount} tokens (${estimate.method}) > ${maxTokens} (omni.processing.transportGuard.maxEstimatedTokens). Reduce duration/resolution or raise the limit.`)}return estimate}__name(assertWithinTokenLimit,"assertWithinTokenLimit");init_esbuild_shims();import fs from"node:fs/promises";import path2 from"node:path";var debugLogger=createDebugLogger("omni:gc");var OBJECT_NAME_RE=/^([0-9a-f]{64})\.[A-Za-z0-9][A-Za-z0-9.]*$/;var SKIPPED={ran:false,deletedObjects:0,deletedBytes:0,remainingBytes:0,derivationsSuspended:false};var gcOnce=new Map;var suspendedRoots=new Set;function effectiveOmniStorageMaxTotalBytes(config){const configured=config.getOmniStorageMaxTotalBytes();const floor=10*effectiveMaxUploadFileBytes(config);if(configured<floor){debugLogger.warn(`omni.storage.maxTotalBytes (${configured}) is below 10\xD7 the transport guard's single-media limit; using ${floor} bytes instead (the budget must hold at least ten normal uploads).`);return floor}return configured}__name(effectiveOmniStorageMaxTotalBytes,"effectiveOmniStorageMaxTotalBytes");function isOmniDerivationSuspended(omniRootDir){return suspendedRoots.has(path2.resolve(omniRootDir))}__name(isOmniDerivationSuspended,"isOmniDerivationSuspended");async function settleOmniGc(omniRootDir){const existing=gcOnce.get(path2.resolve(omniRootDir));if(existing)await existing}__name(settleOmniGc,"settleOmniGc");async function isRealDirectory(p){try{return(await fs.lstat(p)).isDirectory()}catch{return false}}__name(isRealDirectory,"isRealDirectory");async function listObjects(objectsDir){const out=[];if(!await isRealDirectory(objectsDir))return out;let shards;try{shards=await fs.readdir(objectsDir)}catch{return out}for(const shard of shards){const shardDir=path2.join(objectsDir,shard);if(!await isRealDirectory(shardDir))continue;let names;try{names=await fs.readdir(shardDir)}catch{continue}for(const name of names){const match=OBJECT_NAME_RE.exec(name);if(!match)continue;const filePath=path2.join(shardDir,name);try{const st=await fs.lstat(filePath);if(!st.isFile())continue;out.push({sha256:match[1],filePath,mtimeMs:st.mtimeMs,sizeBytes:st.size})}catch{}}}return out}__name(listObjects,"listObjects");async function deleteObject(object,options){try{await fs.rm(object.filePath,{force:true})}catch(err){debugLogger.debug(`gc: failed to delete ${object.sha256}: ${err instanceof Error?err.message:err}`);return false}try{await options.uploadCache?.removeBySha256(object.sha256)}catch{}try{await options.degradationCache?.removeByOriginalSha256(object.sha256);await options.degradationCache?.removeByDegradedSha256(object.sha256)}catch{}debugLogger.debug(`gc: deleted unreferenced object ${object.sha256} (${object.sizeBytes} bytes)`);return true}__name(deleteObject,"deleteObject");function runOmniGcOnce(options){const rootKey=path2.resolve(options.store.getOmniRootDir());const existing=gcOnce.get(rootKey);if(existing)return existing;const run=sweep(options,rootKey).catch(err=>{debugLogger.debug(`gc: run failed, skipped: ${err instanceof Error?err.message:err}`);return SKIPPED});gcOnce.set(rootKey,run);return run}__name(runOmniGcOnce,"runOmniGcOnce");async function recentlyRecoveredFromCorruption(omniRootDir,retentionDays,nowMs){const prefix=`${MEDIA_MEMORY_FILE_NAME}.corrupt-`;let names;try{names=await fs.readdir(omniRootDir)}catch{return false}const cutoff=nowMs-retentionDays*24*36e5;for(const name of names){if(!name.startsWith(prefix))continue;const stamp=Number(name.slice(prefix.length));if(Number.isFinite(stamp)&&stamp>=cutoff)return true;try{const st=await fs.lstat(path2.join(omniRootDir,name));if(st.mtimeMs>=cutoff)return true}catch{return true}}return false}__name(recentlyRecoveredFromCorruption,"recentlyRecoveredFromCorruption");async function sweep(options,rootKey){const nowMsForGuard=options.nowMs??Date.now();const refs=await options.memoryService.collectManagedRefs();if(refs===null){debugLogger.debug("gc: memory snapshot unreadable, skipping run");return SKIPPED}if(await recentlyRecoveredFromCorruption(options.store.getOmniRootDir(),options.retentionDays,nowMsForGuard)){debugLogger.debug("gc: memory ledger recently recovered from corruption, skipping run");return SKIPPED}const objectsDir=options.store.getObjectsDir();for(const fileRef of options.registry?.activeFileRefs()??[]){const name=path2.basename(fileRef);const match=OBJECT_NAME_RE.exec(name);if(match&&fileRef.startsWith(objectsDir))refs.add(match[1])}const nowMs=options.nowMs??Date.now();const cutoffMs=nowMs-options.retentionDays*24*36e5;const objects=await listObjects(objectsDir);let deletedObjects=0;let deletedBytes=0;const survivors=[];const touchedSinceListing=__name(async(object,freshCutoffMs)=>{try{return(await fs.lstat(object.filePath)).mtimeMs>=freshCutoffMs}catch{return true}},"touchedSinceListing");for(const object of objects){if(refs.has(object.sha256)||object.mtimeMs>=cutoffMs){survivors.push(object);continue}if(await touchedSinceListing(object,cutoffMs)){survivors.push(object);continue}if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes}else{survivors.push(object)}}let remainingBytes=survivors.reduce((sum,o)=>sum+o.sizeBytes,0);if(remainingBytes>options.maxTotalBytes){const freshRefs=await options.memoryService.collectManagedRefs();if(freshRefs===null){debugLogger.debug("gc: ledger unreadable at budget pass, skipping budget deletions")}else{const unreferenced=survivors.filter(o=>!refs.has(o.sha256)&&!freshRefs.has(o.sha256)).sort((a,b)=>a.mtimeMs-b.mtimeMs);for(const object of unreferenced){if(remainingBytes<=options.maxTotalBytes)break;if(await touchedSinceListing(object,nowMs))continue;if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes;remainingBytes-=object.sizeBytes}}}}const derivationsSuspended=remainingBytes>options.maxTotalBytes;if(derivationsSuspended){suspendedRoots.add(rootKey);debugLogger.warn(`omni object store over budget with only referenced objects left (${remainingBytes} > ${options.maxTotalBytes} bytes); new policy derivations are suspended for this session. Raise omni.storage.maxTotalBytes or delete memory records you no longer need \u2014 either change takes effect at the next session start (the GC runs once per process).`)}else{suspendedRoots.delete(rootKey)}if(deletedObjects>0){debugLogger.debug(`gc: removed ${deletedObjects} object(s) / ${deletedBytes} bytes; ${remainingBytes} bytes remain`)}return{ran:true,deletedObjects,deletedBytes,remainingBytes,derivationsSuspended}}__name(sweep,"sweep");init_esbuild_shims();import{createHash as createHash2,randomBytes}from"node:crypto";import fs2 from"node:fs/promises";import path3 from"node:path";var debugLogger2=createDebugLogger("omni:policy");var MAX_FILE_ARTIFACT_BYTES=256*1024;var OmniPolicyExecutionError=class extends Error{constructor(message,policyId,options){super(message,options);this.policyId=policyId;this.name="OmniPolicyExecutionError"}static{__name(this,"OmniPolicyExecutionError")}};function resolveArtifactSelector(artifacts,kind,role){if(role!==void 0){const byRole=artifacts[`role:${role}`];if(byRole)return byRole}const byKind=artifacts[`kind:${kind}`];if(byKind)return byKind;return artifacts["*"]??"retain"}__name(resolveArtifactSelector,"resolveArtifactSelector");function resourceConditionContext(recognized,shared){const resource={};const set=__name((field,value)=>{if(typeof value==="number"&&!Number.isNaN(value)){resource[field]=value}},"set");const m=recognized.metadata;set("sizeBytes",recognized.sizeBytes);set("durationMs",m.durationMs);set("width",m.width);set("height",m.height);set("maxWidth",m.width);set("maxHeight",m.height);set("frameRate",m.frameRate);set("frameCount",m.frameCount);set("bitRate",m.bitRate);set("sampleRateHz",m.sampleRateHz);set("channels",m.channels);const estimate=estimateRawResourceTokens(recognized);if(estimate.status==="ok"){set("estimatedTokenCount",estimate.estimatedTokenCount)}return{resource,...shared}}__name(resourceConditionContext,"resourceConditionContext");var MEMORY_ROLE_FIELDS={transcript:"hasTranscript",ocr:"hasOcr",caption:"hasCaption",summary:"hasSummary",keyframe:"hasKeyframes",clip:"hasClip"};async function memoryConditionNamespace(memory,binding){if(!memory||!binding)return void 0;const roles=await memory.service.collectVersionOutputRoles(binding);if(!roles)return void 0;const namespace={};for(const field of Object.values(MEMORY_ROLE_FIELDS)){namespace[field]=0}for(const role of roles){const field=MEMORY_ROLE_FIELDS[role];if(field)namespace[field]=1}return namespace}__name(memoryConditionNamespace,"memoryConditionNamespace");function requestConditionNamespace(items){let total=0;for(const item of items){if(!item.deliver)continue;const estimate=estimateRawResourceTokens(item.recognized);if(estimate.status!=="ok")return void 0;total+=estimate.estimatedTokenCount}return{totalEstimatedMediaTokens:total}}__name(requestConditionNamespace,"requestConditionNamespace");function sortPolicies(policies){return[...policies].sort((a,b)=>b.priority-a.priority||a.id.localeCompare(b.id))}__name(sortPolicies,"sortPolicies");var resourceGates=new Map;async function acquireResourceSlot(rootDir,limit){const effectiveLimit=Math.max(1,Math.floor(limit));let gate=resourceGates.get(rootDir);if(!gate){gate={active:0,waiters:[]};resourceGates.set(rootDir,gate)}const heldGate=gate;if(heldGate.active>=effectiveLimit){await new Promise(resolve=>heldGate.waiters.push(resolve))}else{heldGate.active++}let released=false;return()=>{if(released)return;released=true;const next=heldGate.waiters.shift();if(next){next();return}heldGate.active--;if(heldGate.active===0&&heldGate.waiters.length===0){resourceGates.delete(rootDir)}}}__name(acquireResourceSlot,"acquireResourceSlot");async function runFixedPolicies(config,source,options){const policies=sortPolicies(options.policies);const limits=options.limits??DEFAULT_OMNI_PROCESSING_LIMITS;const releaseSlot=await acquireResourceSlot(options.store.getOmniRootDir(),limits.maxConcurrentResources);try{return await runFixedPoliciesUnbounded(config,source,options,{policies,limits})}finally{releaseSlot()}}__name(runFixedPolicies,"runFixedPolicies");async function runFixedPoliciesUnbounded(config,source,options,normalized){const{policies,limits}=normalized;const cache=options.degradationCache??new OmniDegradationCache(options.store.getOmniRootDir());const records=[];const fileDeliveries=[];const items=[{filePath:source.filePath,recognized:source.recognized,label:source.displayName,origin:source.origin,sha256:source.sha256,memoryBinding:options.memory?.sourceBinding,lineageRuns:new Map,depth:0,deliver:true,process:true}];let runsUsed=0;let artifactsProduced=0;let derivedBytesProduced=0;let budgetExhausted=false;const stopOnBudget=__name((policy,item,reason)=>{budgetExhausted=true;records.push({policyId:policy.id,toolName:policy.toolName,outcome:"budget_exhausted",resource:item.label,error:reason});debugLogger2.debug(`per-root policy budget exhausted on ${item.label}: ${reason}; no further derivation for this root (committed deliveries stand)`)},"stopOnBudget");for(let i=0;i<items.length&&!budgetExhausted;i++){const item=items[i];if(!item.process)continue;if(item.recognized.modality==="image"&&(item.recognized.metadata.frameCount??1)>1){debugLogger2.debug(`animated image ${item.label} (${item.recognized.metadata.frameCount} frames) excluded from policy matching (D9)`);continue}const needsMemoryNamespace=policies.some(policy=>policy.when&&conditionUsesNamespace(policy.when,"memory"));const sharedConditionContext={request:options.conditionContext?.request??requestConditionNamespace(items),session:options.conditionContext?.session,memory:needsMemoryNamespace?await memoryConditionNamespace(options.memory,item.memoryBinding):void 0};for(const policy of policies){if(!policy.mediaTypes.includes(item.recognized.modality))continue;if(!policy.origins.includes(item.origin))continue;const runs=item.lineageRuns.get(policy.id)??0;if(runs>=policy.maxRunsPerLineage)continue;if(policy.when){const evaluation=evaluateFixedPolicyCondition(policy.when,resourceConditionContext(item.recognized,sharedConditionContext));if(evaluation.outcome==="no_match")continue;if(evaluation.outcome==="unavailable"&&policy.onConditionUnavailable==="skip"){records.push({policyId:policy.id,toolName:policy.toolName,outcome:"condition_unavailable",resource:item.label,missingFields:evaluation.missingFields});continue}}if(runsUsed>=limits.maxPolicyRunsPerRoot){stopOnBudget(policy,item,`maxPolicyRunsPerRoot (${limits.maxPolicyRunsPerRoot}) reached`);break}runsUsed++;item.lineageRuns.set(policy.id,runs+1);try{const execution=await executePolicy(config,item,policy,options.store,cache,options.signal,options.memory&&item.memoryBinding?{service:options.memory.service,source:item.memoryBinding}:void 0);records.push({policyId:policy.id,toolName:policy.toolName,outcome:execution.outcome,resource:item.label});if(execution.outcome==="no_op")continue;if(policy.output.source==="omit")item.deliver=false;const childDepth=item.depth+1;const depthAllowsReprocess=childDepth<limits.maxLineageDepth;if(policy.output.reprocessMedia&&!depthAllowsReprocess){debugLogger2.debug(`maxLineageDepth (${limits.maxLineageDepth}) reached under ${item.label}; derivatives deliver but do not re-enter policy matching`)}for(const derived of execution.derived){artifactsProduced++;derivedBytesProduced+=derived.recognized.sizeBytes;items.push({...derived,label:`${item.label} \u2192 ${policy.id}`,origin:"policy",lineageRuns:new Map(item.lineageRuns),depth:childDepth,deliver:resolveArtifactSelector(policy.output.artifacts,derived.recognized.modality,derived.role)==="include",process:policy.output.reprocessMedia&&depthAllowsReprocess})}for(const file of execution.derivedFiles){artifactsProduced++;derivedBytesProduced+=file.sizeBytes;if(resolveArtifactSelector(policy.output.artifacts,"file",file.role)==="include"){fileDeliveries.push(file)}}if(artifactsProduced>limits.maxArtifactsPerRoot){stopOnBudget(policy,item,`maxArtifactsPerRoot (${limits.maxArtifactsPerRoot}) exceeded`);break}if(derivedBytesProduced>limits.maxDerivedBytesPerRoot){stopOnBudget(policy,item,`maxDerivedBytesPerRoot (${limits.maxDerivedBytesPerRoot}) exceeded`);break}}catch(err){if(options.signal?.aborted)throw err;const message=err instanceof Error?err.message:String(err);records.push({policyId:policy.id,toolName:policy.toolName,outcome:"failed",resource:item.label,error:message});debugLogger2.debug(`fixed policy ${policy.id} (${policy.toolName}) failed on ${item.label}: ${message}`);if(policy.onFailure==="abort"||policy.stage==="transport_guard"){throw new OmniPolicyExecutionError(`Fixed policy ${policy.id} failed: ${message}`,policy.id,{cause:err})}}}}return{deliveries:items.filter(item=>item.deliver).map(item=>({filePath:item.filePath,recognized:item.recognized,sha256:item.sha256,disclosure:item.disclosure,degraded:item.degraded,memoryBinding:item.memoryBinding})),fileDeliveries,records}}__name(runFixedPoliciesUnbounded,"runFixedPoliciesUnbounded");async function executePolicy(config,item,policy,store,cache,signal,memory){const tool=config.getToolRegistry().getTool(policy.toolName);const descriptor=tool?.mediaPolicyDescriptor;if(!descriptor){throw new Error(`tool ${policy.toolName} is not a registered media-policy tool`)}item.sha256??=await hashFileSha256(item.filePath,signal);const settingsDefaults=resolvePolicyToolSettings(config,policy.toolName);const effectiveArguments={...settingsDefaults,...policy.arguments};const fingerprint=computePolicyFingerprint(policy.toolName,effectiveArguments,descriptor.version);const startedAt=new Date().toISOString();if(memory){const reusable=await memory.service.findReusableOutputs(item.sha256,fingerprint);const rebuilt=reusable?await rebuildReusedOutputs(reusable,descriptor,store,signal):void 0;if(rebuilt){debugLogger2.debug(`memory reuse hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026 outputs=${rebuilt.outputs.length} (tool not executed)`);const commit=await memory.service.commitPolicySucceeded({invocationId:"memory-reuse",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:rebuilt.outputs});return{outcome:"succeeded",derived:rebuilt.derived.map(d=>({...d,memoryBinding:commit?.mediaBindings.get(d.sha256)})),derivedFiles:rebuilt.derivedFiles}}}const hit=await cache.get(item.sha256,fingerprint);if(hit){try{const objectPath=store.objectPathFor(hit.degradedSha256,hit.extension);const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(stat?.isFile()&&!stat.isSymbolicLink()){const actualSha256=await hashFileSha256(objectPath,signal);if(actualSha256===hit.degradedSha256){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(declared){debugLogger2.debug(`degradation cache hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026`);const commit=memory?await memory.service.commitPolicySucceeded({invocationId:"cache-hit",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:[{kind:"media",objectPath,sha256:hit.degradedSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:hit.role,disclosure:hit.disclosure}]}):void 0;return{outcome:"cache_hit",derived:[{filePath:objectPath,recognized,sha256:hit.degradedSha256,disclosure:hit.disclosure,degraded:true,role:hit.role,memoryBinding:commit?.mediaBindings.get(hit.degradedSha256)}],derivedFiles:[]}}debugLogger2.debug(`degradation cache hit for policy=${policy.id} recognized as undeclared media type ${recognized.detectedMimeType}; dropping the entry and re-transcoding`)}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`degradation cache hit could not be verified for policy=${policy.id}: ${err instanceof Error?err.message:String(err)}; dropping the entry and re-transcoding`)}await cache.removeByDegradedSha256(hit.degradedSha256)}await settleOmniGc(store.getOmniRootDir());if(isOmniDerivationSuspended(store.getOmniRootDir())){throw new Error(`omni object store is over its byte budget with only memory-referenced objects left; new policy derivations are suspended. Raise omni.storage.maxTotalBytes or delete memory records you no longer need, then start a new session \u2014 the budget is re-evaluated once per process.`)}const invocationId=randomBytes(8).toString("hex");const stagingDir=await store.createStagingDir(invocationId);let failure;try{const request={callId:invocationId,name:policy.toolName,args:{...effectiveArguments,inputPath:item.filePath,outputDir:stagingDir},isClientInitiated:true,prompt_id:`omni-fixed-policy-${invocationId}`,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage}};const{executeToolCall}=await import("./nonInteractiveToolExecutor-EMLI363Q.js");const response=await executeToolCall(config,request,signal??new AbortController().signal,{recordToolResult:false});if(response.error){throw new Error(response.error.message,{cause:response.error})}const batch=response.policyArtifacts;if(!batch||batch.artifacts.length===0){throw new Error(`tool ${policy.toolName} succeeded but produced no policy artifacts`)}const validated=await Promise.all(batch.artifacts.map(artifact=>validateArtifact(artifact,descriptor,stagingDir,signal)));assertRequiredOutputsPresent(descriptor,validated,policy.toolName);if(validated.every(a=>a.sha256===item.sha256)){return{outcome:"no_op",derived:[],derivedFiles:[]}}const promoted=await Promise.all(validated.map(async artifact=>{const mimeType=artifact.kind==="media"?artifact.recognized.detectedMimeType:artifact.mimeType;const put=await store.putFile(artifact.absolutePath,artifact.sha256,extensionForMime(mimeType),signal);return{artifact,objectPath:put.objectPath}}));const derived=[];const derivedFiles=[];for(const{artifact,objectPath}of promoted){if(artifact.kind==="media"){derived.push({filePath:objectPath,recognized:artifact.recognized,sha256:artifact.sha256,disclosure:artifact.disclosure,degraded:artifact.lossy,role:artifact.role})}else{derivedFiles.push({filePath:objectPath,role:artifact.role,mimeType:artifact.mimeType,text:artifact.text,sha256:artifact.sha256,sizeBytes:artifact.sizeBytes,disclosure:artifact.disclosure})}}if(memory){const outputs=promoted.map(({artifact,objectPath})=>artifact.kind==="media"?{kind:"media",objectPath,sha256:artifact.sha256,mediaType:artifact.recognized.modality,metadata:artifact.recognized.metadata,sizeBytes:artifact.recognized.sizeBytes,mimeType:artifact.recognized.detectedMimeType,role:artifact.role,disclosure:artifact.disclosure}:{kind:"text",objectPath,sha256:artifact.sha256,mimeType:artifact.mimeType,text:artifact.text,sizeBytes:artifact.sizeBytes,role:artifact.role,disclosure:artifact.disclosure});const commit=await memory.service.commitPolicySucceeded({invocationId,source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs});if(commit){for(const entry of derived){entry.memoryBinding=commit.mediaBindings.get(entry.sha256)}}}if(validated.length===1&&validated[0].kind==="media"&&validated[0].disclosure){await cache.put(item.sha256,fingerprint,{degradedSha256:validated[0].sha256,extension:extensionForMime(validated[0].recognized.detectedMimeType),disclosure:validated[0].disclosure,mimeType:validated[0].recognized.detectedMimeType,...validated[0].role!==void 0?{role:validated[0].role}:{}})}return{outcome:"succeeded",derived,derivedFiles}}catch(err){failure=err;throw err}finally{if(failure===void 0||signal?.aborted){await store.removeStagingDir(invocationId).catch(()=>{})}else{try{await store.quarantineInvocation(invocationId,{policyId:policy.id,toolName:policy.toolName,reason:failure instanceof Error?failure.message:String(failure)})}catch{await store.removeStagingDir(invocationId).catch(()=>{})}}}}__name(executePolicy,"executePolicy");async function rebuildReusedOutputs(reusable,descriptor,store,signal){const outputs=[];const derived=[];const derivedFiles=[];try{for(const record of reusable.outputs){const objectPath=record.objectPath??store.objectPathFor(record.sha256,extensionForMime(record.mimeType));const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink())return void 0;if(await hashFileSha256(objectPath,signal)!==record.sha256){return void 0}if(record.kind==="media"){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!declared)return void 0;outputs.push({kind:"media",objectPath,sha256:record.sha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:record.role,disclosure:record.disclosure});derived.push({filePath:objectPath,recognized,sha256:record.sha256,disclosure:record.disclosure,degraded:record.disclosure!==void 0,role:record.role})}else{const text=await fs2.readFile(objectPath,"utf8");outputs.push({kind:"text",objectPath,sha256:record.sha256,mimeType:record.mimeType,text,sizeBytes:record.sizeBytes,role:record.role,disclosure:record.disclosure});derivedFiles.push({filePath:objectPath,role:record.role,mimeType:record.mimeType,text,sha256:record.sha256,sizeBytes:record.sizeBytes,disclosure:record.disclosure})}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`memory reuse could not be verified, re-deriving: ${err instanceof Error?err.message:String(err)}`);return void 0}return{outputs,derived,derivedFiles}}__name(rebuildReusedOutputs,"rebuildReusedOutputs");async function validateArtifact(artifact,descriptor,stagingDir,signal){if(artifact.storage!=="workspace"||!artifact.workspacePath){throw new Error(`policy artifact "${artifact.title}" is not a workspace file`)}const absolutePath=path3.resolve(stagingDir,artifact.workspacePath);if(!absolutePath.startsWith(stagingDir+path3.sep)){throw new Error(`policy artifact "${artifact.title}" escapes the staging directory`)}const stat=await fs2.lstat(absolutePath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink()){throw new Error(`policy artifact "${artifact.title}" is missing or not a regular file`)}const rawRole=artifact.metadata?.["omniRole"];const role=typeof rawRole==="string"&&rawRole?rawRole:void 0;const rawDisclosure=artifact.metadata?.["omniDisclosure"];const disclosure=typeof rawDisclosure==="string"&&rawDisclosure?rawDisclosure:void 0;if(artifact.kind==="file"){const spec2=descriptor.outputs.find(o=>o.kind==="file"&&(o.role===void 0||o.role===role)&&artifact.mimeType!==void 0&&o.mimeTypes?.includes(artifact.mimeType));if(!spec2){throw new Error(`policy artifact "${artifact.title}" (file, role ${role??"none"}, ${artifact.mimeType??"no mimeType"}) matches no declared file output`)}if(stat.size>MAX_FILE_ARTIFACT_BYTES){throw new Error(`policy artifact "${artifact.title}" exceeds the file-artifact size budget (${stat.size} > ${MAX_FILE_ARTIFACT_BYTES} bytes)`)}const bytes=await fs2.readFile(absolutePath);let text;try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new Error(`policy artifact "${artifact.title}" is not valid UTF-8 text`)}if(spec2.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"file",absolutePath,mimeType:artifact.mimeType,text,sizeBytes:bytes.byteLength,sha256:createHash2("sha256").update(bytes).digest("hex"),disclosure,lossy:spec2.lossy===true,role}}const recognized=await recognizeMediaFile(absolutePath,{signal});const spec=descriptor.outputs.find(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!spec){throw new Error(`policy artifact "${artifact.title}" has undeclared media type ${recognized.detectedMimeType}`)}if(artifact.kind!==recognized.modality){throw new Error(`policy artifact "${artifact.title}" declares kind ${String(artifact.kind)} but contains ${recognized.modality} content`)}if(spec.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"media",absolutePath,recognized,sha256:await hashFileSha256(absolutePath,signal),disclosure,lossy:spec.lossy===true,role}}__name(validateArtifact,"validateArtifact");function assertRequiredOutputsPresent(descriptor,validated,toolName){for(const spec of descriptor.outputs){if(!spec.required)continue;let produced;if(spec.kind==="media"){produced=validated.some(a=>a.kind==="media"&&spec.mimeTypes?.includes(a.recognized.detectedMimeType))}else if(spec.kind==="file"){produced=validated.some(a=>a.kind==="file"&&(spec.role===void 0||a.role===spec.role)&&spec.mimeTypes?.includes(a.mimeType))}else{continue}if(!produced){throw new Error(`tool ${toolName} did not produce its required ${spec.kind} ${spec.mimeTypes?.join("/")??spec.role??""} output`)}}}__name(assertRequiredOutputsPresent,"assertRequiredOutputsPresent");export{estimateRawResourceTokens,computePolicyFingerprint,OmniDegradationCache,DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES,OmniTransportGuardError,effectiveMaxUploadFileBytes,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveOmniStorageMaxTotalBytes,runOmniGcOnce,OmniPolicyExecutionError,runFixedPolicies,validateArtifact,assertRequiredOutputsPresent};
6
6
  /**
7
7
  * @license
8
8
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{JsonOutputAdapter}from"./chunk-JHC22BZH.js";import{runAgentLoop}from"./chunk-6JAXAFX7.js";import{normalizePartList}from"./chunk-HIO3M52C.js";import{formatLoopDetectedMessage,settleChatRecording,subscribeToHeadlessChatRecordingFailures}from"./chunk-BGELKSQ4.js";import{StreamJsonOutputAdapter}from"./chunk-QTKPC24L.js";import{handleAtCommand}from"./chunk-RULGA7WE.js";import{buildInitialSystemReminders,buildSystemMessage,computeUsageFromMetrics,createAgentToolProgressHandler,createToolProgressHandler,extractPartsFromUserMessage,handleSlashCommand,insertAfterFunctionResponses,isSlashCommand}from"./chunk-WK666FGZ.js";import{ModSession}from"./chunk-QHYSRPQR.js";import{formatDuration}from"./chunk-WCI33URB.js";import{cleanupReviewWorktreeLeases}from"./chunk-6WV5RKYB.js";import{RunBudgetEnforcer}from"./chunk-4A663FE6.js";import{sanitizeTerminalText}from"./chunk-64CA3W6G.js";import{isInlineModelOverrideAllowed}from"./chunk-GT4TCQ3R.js";import{AlreadyReportedError,handleBudgetExceededError,handleCancellationError,handleError,handleMaxTurnsExceededError,handleToolError}from"./chunk-HJLRKM3W.js";import{buildGoalContinuationParts,buildSessionRecoveryPlanFromApiHistory,detectAutonomousSentinel,detectLoopSentinel}from"./chunk-CK3OKTTL.js";import{restoreWorktreeContext}from"./chunk-OMDTFGTX.js";import{executeToolCall}from"./chunk-BY46PCWY.js";import{GoalPersistenceUnavailableError,PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE,createDuplicateProviderToolCallResponse,finalizeToolResponses,findPlanModeEntryBatchBoundaryIndex,findRepeatedDuplicateProviderToolCall,getCachedToolCallFingerprint,getLastApiPromptCancellation,goalToolResultProvenance,isReplayOfHandledToolCall,isToolCallConcurrencySafe,markDuplicateProviderToolCallResponseSent,parseAndFormatApiError,partitionByConcurrencySafety,recordHandledToolCall}from"./chunk-T3CQ72HC.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{GOAL_PAUSE_REASON_HEADLESS_RUN_ENDED,GOAL_PAUSE_REASON_USER_INTERRUPT,addAgentOutputMessageAttributes,goalPauseReasonForHeadlessFailure,goalPauseReasonForRunBudget}from"./chunk-HW6AWS7W.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,hasImageParts,runVisionBridge,shouldRunVisionBridge,splitImageParts,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{clampInlineMediaPart}from"./chunk-Q6UAOTP3.js";import{endInteractionSpan,getActiveInteractionSpan,isTelemetrySdkInitialized,shutdownTelemetry}from"./chunk-3XVPZY7X.js";import{registerCleanup}from"./chunk-3ICJI5KW.js";import{isWrappedSystemReminderPart}from"./chunk-B3ZFUGTC.js";import{ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{FatalInputError,getErrorType}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("NON_INTERACTIVE_CLI");var TurnInterruptedError=class extends Error{static{__name(this,"TurnInterruptedError")}constructor(){super("Operation cancelled.");this.name="TurnInterruptedError"}};var ModTurnAbortedError=class extends TurnInterruptedError{static{__name(this,"ModTurnAbortedError")}constructor(){super();this.message="A Mod ended the turn."}};var restoredBackgroundAgentSessions=new WeakMap;var STRUCTURED_SHUTDOWN_HOLDBACK_MS=500;function isHeadlessLoopSentinel(prompt){return detectLoopSentinel(prompt)!==null||detectAutonomousSentinel(prompt)!==null}__name(isHeadlessLoopSentinel,"isHeadlessLoopSentinel");var SUPPRESSED_OUTPUT_SUCCESS="Skipped: this turn's structured_output contract took precedence as the terminal output.";var SUPPRESSED_OUTPUT_RETRY=`${SUPPRESSED_OUTPUT_SUCCESS} Re-issue this call in a separate turn if needed.`;function suppressedOutputBody(structuredCaptured){return structuredCaptured?SUPPRESSED_OUTPUT_SUCCESS:SUPPRESSED_OUTPUT_RETRY}__name(suppressedOutputBody,"suppressedOutputBody");function sameGoalPermit(left,right){return left?.goalId===right.goalId&&left.revision===right.revision&&left.turnId===right.turnId}__name(sameGoalPermit,"sameGoalPermit");function formatGoalState(snapshot,operation){const goal=snapshot.goal;if(!goal){return operation==="clear"?"Goal cleared.":"No Goal is set."}const status=goal.status==="usage_limited"?"usage limited":goal.status;const summary=`Goal ${status}: ${goal.objective}`;const usage=[];if(goal.turnCount>0){const turns=goal.turnBudget??goal.turnCount;usage.push(`${goal.turnCount}${goal.turnBudget===void 0?"":` of ${goal.turnBudget}`} ${turns===1?"turn":"turns"}`)}if(goal.activeTimeMs>0&&goal.activeTimeBudgetMs!==void 0){usage.push(`${formatDuration(goal.activeTimeMs,{hideTrailingZeros:true})} of ${formatDuration(goal.activeTimeBudgetMs,{hideTrailingZeros:true})} active`)}if(goal.tokensUsed>0){const used=goal.tokensUsed.toLocaleString("en-US");usage.push(goal.tokenBudget===void 0?`${used} tokens`:`${used} of ${goal.tokenBudget.toLocaleString("en-US")} tokens`)}const lines=[summary];if(usage.length>0)lines.push(`Usage: ${usage.join(" \xB7 ")}`);if(goal.status!=="active"&&goal.lastReason){lines.push(`Reason: ${sanitizeTerminalText(goal.lastReason)}`)}return lines.join("\n")}__name(formatGoalState,"formatGoalState");async function claimUserGoalTurn(runtime,turnKey,signal){const immediate=runtime.permitForTurn(turnKey)??runtime.beginTurn(turnKey);if(immediate||runtime.getSnapshot().goal?.status!=="active"){return immediate}return new Promise((resolve,reject)=>{let settled=false;let unsubscribe=__name(()=>{},"unsubscribe");const finish=__name((permit,error)=>{if(settled)return;settled=true;unsubscribe();signal.removeEventListener("abort",onAbort);if(error!==void 0)reject(error);else resolve(permit)},"finish");const inspect=__name(()=>{try{const permit=runtime.permitForTurn(turnKey);if(permit||runtime.getSnapshot().goal?.status!=="active"){finish(permit)}}catch(error){finish(void 0,error)}},"inspect");const onAbort=__name(()=>finish(void 0),"onAbort");unsubscribe=runtime.subscribe(inspect);signal.addEventListener("abort",onAbort,{once:true});if(signal.aborted)onAbort();else inspect()})}__name(claimUserGoalTurn,"claimUserGoalTurn");function skipHeadlessLoopSentinel(scheduler,job){if(!isHeadlessLoopSentinel(job.prompt)){return false}if(job.recurring&&!job.durable){debugLogger.debug("skipHeadlessLoopSentinel: cleaning up recurring session loop.md cron in headless mode",{jobId:job.id});void scheduler.delete(job.id).catch(()=>{})}return true}__name(skipHeadlessLoopSentinel,"skipHeadlessLoopSentinel");var PROVIDER_DUPLICATE_ID_LOOP_STOP={loopType:"global_tool_call_duplicate",loopReason:"provider_duplicate_id"};function emitLoopDetectedMessage(config,stop){const message=formatLoopDetectedMessage(stop);if(config.getOutputFormat()!=="text"){return message}process.stderr.write(`${message}
3
+ import{JsonOutputAdapter}from"./chunk-WAIPC47V.js";import{runAgentLoop}from"./chunk-WZU2ECUD.js";import{normalizePartList}from"./chunk-HIO3M52C.js";import{formatLoopDetectedMessage,settleChatRecording,subscribeToHeadlessChatRecordingFailures}from"./chunk-BGELKSQ4.js";import{StreamJsonOutputAdapter}from"./chunk-5FGBLIXB.js";import{handleAtCommand}from"./chunk-PS7MQL57.js";import{buildInitialSystemReminders,buildSystemMessage,computeUsageFromMetrics,createAgentToolProgressHandler,createToolProgressHandler,extractPartsFromUserMessage,handleSlashCommand,insertAfterFunctionResponses,isSlashCommand}from"./chunk-3QTR2HAE.js";import{ModSession}from"./chunk-3ANIQTDT.js";import{formatDuration}from"./chunk-FCGFBUHS.js";import{cleanupReviewWorktreeLeases}from"./chunk-Q65LVCDR.js";import{RunBudgetEnforcer}from"./chunk-OTYPLLMT.js";import{sanitizeTerminalText}from"./chunk-64CA3W6G.js";import{isInlineModelOverrideAllowed}from"./chunk-GT4TCQ3R.js";import{AlreadyReportedError,handleBudgetExceededError,handleCancellationError,handleError,handleMaxTurnsExceededError,handleToolError}from"./chunk-XAGIZY2Y.js";import{buildGoalContinuationParts,buildSessionRecoveryPlanFromApiHistory,detectAutonomousSentinel,detectLoopSentinel}from"./chunk-G2LTZU67.js";import{restoreWorktreeContext}from"./chunk-OMDTFGTX.js";import{executeToolCall}from"./chunk-4HSISRRA.js";import{GoalPersistenceUnavailableError,PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE,createDuplicateProviderToolCallResponse,finalizeToolResponses,findPlanModeEntryBatchBoundaryIndex,findRepeatedDuplicateProviderToolCall,getCachedToolCallFingerprint,getLastApiPromptCancellation,goalToolResultProvenance,isReplayOfHandledToolCall,isToolCallConcurrencySafe,markDuplicateProviderToolCallResponseSent,parseAndFormatApiError,partitionByConcurrencySafety,recordHandledToolCall}from"./chunk-7XQ5D34E.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{GOAL_PAUSE_REASON_HEADLESS_RUN_ENDED,GOAL_PAUSE_REASON_USER_INTERRUPT,addAgentOutputMessageAttributes,goalPauseReasonForHeadlessFailure,goalPauseReasonForRunBudget}from"./chunk-HW6AWS7W.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{promptIdContext}from"./chunk-MWGB5RCF.js";import{formatFullTurnVisionNotice,formatVisionBridgeNotice,getFullTurnVisionModelSelector,hasImageParts,runVisionBridge,shouldRunVisionBridge,splitImageParts,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{clampInlineMediaPart}from"./chunk-Q6UAOTP3.js";import{endInteractionSpan,getActiveInteractionSpan,isTelemetrySdkInitialized,shutdownTelemetry}from"./chunk-3XVPZY7X.js";import{registerCleanup}from"./chunk-EQOHDAYU.js";import{isWrappedSystemReminderPart}from"./chunk-B3ZFUGTC.js";import{ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{FatalInputError,getErrorType}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("NON_INTERACTIVE_CLI");var TurnInterruptedError=class extends Error{static{__name(this,"TurnInterruptedError")}constructor(){super("Operation cancelled.");this.name="TurnInterruptedError"}};var ModTurnAbortedError=class extends TurnInterruptedError{static{__name(this,"ModTurnAbortedError")}constructor(){super();this.message="A Mod ended the turn."}};var restoredBackgroundAgentSessions=new WeakMap;var STRUCTURED_SHUTDOWN_HOLDBACK_MS=500;function isHeadlessLoopSentinel(prompt){return detectLoopSentinel(prompt)!==null||detectAutonomousSentinel(prompt)!==null}__name(isHeadlessLoopSentinel,"isHeadlessLoopSentinel");var SUPPRESSED_OUTPUT_SUCCESS="Skipped: this turn's structured_output contract took precedence as the terminal output.";var SUPPRESSED_OUTPUT_RETRY=`${SUPPRESSED_OUTPUT_SUCCESS} Re-issue this call in a separate turn if needed.`;function suppressedOutputBody(structuredCaptured){return structuredCaptured?SUPPRESSED_OUTPUT_SUCCESS:SUPPRESSED_OUTPUT_RETRY}__name(suppressedOutputBody,"suppressedOutputBody");function sameGoalPermit(left,right){return left?.goalId===right.goalId&&left.revision===right.revision&&left.turnId===right.turnId}__name(sameGoalPermit,"sameGoalPermit");function formatGoalState(snapshot,operation){const goal=snapshot.goal;if(!goal){return operation==="clear"?"Goal cleared.":"No Goal is set."}const status=goal.status==="usage_limited"?"usage limited":goal.status;const summary=`Goal ${status}: ${goal.objective}`;const usage=[];if(goal.turnCount>0){const turns=goal.turnBudget??goal.turnCount;usage.push(`${goal.turnCount}${goal.turnBudget===void 0?"":` of ${goal.turnBudget}`} ${turns===1?"turn":"turns"}`)}if(goal.activeTimeMs>0&&goal.activeTimeBudgetMs!==void 0){usage.push(`${formatDuration(goal.activeTimeMs,{hideTrailingZeros:true})} of ${formatDuration(goal.activeTimeBudgetMs,{hideTrailingZeros:true})} active`)}if(goal.tokensUsed>0){const used=goal.tokensUsed.toLocaleString("en-US");usage.push(goal.tokenBudget===void 0?`${used} tokens`:`${used} of ${goal.tokenBudget.toLocaleString("en-US")} tokens`)}const lines=[summary];if(usage.length>0)lines.push(`Usage: ${usage.join(" \xB7 ")}`);if(goal.status!=="active"&&goal.lastReason){lines.push(`Reason: ${sanitizeTerminalText(goal.lastReason)}`)}return lines.join("\n")}__name(formatGoalState,"formatGoalState");async function claimUserGoalTurn(runtime,turnKey,signal){const immediate=runtime.permitForTurn(turnKey)??runtime.beginTurn(turnKey);if(immediate||runtime.getSnapshot().goal?.status!=="active"){return immediate}return new Promise((resolve,reject)=>{let settled=false;let unsubscribe=__name(()=>{},"unsubscribe");const finish=__name((permit,error)=>{if(settled)return;settled=true;unsubscribe();signal.removeEventListener("abort",onAbort);if(error!==void 0)reject(error);else resolve(permit)},"finish");const inspect=__name(()=>{try{const permit=runtime.permitForTurn(turnKey);if(permit||runtime.getSnapshot().goal?.status!=="active"){finish(permit)}}catch(error){finish(void 0,error)}},"inspect");const onAbort=__name(()=>finish(void 0),"onAbort");unsubscribe=runtime.subscribe(inspect);signal.addEventListener("abort",onAbort,{once:true});if(signal.aborted)onAbort();else inspect()})}__name(claimUserGoalTurn,"claimUserGoalTurn");function skipHeadlessLoopSentinel(scheduler,job){if(!isHeadlessLoopSentinel(job.prompt)){return false}if(job.recurring&&!job.durable){debugLogger.debug("skipHeadlessLoopSentinel: cleaning up recurring session loop.md cron in headless mode",{jobId:job.id});void scheduler.delete(job.id).catch(()=>{})}return true}__name(skipHeadlessLoopSentinel,"skipHeadlessLoopSentinel");var PROVIDER_DUPLICATE_ID_LOOP_STOP={loopType:"global_tool_call_duplicate",loopReason:"provider_duplicate_id"};function emitLoopDetectedMessage(config,stop){const message=formatLoopDetectedMessage(stop);if(config.getOutputFormat()!=="text"){return message}process.stderr.write(`${message}
4
4
  `);return message}__name(emitLoopDetectedMessage,"emitLoopDetectedMessage");async function emitNonInteractiveFinalMessage(params){const{message,isError,adapter,config}=params;adapter.startAssistantMessage();adapter.processEvent({type:"content",value:message});adapter.finalizeAssistantMessage();const metrics=uiTelemetryService.getMetrics();const usage=computeUsageFromMetrics(metrics);const outputFormat=config.getOutputFormat();const stats=outputFormat==="json"?uiTelemetryService.getMetrics():void 0;await params.beforeEmit();adapter.emitResult({isError,durationMs:Date.now()-params.startTimeMs,apiDurationMs:0,numTurns:0,errorMessage:isError?message:void 0,usage,stats,summary:message})}__name(emitNonInteractiveFinalMessage,"emitNonInteractiveFinalMessage");function partitionHeadlessToolCalls(requests,config){let skillBefore=false;return partitionByConcurrencySafety(requests,request=>{const executionRequest=getHeadlessExecutionRequest(request,config);const canonicalName=canonicalToolName(executionRequest.name);const kind=config.getToolRegistry().getTool(canonicalName)?.kind;const inputMayChange=kind==="execute"&&(skillBefore||!config.getDisableAllHooks()&&(config.hasHooksForEvent("PreToolUse")||config.hasHooksForEvent("PermissionRequest")));skillBefore||=canonicalName===ToolNames.SKILL;return!inputMayChange&&isToolCallConcurrencySafe(executionRequest.name,kind,executionRequest.args)})}__name(partitionHeadlessToolCalls,"partitionHeadlessToolCalls");function getHeadlessExecutionRequest(request,config){if(canonicalToolName(request.name)!==ToolNames.TOOL_CALL){return request}const targetName=request.args["name"];let targetArgs=request.args["arguments"];if(typeof targetArgs==="string"){try{targetArgs=JSON.parse(targetArgs)}catch{return request}}if(typeof targetName!=="string"||typeof targetArgs!=="object"||targetArgs===null||Array.isArray(targetArgs)){return request}const registry=config.getToolRegistry();const target=registry.getTool(canonicalToolName(targetName));if(!target||!registry.isDeferredAndHidden(target.name)){return request}return{...request,name:target.name,args:targetArgs}}__name(getHeadlessExecutionRequest,"getHeadlessExecutionRequest");async function runNonInteractive(config,settings,input,prompt_id,options={}){return promptIdContext.run(prompt_id,async()=>{let adapter;const outputFormat=config.getOutputFormat();if(options.adapter){adapter=options.adapter}else if(outputFormat==="stream-json"){adapter=new StreamJsonOutputAdapter(config,config.getIncludePartialMessages())}else{adapter=new JsonOutputAdapter(config)}const ownsAdapter=options.adapter===void 0;const modSession=options.modSession??ModSession.create(config,settings,adapter);const ownsModSession=options.modSession===void 0;let modTurn;const unsubscribeRecordingFailure=ownsAdapter?subscribeToHeadlessChatRecordingFailures(config,adapter):void 0;let chatRecordingSettlement;const settleBeforeTerminalOutput=__name(()=>{chatRecordingSettlement??=(async()=>{await modTurn?.complete(abortController.signal.aborted&&!budgetEnforcer.getExceeded()?"aborted":"error");if(ownsModSession)await modSession?.close();modSession?.flushLogs();await settleChatRecording(config,{finalize:ownsAdapter})})();return chatRecordingSettlement},"settleBeforeTerminalOutput");const emitResult=__name(async result=>{await settleBeforeTerminalOutput();adapter.emitResult(result);options.onResultEmitted?.();await modSession?.flushOutput()},"emitResult");const sessionId=config.getSessionId();const permissionMode=config.getApprovalMode();const cleanupReviewWorktrees=__name(gitTimeout=>{if(config.getShellExecutionSandbox?.())return;cleanupReviewWorktreeLeases({sessionId,promptId:prompt_id,repositoryRoot:config.getProjectRoot(),gitTimeout})},"cleanupReviewWorktrees");const unregisterReviewWorktreeCleanup=registerCleanup(()=>cleanupReviewWorktrees(1e3));let turnCount=0;let limitedTurnCount=0;let totalApiDurationMs=0;const startTime=Date.now();let activeInteractionPromptId=prompt_id;let activeInteractionOwner;const selectActiveInteraction=__name((promptId,startsInteraction=false)=>{if(startsInteraction||activeInteractionPromptId!==promptId){activeInteractionOwner=void 0}activeInteractionPromptId=promptId},"selectActiveInteraction");const captureActiveInteractionOwner=__name(()=>{activeInteractionOwner??=getActiveInteractionSpan(activeInteractionPromptId);return activeInteractionOwner},"captureActiveInteractionOwner");const endActiveInteraction=__name((status,metadata={})=>{const owner=captureActiveInteractionOwner();if(!owner||getActiveInteractionSpan(activeInteractionPromptId)!==owner){return}endInteractionSpan(status,{promptId:activeInteractionPromptId,...metadata})},"endActiveInteraction");const llmClient=config.getLlmClient();const abortController=options.abortController??new AbortController;const queuedGoalTurns=[];let activeGoalTurn;let goalRuntimeUnsubscribe;const emitGoalSnapshot=__name(snapshot=>{adapter.processEvent({type:"goal_state",value:snapshot})},"emitGoalSnapshot");const observeGoalRuntime=__name(runtime=>{goalRuntimeUnsubscribe??=runtime.subscribe(emitGoalSnapshot)},"observeGoalRuntime");const enforceSessionTurnLimit=__name(async isRuntimeGoalTurn=>{if(isRuntimeGoalTurn)return;limitedTurnCount++;const maxSessionTurns=config.getMaxSessionTurns();if(maxSessionTurns>=0&&limitedTurnCount>maxSessionTurns){await failClosedActiveGoalTurn("Headless Goal stopped after the session turn limit");await settleBeforeTerminalOutput();await handleMaxTurnsExceededError(config)}},"enforceSessionTurnLimit");let goalHostUnbind;const goalHost={startGoalTurn:__name(async input2=>{if(queuedGoalTurns.some(({permit:permit2})=>permit2.turnId===input2.permit.turnId)){return}const{permit,...continuation}=input2;queuedGoalTurns.push({permit:{...permit},turnKey:`goal-runtime:${permit.turnId}`,controller:new AbortController,origin:"runtime",...continuation})},"startGoalTurn"),preemptGoalTurn:__name(reason=>{for(const turn of queuedGoalTurns.splice(0)){turn.controller.abort(reason)}activeGoalTurn?.controller.abort(reason)},"preemptGoalTurn")};const bindGoalHost=__name(()=>{goalHostUnbind??=config.bindGoalTurnHost(goalHost)},"bindGoalHost");const markGoalTurnDelivered=__name(turn=>{try{config.getGoalRuntime().markTurnDelivered(turn.turnKey)}catch{}},"markGoalTurnDelivered");let settlingGoalTurn;let goalTurnSettlement;const failClosedActiveGoalTurn=__name((reason,pauseReason)=>{const turn=activeGoalTurn;if(!turn)return Promise.resolve();if(settlingGoalTurn===turn&&goalTurnSettlement){return goalTurnSettlement}settlingGoalTurn=turn;goalTurnSettlement=(async()=>{if(!turn.controller.signal.aborted){turn.controller.abort(reason)}try{const runtime=await config.getGoalRuntimeReady();if(!sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){return}if(runtime.getSnapshot().goal?.status==="active"){try{await runtime.dispatch({action:"pause",expectedGoalId:turn.permit.goalId,expectedRevision:turn.permit.revision,reason:pauseReason??goalPauseReasonForHeadlessFailure(reason)})}catch(error){debugLogger.warn("Failed to pause terminal headless Goal",error)}}try{await config.getChatRecordingService?.()?.flush()}catch(error){debugLogger.warn("Failed to flush terminal headless Goal",error)}if(sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){await runtime.finishTurn(turn.permit)}}catch(error){debugLogger.warn("Failed to close terminal headless Goal",error)}finally{if(activeGoalTurn===turn){activeGoalTurn=void 0}if(settlingGoalTurn===turn){settlingGoalTurn=void 0;goalTurnSettlement=void 0}}})();return goalTurnSettlement},"failClosedActiveGoalTurn");const finishGoalTurn=__name(async turn=>{const runtime=await config.getGoalRuntimeReady();if(!sameGoalPermit(runtime.permitForTurn(turn.turnKey),turn.permit)){return}let abortSettlement;const pauseOnAbort=__name(()=>{const exceeded=budgetEnforcer.getExceeded();abortSettlement??=runtime.dispatch({action:"pause",expectedGoalId:turn.permit.goalId,expectedRevision:turn.permit.revision,reason:exceeded?goalPauseReasonForRunBudget(exceeded.kind):GOAL_PAUSE_REASON_USER_INTERRUPT}).then(()=>void 0).catch(error=>{debugLogger.warn("Failed to pause aborted headless Goal",error)})},"pauseOnAbort");abortController.signal.addEventListener("abort",pauseOnAbort,{once:true});if(abortController.signal.aborted)pauseOnAbort();try{if(!abortController.signal.aborted){await runtime.finishTurn(turn.permit)}}finally{abortController.signal.removeEventListener("abort",pauseOnAbort);await abortSettlement}},"finishGoalTurn");const budgetEnforcer=new RunBudgetEnforcer({maxWallTimeSeconds:config.getMaxWallTimeSeconds(),maxToolCalls:config.getMaxToolCalls()},abortController);const stampBudgetAbort=__name(()=>{const exceeded=budgetEnforcer.getExceeded();if(!exceeded)return;endActiveInteraction("error",{errorMessage:exceeded.message,errorType:"run_budget_exceeded"})},"stampBudgetAbort");abortController.signal.addEventListener("abort",stampBudgetAbort,{once:true});budgetEnforcer.start();const routeAbort=__name(async()=>{const exceeded=budgetEnforcer.getExceeded();endActiveInteraction(exceeded?"error":"cancelled",{...exceeded?{errorMessage:exceeded.message,errorType:"run_budget_exceeded"}:{}});await failClosedActiveGoalTurn(exceeded?.message??"Headless Goal execution was cancelled",exceeded?goalPauseReasonForRunBudget(exceeded.kind):GOAL_PAUSE_REASON_USER_INTERRUPT);await settleBeforeTerminalOutput();if(exceeded){await handleBudgetExceededError(config,exceeded);throw new Error(exceeded.message)}const reason=abortController.signal.reason;if(reason instanceof TurnInterruptedError&&(options.recoverableCancellation===true||reason instanceof ModTurnAbortedError)){throw reason}await handleCancellationError(config);throw new Error("Operation cancelled.")},"routeAbort");const localQueue=[];const sdkOnlyMonitorQueue=[];const isCancelledMonitorEvent=__name(item=>Boolean(item.monitorId&&item.sdkNotification?.status==="running"&&config.getMonitorRegistry().get(item.monitorId)?.status==="cancelled"),"isCancelledMonitorEvent");const emitNotificationToSdk=__name(item=>{if(item.sendMessageType!=="notification")return;adapter.emitUserMessage([{text:item.displayText}]);if(item.sdkNotification){adapter.emitSystemMessage("task_notification",item.sdkNotification)}},"emitNotificationToSdk");const flushQueuedNotificationsToSdk=__name(queue=>{while(queue.length>0){const item=queue.shift();if(!isCancelledMonitorEvent(item)){emitNotificationToSdk(item)}}},"flushQueuedNotificationsToSdk");let captureMonitorTurnsInLocalQueue=true;let oneShotMonitorsFinalized=false;const finalizeOneShotMonitors=__name(()=>{if(options.captureMonitorNotifications===false||oneShotMonitorsFinalized)return;oneShotMonitorsFinalized=true;captureMonitorTurnsInLocalQueue=false;config.getMonitorRegistry().abortAll();flushQueuedNotificationsToSdk(sdkOnlyMonitorQueue)},"finalizeOneShotMonitors");let pipeBroken=false;let workflowApprovalChannelRegistered=false;const stdoutErrorHandler=__name(err=>{if(err.code==="EPIPE"&&!pipeBroken){pipeBroken=true;process.stdout.destroy()}},"stdoutErrorHandler");const shutdownHandler=__name(()=>{debugLogger.debug("[runNonInteractive] Shutdown signal received");abortController.abort()},"shutdownHandler");const pendingTeammateMessages=[];let boundManager=null;let approvalListener=null;const detachFromManager=__name(m=>{m.setLeaderMessageCallback(null);if(approvalListener){m.getEventEmitter().off("teammate_approval_request",approvalListener);approvalListener=null}},"detachFromManager");const onTeamManagerChangeHandler=__name(manager=>{if(boundManager&&boundManager!==manager){detachFromManager(boundManager)}boundManager=manager;if(manager){manager.setLeaderMessageCallback(formatted=>{pendingTeammateMessages.push(formatted)});if(options.controlService){approvalListener=__name(event=>{options.controlService.permission.handleTeammateApproval(event).catch(err=>{debugLogger.warn("Teammate approval handling failed:",err)})},"approvalListener")}else{approvalListener=__name(event=>{const mode=config.getApprovalMode();const confirmationDetails=event.confirmationDetails;const requiresExplicitHostApproval=confirmationDetails?.type!=="plan"&&confirmationDetails!==void 0&&"hideAlwaysAllow"in confirmationDetails&&confirmationDetails.hideAlwaysAllow===true;if(mode==="yolo"&&!requiresExplicitHostApproval){event.respond("proceed_once").catch(err=>{debugLogger.warn("Teammate approval ProceedOnce failed:",err)});return}const reason=requiresExplicitHostApproval?mode==="yolo"?`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": this request requires an explicit interactive approval surface and cannot be bypassed by YOLO mode.`:`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": this request requires an explicit interactive approval surface, which is unavailable in non-stream-json mode with the current approval mode (${mode}). Use --input-format stream-json --output-format stream-json to review it.`:`Auto-cancelling tool ${event.toolName} requested by teammate "${event.teammateName}": current approval mode (${mode}) cannot prompt in non-stream-json mode. Use --yolo or stream-json to allow teammate tool calls.`;process.stderr.write(`[team] ${reason}
5
5
  `);pendingTeammateMessages.push(`<team_notice>
6
6
  ${reason}
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{createManagedContextAttestationResponse,isManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{getCliVersion}from"./chunk-MXZXQUVP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync,spawn}from"node:child_process";import{createHash as createHash3,createHmac,randomUUID}from"node:crypto";import{constants as constants3,promises as fs3}from"node:fs";import path3 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";import{constants,promises as fs}from"node:fs";import path from"node:path";var MAX_WORKSPACE_UPLOAD_BYTES=8*1024*1024;var WorkspaceFileError=class extends Error{constructor(code){super("Workspace file request is unavailable.");this.code=code}static{__name(this,"WorkspaceFileError")}};function refuse(code="unavailable"){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse,"refuse");function workspaceFilePath(value){if(value===".")return".";if(typeof value!=="string"||value.length>1024||/[\\\p{Cc}\p{Cs}]/u.test(value)||value.split("/").some(part=>!part||part==="."||part===".."||part===".git"||part===".qwen-child-workspaces"||part.startsWith(".qwen-managed-")))refuse("invalid_path");return value}__name(workspaceFilePath,"workspaceFilePath");function sessionWorkspaceFileScope(value,cwdRelative){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const scope=value;const keys=["sessionId","contextDigest","worktreeId","worktreeRevision","cwdRelative","worktreeRootIdentity"];if(Object.keys(scope).length!==keys.length||keys.some(key=>!(key in scope))||typeof scope["sessionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(scope["sessionId"])||typeof scope["contextDigest"]!=="string"||!/^sha256:[a-f0-9]{64}$/.test(scope["contextDigest"])||typeof scope["worktreeId"]!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(scope["worktreeId"])||!Number.isSafeInteger(scope["worktreeRevision"])||Number(scope["worktreeRevision"])<1||typeof cwdRelative!=="string"||scope["cwdRelative"]!==cwdRelative)refuse("invalid_request");const prefix=`.qwen-managed-worktrees/${scope["worktreeId"]}`;if(cwdRelative!==prefix&&!cwdRelative.startsWith(`${prefix}/`))refuse("invalid_path");workspaceFilePath(cwdRelative.slice(prefix.length+1)||".");const identity=scope["worktreeRootIdentity"];if(!identity||typeof identity!=="object"||Array.isArray(identity))refuse("invalid_request");const fields=identity;if(Object.keys(fields).length!==2||!["device","inode"].every(key=>typeof fields[key]==="string"&&/^\d+$/.test(fields[key])))refuse("invalid_request");return scope}__name(sessionWorkspaceFileScope,"sessionWorkspaceFileScope");function signature(stat){return[stat.dev,stat.ino,stat.birthtimeNs,stat.size,stat.mtimeNs,stat.ctimeNs].join(":")}__name(signature,"signature");async function workspaceFileDirectories(root,cwdRelative,expected,sessionScope){const scope=sessionWorkspaceFileScope(sessionScope,cwdRelative);const cwd=scope?.cwdRelative??workspaceFilePath(cwdRelative);const worktreeRoot=scope?path.join(root,".qwen-managed-worktrees",scope.worktreeId):void 0;const anchors=new Map;async function directory(relative){const segments=relative==="."?[]:relative.split("/");let current=root;for(const segment of["",...segments]){if(segment)current=path.join(current,segment);const stat=await fs.lstat(current,{bigint:true});if(!stat.isDirectory()||await fs.realpath(current)!==current)refuse();if(current===root&&(String(stat.dev)!==expected.device||String(stat.ino)!==expected.inode))refuse();if(scope&&current===worktreeRoot&&(String(stat.dev)!==scope.worktreeRootIdentity.device||String(stat.ino)!==scope.worktreeRootIdentity.inode))refuse("changed");const prior=anchors.get(current);const identity=[stat.dev,stat.ino,stat.birthtimeNs].join(":");if(prior&&prior!==identity)refuse("changed");anchors.set(current,identity)}return current}__name(directory,"directory");async function verify(){for(const[name,identity]of anchors){const stat=await fs.lstat(name,{bigint:true});if(!stat.isDirectory()||await fs.realpath(name)!==name||[stat.dev,stat.ino,stat.birthtimeNs].join(":")!==identity)refuse("changed")}}__name(verify,"verify");const base=await directory(cwd);const rooted=__name(relative=>cwd==="."?relative:relative==="."?cwd:`${cwd}/${relative}`,"rooted");return{base,directory:__name(relative=>directory(rooted(relative)),"directory"),verify}}__name(workspaceFileDirectories,"workspaceFileDirectories");async function readWorkspaceFiles(root,cwdRelative,value,expected,sessionScope){if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const request=value;if(request["protocolVersion"]!==1)refuse("unsupported");const{base,directory,verify}=await workspaceFileDirectories(root,cwdRelative,expected,sessionScope);if(request["operation"]==="read"){const relative2=workspaceFilePath(request["path"]);if(relative2===".")refuse("invalid_path");const parent=path.posix.dirname(relative2);await directory(parent);const filename=path.join(base,relative2);const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(!before.isFile()||before.size===0n||before.size>24n*1024n)refuse("unsupported_content");const bytes=Buffer.alloc(24*1024+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}if(BigInt(size)!==before.size||signature(before)!==signature(await handle.stat({bigint:true}))||signature(before)!==signature(await fs.lstat(filename,{bigint:true})))refuse("changed");let text2;try{text2=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(bytes.subarray(0,size))}catch{return refuse("unsupported_content")}if(!text2||text2.includes("\0"))refuse("unsupported_content");await verify();const result={protocolVersion:1,path:relative2,name:path.posix.basename(relative2),mimeType:"text/plain",text:text2,byteLength:size,sha256:createHash("sha256").update(bytes.subarray(0,size)).digest("hex")};if(Buffer.byteLength(JSON.stringify(result))>48*1024)refuse("too_large");return result}finally{await handle.close()}}if(request["operation"]!=="query")refuse("invalid_request");const relative=workspaceFilePath(request["directory"]??".");const query=request["query"]??"";if(typeof query!=="string"||query.length>256||/[\p{Cc}\p{Cs}]/u.test(query))refuse("invalid_request");const entries=[];let scanned=0;let truncated=false;const deadline=Date.now()+2e3;const queue=[{relative,depth:0}];while(queue.length){const next=queue.shift();const dir=await directory(next.relative);const stream=await fs.opendir(dir);for await(const entry of stream){if(++scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}const name=next.relative==="."?entry.name:`${next.relative}/${entry.name}`;try{workspaceFilePath(name)}catch{continue}if(!entry.isFile()&&!entry.isDirectory())continue;if(query&&entry.isDirectory()){if(next.depth<32)queue.push({relative:name,depth:next.depth+1});else truncated=true}if(query&&(entry.isDirectory()||!name.toLowerCase().includes(query.toLowerCase())))continue;const item={path:name,name:entry.name,kind:entry.isDirectory()?"directory":"file"};if(Buffer.byteLength(JSON.stringify([...entries,item]))>24*1024){truncated=true;break}entries.push(item)}if(scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}}await verify();return{protocolVersion:1,directory:relative,entries,truncated,maxUploadBytes:MAX_WORKSPACE_UPLOAD_BYTES}}__name(readWorkspaceFiles,"readWorkspaceFiles");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{constants as constants2,promises as fs2}from"node:fs";import path2 from"node:path";function refuse2(code){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse2,"refuse");function failed(metadata,error){return workspaceUploadResult(metadata,"failed",error instanceof WorkspaceFileError?error.code:error.code==="EEXIST"?"ssh_runtime_file_exists":"ssh_runtime_file_unavailable")}__name(failed,"failed");function workspaceUploadRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))refuse2("invalid_request");const request=value;if(request["protocolVersion"]!==1||!["upload","upload-status"].includes(String(request["operation"]))||typeof request["uploadId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(request["uploadId"])||!Number.isSafeInteger(request["sizeBytes"])||Number(request["sizeBytes"])<0||Number(request["sizeBytes"])>MAX_WORKSPACE_UPLOAD_BYTES||typeof request["sha256"]!=="string"||!/^[0-9a-f]{64}$/.test(request["sha256"]))refuse2("invalid_request");const relative=workspaceFilePath(request["path"]);if(relative===".")refuse2("invalid_path");const metadata={uploadId:request["uploadId"],path:relative,sizeBytes:Number(request["sizeBytes"]),sha256:request["sha256"]};if(request["operation"]==="upload-status"){if(request["data"]!==void 0)refuse2("invalid_request");return{metadata}}const data=request["data"];if(typeof data!=="string"||data.length!==Math.ceil(metadata.sizeBytes/3)*4)refuse2("invalid_content");const bytes=Buffer.from(data,"base64");if(bytes.length!==metadata.sizeBytes||bytes.toString("base64")!==data||createHash2("sha256").update(bytes).digest("hex")!==metadata.sha256)refuse2("invalid_content");return{metadata,bytes}}__name(workspaceUploadRequest,"workspaceUploadRequest");function workspaceUploadResult(metadata,state,code){return{protocolVersion:1,...metadata,state,...code===void 0?{}:{code}}}__name(workspaceUploadResult,"workspaceUploadResult");function temporaryPath(directory,metadata){return path2.join(directory,`.qwen-managed-upload-${metadata.uploadId}.tmp`)}__name(temporaryPath,"temporaryPath");async function removeTemporary(temporary){try{await fs2.unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}}__name(removeTemporary,"removeTemporary");async function syncDirectory(directory){const handle=await fs2.open(directory,"r");try{await handle.sync()}finally{await handle.close()}}__name(syncDirectory,"syncDirectory");async function writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope){let directories;let parent;try{await verifyStorage();directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);parent=await directories.directory(path2.posix.dirname(metadata.path))}catch(error){return failed(metadata,error)}const destination=path2.join(directories.base,metadata.path);const temporary=temporaryPath(parent,metadata);let ownsTemporary=false;let result;try{const handle=await fs2.open(temporary,"wx",384);ownsTemporary=true;try{await handle.writeFile(bytes);await handle.sync()}finally{await handle.close()}await directories.verify();await verifyStorage();await fs2.link(temporary,destination);await directories.verify();await verifyStorage();result=workspaceUploadResult(metadata,"completed")}catch(error){result=failed(metadata,error)}finally{if(ownsTemporary){await directories.verify();await removeTemporary(temporary);await syncDirectory(parent)}}return result}__name(writeWorkspaceUpload,"writeWorkspaceUpload");async function inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope){await verifyStorage();const directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);const parent=await directories.directory(path2.posix.dirname(metadata.path));const destination=path2.join(directories.base,metadata.path);let completed=false;try{const handle=await fs2.open(destination,constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(before.isFile()&&before.size===BigInt(metadata.sizeBytes)){const bytes=Buffer.alloc(metadata.sizeBytes+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}const after=await handle.stat({bigint:true});const current=await fs2.lstat(destination,{bigint:true});completed=size===metadata.sizeBytes&&before.dev===current.dev&&before.ino===current.ino&&before.mtimeNs===after.mtimeNs&&before.ctimeNs===after.ctimeNs&&before.size===after.size&&after.ctimeNs===current.ctimeNs&&createHash2("sha256").update(bytes.subarray(0,size)).digest("hex")===metadata.sha256}}finally{await handle.close()}}catch(error){if(!["ENOENT","ELOOP"].includes(error.code??""))throw error}await directories.verify();await verifyStorage();await removeTemporary(temporaryPath(parent,metadata));await syncDirectory(parent);return workspaceUploadResult(metadata,completed?"completed":"failed",completed?void 0:"ssh_runtime_file_upload_incomplete")}__name(inspectWorkspaceUpload,"inspectWorkspaceUpload");var MARKER=".qwen-managed-storage.json";var MAX_BYTES=64*1024;var MAX_UPLOAD_REQUEST_BYTES=12*1024*1024;var ID=/^[a-zA-Z0-9_.:-]{1,512}$/;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var hostId;var SSH_RETIRE_PATH="/internal/managed-runtime/v3/retire";var SshBootstrapError=class extends Error{constructor(code,message,retryable=false){super(message);this.code=code;this.retryable=retryable}static{__name(this,"SshBootstrapError")}};function refuse3(message){throw new SshBootstrapError("ssh_runtime_identity_conflict",message)}__name(refuse3,"refuse");function object(value){if(!value||typeof value!=="object"||Array.isArray(value))return refuse3("Runtime bootstrap document is invalid.");return value}__name(object,"object");function text(value){if(typeof value!=="string"||!value||value.includes("\0"))return refuse3("Runtime bootstrap text is invalid.");return value}__name(text,"text");function absolute(value){const directory=text(value);if(!path3.isAbsolute(directory)||path3.resolve(directory)!==directory)return refuse3("Runtime path must be absolute and normalized.");return directory}__name(absolute,"absolute");function within(root,candidate){const relative=path3.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path3.sep}`)&&!path3.isAbsolute(relative)}__name(within,"within");function exact(value,fields){if(Object.keys(value).length!==fields.length||fields.some(field=>!(field in value)))refuse3("Runtime bootstrap document has unexpected fields.")}__name(exact,"exact");async function readSshPrivateJson(file){const stat=await fs3.lstat(file);if(!stat.isFile()||stat.size>MAX_BYTES||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state file is not owner-private.");return JSON.parse(await fs3.readFile(file,"utf8"))}__name(readSshPrivateJson,"readSshPrivateJson");async function syncParentDirectory(file){const directory=await fs3.open(path3.dirname(file),"r");try{await directory.sync()}finally{await directory.close()}}__name(syncParentDirectory,"syncParentDirectory");async function writeSshPrivateJson(file,value){if(!await createSshPrivateJson(file,value)&&!isDeepStrictEqual(await readSshPrivateJson(file),value))refuse3("Runtime state conflicts with an earlier operation.")}__name(writeSshPrivateJson,"writeSshPrivateJson");async function createSshPrivateJson(file,value){const temporary=path3.join(path3.dirname(file),`.${path3.basename(file)}.${randomUUID()}.tmp`);const handle=await fs3.open(temporary,"wx",384);let created=true;try{try{await handle.writeFile(JSON.stringify(value),"utf8");await handle.sync()}finally{await handle.close()}try{await fs3.link(temporary,file)}catch(error){if(error.code!=="EEXIST")throw error;created=false}}finally{await fs3.unlink(temporary)}await syncParentDirectory(file);return created}__name(createSshPrivateJson,"createSshPrivateJson");async function privateDirectory(directory){const created=await fs3.mkdir(directory,{recursive:true,mode:448});const stat=await fs3.lstat(directory);if(!stat.isDirectory()||await fs3.realpath(directory)!==directory||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state directory must be canonical and owner-private.");for(let current=directory;;current=path3.dirname(current)){await syncParentDirectory(current);if(created===void 0||current===created)break}}__name(privateDirectory,"privateDirectory");function identityDocument(value){const identity=object(value);exact(identity,["root","hostId","device","inode","birthTime"]);absolute(identity["root"]);if(!/^[0-9a-f]{64}$/.test(text(identity["hostId"]))||!/^\d+$/.test(text(identity["device"]))||!/^\d+$/.test(text(identity["inode"]))||!Number.isFinite(Date.parse(text(identity["birthTime"]))))refuse3("Storage identity is invalid.");return identity}__name(identityDocument,"identityDocument");function markerDocument(value,identity){const marker=object(value);exact(marker,["version","tenantId","storageId","root","hostId","device","inode","birthTime","registrationId"]);if(marker["version"]!==2||!UUID.test(text(marker["registrationId"]))||!ID.test(text(marker["tenantId"]))||!ID.test(text(marker["storageId"]))||Object.entries(identity).some(([key,item])=>marker[key]!==item))refuse3("Storage marker does not bind the registered identity.");return marker}__name(markerDocument,"markerDocument");async function inspectSshStorage(root){if(!["linux","darwin"].includes(process.platform))throw new SshBootstrapError("ssh_runtime_platform_unsupported","Runtime requires Linux or macOS.");if(absolute(root)!==await fs3.realpath(root))refuse3("Storage root is not canonical.");const stat=await fs3.lstat(root,{bigint:true});if(!stat.isDirectory()||stat.birthtimeNs<=0n)refuse3("Storage directory has no independent birth identity.");await fs3.access(root,constants3.R_OK|constants3.W_OK|constants3.X_OK);const machine=hostId?void 0:process.platform==="linux"?(await fs3.readFile("/etc/machine-id","utf8")).trim():/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(execFileSync("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:MAX_BYTES}))?.[1];if(!hostId){if(!machine||machine.length>256)refuse3("Stable host identity is unavailable.");hostId=createHmac("sha256",machine).update("Qwen-Code/verified-workspace/v2").digest("hex")}const seconds=stat.birthtimeNs/1000000000n;const nanos=(stat.birthtimeNs%1000000000n).toString().padStart(9,"0");const fraction=nanos==="000000000"?"":`.${nanos.endsWith("000000")?nanos.slice(0,3):nanos.endsWith("000")?nanos.slice(0,6):nanos}`;return{root,hostId,device:BigInt.asUintN(64,stat.dev).toString(),inode:BigInt.asUintN(64,stat.ino).toString(),birthTime:new Date(Number(seconds)*1e3).toISOString().replace(/\.000Z$/,`${fraction}Z`)}}__name(inspectSshStorage,"inspectSshStorage");async function verifySshStorage(identity,marker){if(!isDeepStrictEqual(await inspectSshStorage(identity.root),identity))refuse3("Registered storage identity changed.");if(marker&&!isDeepStrictEqual(await readSshPrivateJson(path3.join(identity.root,MARKER)),marker))refuse3("Registered storage marker changed.")}__name(verifySshStorage,"verifySshStorage");function resourceDirectory(stateDirectory,resourceId){if(!UUID.test(resourceId))refuse3("Runtime resource identity is invalid.");return path3.join(stateDirectory,"resources",resourceId)}__name(resourceDirectory,"resourceDirectory");async function readSshRuntimeRecord(directory){const value=object(await readSshPrivateJson(path3.join(directory,"intent.json")));exact(value,["version","nodeId","stateDirectory","resourceId","bindingId","bindingGeneration","boot","identity","marker","workerEntry","expectedQwenVersion"]);const identity=identityDocument(value["identity"]);const boot=parseManagedContextBoot(value["boot"]);const marker=markerDocument(value["marker"],identity);if(value["version"]!==1||!ID.test(text(value["nodeId"]))||!ID.test(text(value["bindingId"]))||!Number.isSafeInteger(value["bindingGeneration"])||Number(value["bindingGeneration"])<=0||boot.isolationClass!=="session"||boot.mountRoot!==identity.root||boot.tenantId!==marker.tenantId||boot.storageId!==marker.storageId||resourceDirectory(absolute(value["stateDirectory"]),text(value["resourceId"]))!==directory)refuse3("Runtime intent identity is invalid.");absolute(value["workerEntry"]);text(value["expectedQwenVersion"]);return value}__name(readSshRuntimeRecord,"readSshRuntimeRecord");function sshCleanProof(record,retirementId,retiredAt){return{version:record.boot.managedExtensions?2:1,...record.boot.managedExtensions?{executionMode:record.boot.managedExtensions.mode,scope:record.boot.managedExtensions.mode==="linux-cgroup"?"process_tree":"process_group"}:{},resourceId:record.resourceId,bindingId:record.bindingId,bindingGeneration:record.bindingGeneration,provisionRequestId:record.boot.provisionRequestId,runtimeInstanceId:record.boot.runtimeInstanceId,runtimeIncarnation:record.boot.runtimeIncarnation,leaseId:record.boot.leaseId,epoch:record.boot.epoch,retirementId,retiredAt}}__name(sshCleanProof,"sshCleanProof");function alive(pid){try{process.kill(pid,0);return true}catch(error){if(error.code==="ESRCH")return false;throw new SshBootstrapError("ssh_runtime_stop_unverified","Original process liveness is unverified.")}}__name(alive,"alive");async function optionalJson(file){try{return await readSshPrivateJson(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(optionalJson,"optionalJson");async function observe(record){await verifySshStorage(record.identity,record.marker);const directory=resourceDirectory(record.stateDirectory,record.resourceId);const pidRecord=await optionalJson(path3.join(directory,"pid.json"));const pid=pidRecord===void 0?null:object(pidRecord)["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Runtime process record is invalid.");const result={resourceId:record.resourceId,state:"INTENT",pid,ready:null};const claim=await optionalJson(path3.join(directory,"launch.claim"));if(claim===void 0){for(const file of["pid.json","ready.json","clean.json","stdout.log","stderr.log","launch-failed.json"]){try{await fs3.lstat(path3.join(directory,file))}catch(error){if(error.code==="ENOENT")continue;throw error}refuse3("Runtime launch claim is missing from an existing resource.")}return result}const claimedRetirement=object(claim)["retirementId"];const neverStarted=typeof claimedRetirement==="string"&&UUID.test(claimedRetirement);if(!isDeepStrictEqual(claim,neverStarted?{provisionRequestId:record.boot.provisionRequestId,retirementId:claimedRetirement}:{provisionRequestId:record.boot.provisionRequestId}))refuse3("Runtime launch claim conflicts.");if(neverStarted&&pid!==null)refuse3("A retired launch claim cannot own a worker process.");const failed2=await optionalJson(path3.join(directory,"launch-failed.json"));if(failed2!==void 0&&(!isDeepStrictEqual(failed2,{provisionRequestId:record.boot.provisionRequestId})||pid!==null||await optionalJson(path3.join(directory,"ready.json"))!==void 0))refuse3("Runtime failed-launch evidence conflicts.");const clean=await optionalJson(path3.join(directory,"clean.json"));if(clean!==void 0){const proof=object(clean);const retiredAt=text(proof["retiredAt"]);const stop=object(await readSshPrivateJson(path3.join(directory,"stop.json")));if(!Number.isFinite(Date.parse(retiredAt))||!isDeepStrictEqual(clean,sshCleanProof(record,text(stop["retirementId"]),retiredAt)))refuse3("Runtime clean proof conflicts.");if((neverStarted||failed2!==void 0)&&pid===null&&(failed2!==void 0||claimedRetirement===stop["retirementId"])||pid!==null&&!alive(Number(pid)))return{...result,state:"RETIRED",cleanProof:clean};return{...result,state:"BLOCKED"}}if(failed2!==void 0)return{...result,state:"FAILED"};if(neverStarted&&pid===null)return result;if(pid===null||!alive(Number(pid)))return{...result,state:"BLOCKED"};const ready=await optionalJson(path3.join(directory,"ready.json"));if(ready===void 0)return{...result,state:"STARTING"};const value=object(ready);if(!isManagedContextReady(value,record.boot))refuse3("Runtime ready identity conflicts.");return{...result,state:"READY",ready:value}}__name(observe,"observe");async function attest(record,ready){const expected=createManagedContextAttestationResponse(record.boot);const{runtimeInstanceId:_runtime,runtimeIncarnation:_incarnation,leaseId:_lease,epoch:_epoch,...request}=expected;const response=await fetch(`${ready.url}/internal/managed-runtime/v3/attest`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify(request),redirect:"error",signal:AbortSignal.timeout(5e3)});if(!response.ok||!isDeepStrictEqual(await response.json(),expected))refuse3("Original Runtime attestation failed.")}__name(attest,"attest");function sshRuntimeHeaders(boot){return{Authorization:`Bearer ${boot.token}`,"Cache-Control":"no-store","Content-Type":"application/json","X-Qwen-Managed-Lease-Id":boot.leaseId,"X-Qwen-Managed-Lease-Epoch":String(boot.epoch)}}__name(sshRuntimeHeaders,"sshRuntimeHeaders");async function ensure(request,nodeId,stateDirectory){const resourceId=text(request["resourceId"]);const expectedQwenVersion=text(request["expectedQwenVersion"]);if(expectedQwenVersion!==await getCliVersion()){throw new SshBootstrapError("ssh_runtime_version_conflict","Pinned Qwen version does not match this installation.")}const directory=resourceDirectory(stateDirectory,resourceId);const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity,marker);await privateDirectory(directory);const record={version:1,nodeId,stateDirectory,resourceId,bindingId:request["bindingId"],bindingGeneration:request["bindingGeneration"],boot:request["boot"],identity,marker,workerEntry:absolute(request["workerEntry"]),expectedQwenVersion};await writeSshPrivateJson(path3.join(directory,"intent.json"),record);const saved=await readSshRuntimeRecord(directory);if(typeof request["launch"]!=="boolean")refuse3("Runtime launch phase is required.");if(!request["launch"])return observe(saved);if(await optionalJson(path3.join(directory,"stop.json"))!==void 0)return observe(saved);const original=await observe(saved);if(original["state"]!=="INTENT")return original;if(!await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:saved.boot.provisionRequestId}))return observe(saved);let spawned=false;try{const output=await fs3.open(path3.join(directory,"stdout.log"),"ax",384);try{const errors=await fs3.open(path3.join(directory,"stderr.log"),"ax",384);try{const env={};for(const key of["PATH","HOME","USER","LOGNAME","SHELL","LANG","LC_ALL","TMPDIR","TMP","TEMP","TZ"]){if(process.env[key]!==void 0)env[key]=process.env[key]}const child=spawn(process.execPath,[saved.workerEntry,"managed-runtime-bootstrap-worker",directory],{cwd:path3.dirname(saved.workerEntry),detached:true,stdio:["ignore",output.fd,errors.fd],env});await new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",reject)});spawned=true;child.unref();await writeSshPrivateJson(path3.join(directory,"pid.json"),{pid:child.pid})}finally{await errors.close()}}finally{await output.close()}}catch{if(!spawned){await writeSshPrivateJson(path3.join(directory,"launch-failed.json"),{provisionRequestId:saved.boot.provisionRequestId});return observe(saved)}}for(let attempt=0;attempt<100;attempt++){const observed=await observe(saved);if(observed["state"]!=="STARTING"&&!(observed["state"]==="BLOCKED"&&observed["pid"]===null))return observed;await new Promise(resolve=>setTimeout(resolve,50))}return observe(saved)}__name(ensure,"ensure");async function workspaceUpload(request,expected,verifyStorage,sessionScope){const{metadata,bytes}=workspaceUploadRequest(request["files"]);const root=absolute(request["root"]);const cwd=sessionScope?.cwdRelative??workspaceFilePath(request["cwdRelative"]);const target={nodeId:request["nodeId"],root,cwd,expected,identity:request["identity"]??null,marker:request["marker"]??null,...sessionScope?{sessionFileScope:sessionScope}:{},...metadata};const canonical=__name(value=>value&&typeof value==="object"&&!Array.isArray(value)?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,item])=>[key,canonical(item)])):value,"canonical");const requestDigest=createHash3("sha256").update(JSON.stringify(canonical(target))).digest("hex");const stateDirectory=absolute(request["stateDirectory"]);await privateDirectory(stateDirectory);const directory=path3.join(stateDirectory,"workspace-uploads",metadata.uploadId);await privateDirectory(directory);const claimPath=path3.join(directory,"claim.json");const receiptPath=path3.join(directory,"receipt.json");let claim=await optionalJson(claimPath);let started=false;if(claim===void 0){if(await optionalJson(receiptPath)!==void 0)refuse3("Workspace upload claim is unavailable.");const proposed={version:1,target,requestDigest,pid:bytes===void 0?null:process.pid};started=await createSshPrivateJson(claimPath,proposed);claim=started?proposed:await readSshPrivateJson(claimPath)}const saved=object(claim);exact(saved,["version","target","requestDigest","pid"]);if(saved["version"]!==1||saved["requestDigest"]!==requestDigest||!isDeepStrictEqual(saved["target"],target))throw new WorkspaceFileError("ssh_runtime_file_upload_conflict");const pid=saved["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Workspace upload process identity is invalid.");const receipt=await optionalJson(receiptPath);if(receipt!==void 0){const result2=object(receipt);if(!["completed","failed"].includes(String(result2["state"]))||result2["state"]==="failed"&&typeof result2["code"]!=="string"||!isDeepStrictEqual(receipt,workspaceUploadResult(metadata,result2["state"],result2["code"])))refuse3("Workspace upload receipt is invalid.");return receipt}let result;if(pid===null){result=workspaceUploadResult(metadata,"failed","ssh_runtime_file_upload_not_started")}else if(started&&bytes!==void 0){result=await writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope)}else{let live=true;try{live=alive(Number(pid))}catch{}if(live)return workspaceUploadResult(metadata,"pending");result=await inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope)}await writeSshPrivateJson(receiptPath,result);return result}__name(workspaceUpload,"workspaceUpload");async function executeSshBootstrap(value){const request=object(value);if(request["protocolVersion"]!==1||!ID.test(text(request["nodeId"])))refuse3("Runtime bootstrap protocol is invalid.");const nodeId=text(request["nodeId"]);const stateDirectory=absolute(request["stateDirectory"]);const operation=text(request["operation"]);if(operation==="probe"||operation==="ensure"){if(Number(process.versions.node.split(".")[0])<22){throw new SshBootstrapError("ssh_runtime_node_unsupported","Runtime requires Node.js 22 or later.")}}if(operation==="probe"){const root=absolute(request["root"]);const roots=request["allowedRoots"];if(!Array.isArray(roots)||roots.length===0||!roots.some(candidate=>within(absolute(candidate),root)))refuse3("Directory is outside the configured roots.");if(within(root,stateDirectory)||within(stateDirectory,root))refuse3("Runtime state and Workspace roots must not overlap.");if(request["files"]!==void 0){const fileOperation=object(request["files"])["operation"];const uploading=["upload","upload-status"].includes(String(fileOperation));const identity2=request["identity"]===void 0?void 0:identityDocument(request["identity"]);const marker=identity2?markerDocument(request["marker"],identity2):void 0;if(identity2&&identity2.root!==root)refuse3("Storage root conflicts.");if(identity2&&!uploading)await verifySshStorage(identity2,marker);const expected=identity2??object(request["localRootIdentity"]);try{if(request["sessionFileScope"]!==void 0&&identity2)refuse3("Session file scopes require local storage.");const sessionScope=sessionWorkspaceFileScope(request["sessionFileScope"],request["cwdRelative"]);const fileIdentity={device:text(expected.device),inode:text(expected.inode)};const files=uploading?await workspaceUpload(request,fileIdentity,async()=>{if(identity2)await verifySshStorage(identity2,marker)},sessionScope):await readWorkspaceFiles(root,text(request["cwdRelative"]),request["files"],fileIdentity,sessionScope);if(identity2&&!uploading)await verifySshStorage(identity2,marker);return{qwenVersion:await getCliVersion(),files}}catch(error){if(error instanceof WorkspaceFileError)throw new SshBootstrapError(error.code,error.message);throw error}}const identity=await inspectSshStorage(root);if(request["cwdRelative"]!==void 0){const relative=text(request["cwdRelative"]);const cwd=path3.resolve(root,relative);if(path3.isAbsolute(relative)||!within(root,cwd)||cwd!==await fs3.realpath(cwd)||!(await fs3.stat(cwd)).isDirectory())refuse3("Working directory is unavailable.");await fs3.access(cwd,constants3.R_OK|constants3.W_OK|constants3.X_OK)}return{platform:process.platform,nodeVersion:process.version,qwenVersion:await getCliVersion(),identity,marker:await optionalJson(path3.join(root,MARKER))??null}}if(operation==="register-storage"){const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity);await writeSshPrivateJson(path3.join(identity.root,MARKER),marker);await verifySshStorage(identity,marker);return{identity,marker}}await privateDirectory(stateDirectory);if(operation==="ensure")return ensure(request,nodeId,stateDirectory);const directory=resourceDirectory(stateDirectory,text(request["resourceId"]));const record=await readSshRuntimeRecord(directory);if(record.nodeId!==nodeId||record.stateDirectory!==stateDirectory)refuse3("Runtime node identity conflicts.");let observed=await observe(record);if(operation==="observe")return observed;if(operation!=="stop")refuse3("Runtime bootstrap operation is unsupported.");const retirementId=text(request["retirementId"]);if(!UUID.test(retirementId))refuse3("Runtime retirement identity is invalid.");if(observed["state"]==="INTENT"){await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:record.boot.provisionRequestId,retirementId});observed=await observe(record)}const claim=object(await readSshPrivateJson(path3.join(directory,"launch.claim")));if(claim["retirementId"]!==void 0&&claim["retirementId"]!==retirementId)refuse3("Runtime retirement identity conflicts.");if(observed["state"]==="RETIRED"){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});return observed}if(observed["state"]==="FAILED"||claim["retirementId"]===retirementId){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});await verifySshStorage(record.identity,record.marker);await writeSshPrivateJson(path3.join(directory,"clean.json"),sshCleanProof(record,retirementId,new Date().toISOString()));return observe(record)}if(observed["state"]==="STARTING"||observed["state"]==="BLOCKED"&&observed["pid"]===null)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime startup has not completed.",true);if(observed["state"]!=="READY")throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime is not reachable for clean retirement.");await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});const ready=observed["ready"];try{await attest(record,ready);const response=await fetch(`${ready.url}${SSH_RETIRE_PATH}`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify({protocolVersion:1,resourceId:record.resourceId,retirementId}),redirect:"error",signal:AbortSignal.timeout(15e3)});if(!response.ok)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement is not proven.",true);await response.arrayBuffer()}catch(error){if(error instanceof SshBootstrapError)throw error;if((await observe(record))["state"]!=="RETIRED")throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement response is unavailable.",true)}for(let attempt=0;attempt<100;attempt++){const result=await observe(record);if(result["state"]==="RETIRED")return result;await new Promise(resolve=>setTimeout(resolve,50))}throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime process has not exited.",true)}__name(executeSshBootstrap,"executeSshBootstrap");async function runManagedRuntimeBootstrap(help=false,workspaceFileUpload=false){if(help){process.stdout.write(`${JSON.stringify({protocolVersion:1,capabilities:{workspaceFiles:1,workspaceFileUpload:1}})}
3
+ import{createManagedContextAttestationResponse,isManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{getCliVersion}from"./chunk-6ZEMLEK2.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync,spawn}from"node:child_process";import{createHash as createHash3,createHmac,randomUUID}from"node:crypto";import{constants as constants3,promises as fs3}from"node:fs";import path3 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";import{constants,promises as fs}from"node:fs";import path from"node:path";var MAX_WORKSPACE_UPLOAD_BYTES=8*1024*1024;var WorkspaceFileError=class extends Error{constructor(code){super("Workspace file request is unavailable.");this.code=code}static{__name(this,"WorkspaceFileError")}};function refuse(code="unavailable"){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse,"refuse");function workspaceFilePath(value){if(value===".")return".";if(typeof value!=="string"||value.length>1024||/[\\\p{Cc}\p{Cs}]/u.test(value)||value.split("/").some(part=>!part||part==="."||part===".."||part===".git"||part===".qwen-child-workspaces"||part.startsWith(".qwen-managed-")))refuse("invalid_path");return value}__name(workspaceFilePath,"workspaceFilePath");function sessionWorkspaceFileScope(value,cwdRelative){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const scope=value;const keys=["sessionId","contextDigest","worktreeId","worktreeRevision","cwdRelative","worktreeRootIdentity"];if(Object.keys(scope).length!==keys.length||keys.some(key=>!(key in scope))||typeof scope["sessionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(scope["sessionId"])||typeof scope["contextDigest"]!=="string"||!/^sha256:[a-f0-9]{64}$/.test(scope["contextDigest"])||typeof scope["worktreeId"]!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(scope["worktreeId"])||!Number.isSafeInteger(scope["worktreeRevision"])||Number(scope["worktreeRevision"])<1||typeof cwdRelative!=="string"||scope["cwdRelative"]!==cwdRelative)refuse("invalid_request");const prefix=`.qwen-managed-worktrees/${scope["worktreeId"]}`;if(cwdRelative!==prefix&&!cwdRelative.startsWith(`${prefix}/`))refuse("invalid_path");workspaceFilePath(cwdRelative.slice(prefix.length+1)||".");const identity=scope["worktreeRootIdentity"];if(!identity||typeof identity!=="object"||Array.isArray(identity))refuse("invalid_request");const fields=identity;if(Object.keys(fields).length!==2||!["device","inode"].every(key=>typeof fields[key]==="string"&&/^\d+$/.test(fields[key])))refuse("invalid_request");return scope}__name(sessionWorkspaceFileScope,"sessionWorkspaceFileScope");function signature(stat){return[stat.dev,stat.ino,stat.birthtimeNs,stat.size,stat.mtimeNs,stat.ctimeNs].join(":")}__name(signature,"signature");async function workspaceFileDirectories(root,cwdRelative,expected,sessionScope){const scope=sessionWorkspaceFileScope(sessionScope,cwdRelative);const cwd=scope?.cwdRelative??workspaceFilePath(cwdRelative);const worktreeRoot=scope?path.join(root,".qwen-managed-worktrees",scope.worktreeId):void 0;const anchors=new Map;async function directory(relative){const segments=relative==="."?[]:relative.split("/");let current=root;for(const segment of["",...segments]){if(segment)current=path.join(current,segment);const stat=await fs.lstat(current,{bigint:true});if(!stat.isDirectory()||await fs.realpath(current)!==current)refuse();if(current===root&&(String(stat.dev)!==expected.device||String(stat.ino)!==expected.inode))refuse();if(scope&&current===worktreeRoot&&(String(stat.dev)!==scope.worktreeRootIdentity.device||String(stat.ino)!==scope.worktreeRootIdentity.inode))refuse("changed");const prior=anchors.get(current);const identity=[stat.dev,stat.ino,stat.birthtimeNs].join(":");if(prior&&prior!==identity)refuse("changed");anchors.set(current,identity)}return current}__name(directory,"directory");async function verify(){for(const[name,identity]of anchors){const stat=await fs.lstat(name,{bigint:true});if(!stat.isDirectory()||await fs.realpath(name)!==name||[stat.dev,stat.ino,stat.birthtimeNs].join(":")!==identity)refuse("changed")}}__name(verify,"verify");const base=await directory(cwd);const rooted=__name(relative=>cwd==="."?relative:relative==="."?cwd:`${cwd}/${relative}`,"rooted");return{base,directory:__name(relative=>directory(rooted(relative)),"directory"),verify}}__name(workspaceFileDirectories,"workspaceFileDirectories");async function readWorkspaceFiles(root,cwdRelative,value,expected,sessionScope){if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const request=value;if(request["protocolVersion"]!==1)refuse("unsupported");const{base,directory,verify}=await workspaceFileDirectories(root,cwdRelative,expected,sessionScope);if(request["operation"]==="read"){const relative2=workspaceFilePath(request["path"]);if(relative2===".")refuse("invalid_path");const parent=path.posix.dirname(relative2);await directory(parent);const filename=path.join(base,relative2);const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(!before.isFile()||before.size===0n||before.size>24n*1024n)refuse("unsupported_content");const bytes=Buffer.alloc(24*1024+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}if(BigInt(size)!==before.size||signature(before)!==signature(await handle.stat({bigint:true}))||signature(before)!==signature(await fs.lstat(filename,{bigint:true})))refuse("changed");let text2;try{text2=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(bytes.subarray(0,size))}catch{return refuse("unsupported_content")}if(!text2||text2.includes("\0"))refuse("unsupported_content");await verify();const result={protocolVersion:1,path:relative2,name:path.posix.basename(relative2),mimeType:"text/plain",text:text2,byteLength:size,sha256:createHash("sha256").update(bytes.subarray(0,size)).digest("hex")};if(Buffer.byteLength(JSON.stringify(result))>48*1024)refuse("too_large");return result}finally{await handle.close()}}if(request["operation"]!=="query")refuse("invalid_request");const relative=workspaceFilePath(request["directory"]??".");const query=request["query"]??"";if(typeof query!=="string"||query.length>256||/[\p{Cc}\p{Cs}]/u.test(query))refuse("invalid_request");const entries=[];let scanned=0;let truncated=false;const deadline=Date.now()+2e3;const queue=[{relative,depth:0}];while(queue.length){const next=queue.shift();const dir=await directory(next.relative);const stream=await fs.opendir(dir);for await(const entry of stream){if(++scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}const name=next.relative==="."?entry.name:`${next.relative}/${entry.name}`;try{workspaceFilePath(name)}catch{continue}if(!entry.isFile()&&!entry.isDirectory())continue;if(query&&entry.isDirectory()){if(next.depth<32)queue.push({relative:name,depth:next.depth+1});else truncated=true}if(query&&(entry.isDirectory()||!name.toLowerCase().includes(query.toLowerCase())))continue;const item={path:name,name:entry.name,kind:entry.isDirectory()?"directory":"file"};if(Buffer.byteLength(JSON.stringify([...entries,item]))>24*1024){truncated=true;break}entries.push(item)}if(scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}}await verify();return{protocolVersion:1,directory:relative,entries,truncated,maxUploadBytes:MAX_WORKSPACE_UPLOAD_BYTES}}__name(readWorkspaceFiles,"readWorkspaceFiles");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{constants as constants2,promises as fs2}from"node:fs";import path2 from"node:path";function refuse2(code){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse2,"refuse");function failed(metadata,error){return workspaceUploadResult(metadata,"failed",error instanceof WorkspaceFileError?error.code:error.code==="EEXIST"?"ssh_runtime_file_exists":"ssh_runtime_file_unavailable")}__name(failed,"failed");function workspaceUploadRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))refuse2("invalid_request");const request=value;if(request["protocolVersion"]!==1||!["upload","upload-status"].includes(String(request["operation"]))||typeof request["uploadId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(request["uploadId"])||!Number.isSafeInteger(request["sizeBytes"])||Number(request["sizeBytes"])<0||Number(request["sizeBytes"])>MAX_WORKSPACE_UPLOAD_BYTES||typeof request["sha256"]!=="string"||!/^[0-9a-f]{64}$/.test(request["sha256"]))refuse2("invalid_request");const relative=workspaceFilePath(request["path"]);if(relative===".")refuse2("invalid_path");const metadata={uploadId:request["uploadId"],path:relative,sizeBytes:Number(request["sizeBytes"]),sha256:request["sha256"]};if(request["operation"]==="upload-status"){if(request["data"]!==void 0)refuse2("invalid_request");return{metadata}}const data=request["data"];if(typeof data!=="string"||data.length!==Math.ceil(metadata.sizeBytes/3)*4)refuse2("invalid_content");const bytes=Buffer.from(data,"base64");if(bytes.length!==metadata.sizeBytes||bytes.toString("base64")!==data||createHash2("sha256").update(bytes).digest("hex")!==metadata.sha256)refuse2("invalid_content");return{metadata,bytes}}__name(workspaceUploadRequest,"workspaceUploadRequest");function workspaceUploadResult(metadata,state,code){return{protocolVersion:1,...metadata,state,...code===void 0?{}:{code}}}__name(workspaceUploadResult,"workspaceUploadResult");function temporaryPath(directory,metadata){return path2.join(directory,`.qwen-managed-upload-${metadata.uploadId}.tmp`)}__name(temporaryPath,"temporaryPath");async function removeTemporary(temporary){try{await fs2.unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}}__name(removeTemporary,"removeTemporary");async function syncDirectory(directory){const handle=await fs2.open(directory,"r");try{await handle.sync()}finally{await handle.close()}}__name(syncDirectory,"syncDirectory");async function writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope){let directories;let parent;try{await verifyStorage();directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);parent=await directories.directory(path2.posix.dirname(metadata.path))}catch(error){return failed(metadata,error)}const destination=path2.join(directories.base,metadata.path);const temporary=temporaryPath(parent,metadata);let ownsTemporary=false;let result;try{const handle=await fs2.open(temporary,"wx",384);ownsTemporary=true;try{await handle.writeFile(bytes);await handle.sync()}finally{await handle.close()}await directories.verify();await verifyStorage();await fs2.link(temporary,destination);await directories.verify();await verifyStorage();result=workspaceUploadResult(metadata,"completed")}catch(error){result=failed(metadata,error)}finally{if(ownsTemporary){await directories.verify();await removeTemporary(temporary);await syncDirectory(parent)}}return result}__name(writeWorkspaceUpload,"writeWorkspaceUpload");async function inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope){await verifyStorage();const directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);const parent=await directories.directory(path2.posix.dirname(metadata.path));const destination=path2.join(directories.base,metadata.path);let completed=false;try{const handle=await fs2.open(destination,constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(before.isFile()&&before.size===BigInt(metadata.sizeBytes)){const bytes=Buffer.alloc(metadata.sizeBytes+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}const after=await handle.stat({bigint:true});const current=await fs2.lstat(destination,{bigint:true});completed=size===metadata.sizeBytes&&before.dev===current.dev&&before.ino===current.ino&&before.mtimeNs===after.mtimeNs&&before.ctimeNs===after.ctimeNs&&before.size===after.size&&after.ctimeNs===current.ctimeNs&&createHash2("sha256").update(bytes.subarray(0,size)).digest("hex")===metadata.sha256}}finally{await handle.close()}}catch(error){if(!["ENOENT","ELOOP"].includes(error.code??""))throw error}await directories.verify();await verifyStorage();await removeTemporary(temporaryPath(parent,metadata));await syncDirectory(parent);return workspaceUploadResult(metadata,completed?"completed":"failed",completed?void 0:"ssh_runtime_file_upload_incomplete")}__name(inspectWorkspaceUpload,"inspectWorkspaceUpload");var MARKER=".qwen-managed-storage.json";var MAX_BYTES=64*1024;var MAX_UPLOAD_REQUEST_BYTES=12*1024*1024;var ID=/^[a-zA-Z0-9_.:-]{1,512}$/;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var hostId;var SSH_RETIRE_PATH="/internal/managed-runtime/v3/retire";var SshBootstrapError=class extends Error{constructor(code,message,retryable=false){super(message);this.code=code;this.retryable=retryable}static{__name(this,"SshBootstrapError")}};function refuse3(message){throw new SshBootstrapError("ssh_runtime_identity_conflict",message)}__name(refuse3,"refuse");function object(value){if(!value||typeof value!=="object"||Array.isArray(value))return refuse3("Runtime bootstrap document is invalid.");return value}__name(object,"object");function text(value){if(typeof value!=="string"||!value||value.includes("\0"))return refuse3("Runtime bootstrap text is invalid.");return value}__name(text,"text");function absolute(value){const directory=text(value);if(!path3.isAbsolute(directory)||path3.resolve(directory)!==directory)return refuse3("Runtime path must be absolute and normalized.");return directory}__name(absolute,"absolute");function within(root,candidate){const relative=path3.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path3.sep}`)&&!path3.isAbsolute(relative)}__name(within,"within");function exact(value,fields){if(Object.keys(value).length!==fields.length||fields.some(field=>!(field in value)))refuse3("Runtime bootstrap document has unexpected fields.")}__name(exact,"exact");async function readSshPrivateJson(file){const stat=await fs3.lstat(file);if(!stat.isFile()||stat.size>MAX_BYTES||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state file is not owner-private.");return JSON.parse(await fs3.readFile(file,"utf8"))}__name(readSshPrivateJson,"readSshPrivateJson");async function syncParentDirectory(file){const directory=await fs3.open(path3.dirname(file),"r");try{await directory.sync()}finally{await directory.close()}}__name(syncParentDirectory,"syncParentDirectory");async function writeSshPrivateJson(file,value){if(!await createSshPrivateJson(file,value)&&!isDeepStrictEqual(await readSshPrivateJson(file),value))refuse3("Runtime state conflicts with an earlier operation.")}__name(writeSshPrivateJson,"writeSshPrivateJson");async function createSshPrivateJson(file,value){const temporary=path3.join(path3.dirname(file),`.${path3.basename(file)}.${randomUUID()}.tmp`);const handle=await fs3.open(temporary,"wx",384);let created=true;try{try{await handle.writeFile(JSON.stringify(value),"utf8");await handle.sync()}finally{await handle.close()}try{await fs3.link(temporary,file)}catch(error){if(error.code!=="EEXIST")throw error;created=false}}finally{await fs3.unlink(temporary)}await syncParentDirectory(file);return created}__name(createSshPrivateJson,"createSshPrivateJson");async function privateDirectory(directory){const created=await fs3.mkdir(directory,{recursive:true,mode:448});const stat=await fs3.lstat(directory);if(!stat.isDirectory()||await fs3.realpath(directory)!==directory||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state directory must be canonical and owner-private.");for(let current=directory;;current=path3.dirname(current)){await syncParentDirectory(current);if(created===void 0||current===created)break}}__name(privateDirectory,"privateDirectory");function identityDocument(value){const identity=object(value);exact(identity,["root","hostId","device","inode","birthTime"]);absolute(identity["root"]);if(!/^[0-9a-f]{64}$/.test(text(identity["hostId"]))||!/^\d+$/.test(text(identity["device"]))||!/^\d+$/.test(text(identity["inode"]))||!Number.isFinite(Date.parse(text(identity["birthTime"]))))refuse3("Storage identity is invalid.");return identity}__name(identityDocument,"identityDocument");function markerDocument(value,identity){const marker=object(value);exact(marker,["version","tenantId","storageId","root","hostId","device","inode","birthTime","registrationId"]);if(marker["version"]!==2||!UUID.test(text(marker["registrationId"]))||!ID.test(text(marker["tenantId"]))||!ID.test(text(marker["storageId"]))||Object.entries(identity).some(([key,item])=>marker[key]!==item))refuse3("Storage marker does not bind the registered identity.");return marker}__name(markerDocument,"markerDocument");async function inspectSshStorage(root){if(!["linux","darwin"].includes(process.platform))throw new SshBootstrapError("ssh_runtime_platform_unsupported","Runtime requires Linux or macOS.");if(absolute(root)!==await fs3.realpath(root))refuse3("Storage root is not canonical.");const stat=await fs3.lstat(root,{bigint:true});if(!stat.isDirectory()||stat.birthtimeNs<=0n)refuse3("Storage directory has no independent birth identity.");await fs3.access(root,constants3.R_OK|constants3.W_OK|constants3.X_OK);const machine=hostId?void 0:process.platform==="linux"?(await fs3.readFile("/etc/machine-id","utf8")).trim():/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(execFileSync("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:MAX_BYTES}))?.[1];if(!hostId){if(!machine||machine.length>256)refuse3("Stable host identity is unavailable.");hostId=createHmac("sha256",machine).update("Qwen-Code/verified-workspace/v2").digest("hex")}const seconds=stat.birthtimeNs/1000000000n;const nanos=(stat.birthtimeNs%1000000000n).toString().padStart(9,"0");const fraction=nanos==="000000000"?"":`.${nanos.endsWith("000000")?nanos.slice(0,3):nanos.endsWith("000")?nanos.slice(0,6):nanos}`;return{root,hostId,device:BigInt.asUintN(64,stat.dev).toString(),inode:BigInt.asUintN(64,stat.ino).toString(),birthTime:new Date(Number(seconds)*1e3).toISOString().replace(/\.000Z$/,`${fraction}Z`)}}__name(inspectSshStorage,"inspectSshStorage");async function verifySshStorage(identity,marker){if(!isDeepStrictEqual(await inspectSshStorage(identity.root),identity))refuse3("Registered storage identity changed.");if(marker&&!isDeepStrictEqual(await readSshPrivateJson(path3.join(identity.root,MARKER)),marker))refuse3("Registered storage marker changed.")}__name(verifySshStorage,"verifySshStorage");function resourceDirectory(stateDirectory,resourceId){if(!UUID.test(resourceId))refuse3("Runtime resource identity is invalid.");return path3.join(stateDirectory,"resources",resourceId)}__name(resourceDirectory,"resourceDirectory");async function readSshRuntimeRecord(directory){const value=object(await readSshPrivateJson(path3.join(directory,"intent.json")));exact(value,["version","nodeId","stateDirectory","resourceId","bindingId","bindingGeneration","boot","identity","marker","workerEntry","expectedQwenVersion"]);const identity=identityDocument(value["identity"]);const boot=parseManagedContextBoot(value["boot"]);const marker=markerDocument(value["marker"],identity);if(value["version"]!==1||!ID.test(text(value["nodeId"]))||!ID.test(text(value["bindingId"]))||!Number.isSafeInteger(value["bindingGeneration"])||Number(value["bindingGeneration"])<=0||boot.isolationClass!=="session"||boot.mountRoot!==identity.root||boot.tenantId!==marker.tenantId||boot.storageId!==marker.storageId||resourceDirectory(absolute(value["stateDirectory"]),text(value["resourceId"]))!==directory)refuse3("Runtime intent identity is invalid.");absolute(value["workerEntry"]);text(value["expectedQwenVersion"]);return value}__name(readSshRuntimeRecord,"readSshRuntimeRecord");function sshCleanProof(record,retirementId,retiredAt){return{version:record.boot.managedExtensions?2:1,...record.boot.managedExtensions?{executionMode:record.boot.managedExtensions.mode,scope:record.boot.managedExtensions.mode==="linux-cgroup"?"process_tree":"process_group"}:{},resourceId:record.resourceId,bindingId:record.bindingId,bindingGeneration:record.bindingGeneration,provisionRequestId:record.boot.provisionRequestId,runtimeInstanceId:record.boot.runtimeInstanceId,runtimeIncarnation:record.boot.runtimeIncarnation,leaseId:record.boot.leaseId,epoch:record.boot.epoch,retirementId,retiredAt}}__name(sshCleanProof,"sshCleanProof");function alive(pid){try{process.kill(pid,0);return true}catch(error){if(error.code==="ESRCH")return false;throw new SshBootstrapError("ssh_runtime_stop_unverified","Original process liveness is unverified.")}}__name(alive,"alive");async function optionalJson(file){try{return await readSshPrivateJson(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(optionalJson,"optionalJson");async function observe(record){await verifySshStorage(record.identity,record.marker);const directory=resourceDirectory(record.stateDirectory,record.resourceId);const pidRecord=await optionalJson(path3.join(directory,"pid.json"));const pid=pidRecord===void 0?null:object(pidRecord)["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Runtime process record is invalid.");const result={resourceId:record.resourceId,state:"INTENT",pid,ready:null};const claim=await optionalJson(path3.join(directory,"launch.claim"));if(claim===void 0){for(const file of["pid.json","ready.json","clean.json","stdout.log","stderr.log","launch-failed.json"]){try{await fs3.lstat(path3.join(directory,file))}catch(error){if(error.code==="ENOENT")continue;throw error}refuse3("Runtime launch claim is missing from an existing resource.")}return result}const claimedRetirement=object(claim)["retirementId"];const neverStarted=typeof claimedRetirement==="string"&&UUID.test(claimedRetirement);if(!isDeepStrictEqual(claim,neverStarted?{provisionRequestId:record.boot.provisionRequestId,retirementId:claimedRetirement}:{provisionRequestId:record.boot.provisionRequestId}))refuse3("Runtime launch claim conflicts.");if(neverStarted&&pid!==null)refuse3("A retired launch claim cannot own a worker process.");const failed2=await optionalJson(path3.join(directory,"launch-failed.json"));if(failed2!==void 0&&(!isDeepStrictEqual(failed2,{provisionRequestId:record.boot.provisionRequestId})||pid!==null||await optionalJson(path3.join(directory,"ready.json"))!==void 0))refuse3("Runtime failed-launch evidence conflicts.");const clean=await optionalJson(path3.join(directory,"clean.json"));if(clean!==void 0){const proof=object(clean);const retiredAt=text(proof["retiredAt"]);const stop=object(await readSshPrivateJson(path3.join(directory,"stop.json")));if(!Number.isFinite(Date.parse(retiredAt))||!isDeepStrictEqual(clean,sshCleanProof(record,text(stop["retirementId"]),retiredAt)))refuse3("Runtime clean proof conflicts.");if((neverStarted||failed2!==void 0)&&pid===null&&(failed2!==void 0||claimedRetirement===stop["retirementId"])||pid!==null&&!alive(Number(pid)))return{...result,state:"RETIRED",cleanProof:clean};return{...result,state:"BLOCKED"}}if(failed2!==void 0)return{...result,state:"FAILED"};if(neverStarted&&pid===null)return result;if(pid===null||!alive(Number(pid)))return{...result,state:"BLOCKED"};const ready=await optionalJson(path3.join(directory,"ready.json"));if(ready===void 0)return{...result,state:"STARTING"};const value=object(ready);if(!isManagedContextReady(value,record.boot))refuse3("Runtime ready identity conflicts.");return{...result,state:"READY",ready:value}}__name(observe,"observe");async function attest(record,ready){const expected=createManagedContextAttestationResponse(record.boot);const{runtimeInstanceId:_runtime,runtimeIncarnation:_incarnation,leaseId:_lease,epoch:_epoch,...request}=expected;const response=await fetch(`${ready.url}/internal/managed-runtime/v3/attest`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify(request),redirect:"error",signal:AbortSignal.timeout(5e3)});if(!response.ok||!isDeepStrictEqual(await response.json(),expected))refuse3("Original Runtime attestation failed.")}__name(attest,"attest");function sshRuntimeHeaders(boot){return{Authorization:`Bearer ${boot.token}`,"Cache-Control":"no-store","Content-Type":"application/json","X-Qwen-Managed-Lease-Id":boot.leaseId,"X-Qwen-Managed-Lease-Epoch":String(boot.epoch)}}__name(sshRuntimeHeaders,"sshRuntimeHeaders");async function ensure(request,nodeId,stateDirectory){const resourceId=text(request["resourceId"]);const expectedQwenVersion=text(request["expectedQwenVersion"]);if(expectedQwenVersion!==await getCliVersion()){throw new SshBootstrapError("ssh_runtime_version_conflict","Pinned Qwen version does not match this installation.")}const directory=resourceDirectory(stateDirectory,resourceId);const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity,marker);await privateDirectory(directory);const record={version:1,nodeId,stateDirectory,resourceId,bindingId:request["bindingId"],bindingGeneration:request["bindingGeneration"],boot:request["boot"],identity,marker,workerEntry:absolute(request["workerEntry"]),expectedQwenVersion};await writeSshPrivateJson(path3.join(directory,"intent.json"),record);const saved=await readSshRuntimeRecord(directory);if(typeof request["launch"]!=="boolean")refuse3("Runtime launch phase is required.");if(!request["launch"])return observe(saved);if(await optionalJson(path3.join(directory,"stop.json"))!==void 0)return observe(saved);const original=await observe(saved);if(original["state"]!=="INTENT")return original;if(!await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:saved.boot.provisionRequestId}))return observe(saved);let spawned=false;try{const output=await fs3.open(path3.join(directory,"stdout.log"),"ax",384);try{const errors=await fs3.open(path3.join(directory,"stderr.log"),"ax",384);try{const env={};for(const key of["PATH","HOME","USER","LOGNAME","SHELL","LANG","LC_ALL","TMPDIR","TMP","TEMP","TZ"]){if(process.env[key]!==void 0)env[key]=process.env[key]}const child=spawn(process.execPath,[saved.workerEntry,"managed-runtime-bootstrap-worker",directory],{cwd:path3.dirname(saved.workerEntry),detached:true,stdio:["ignore",output.fd,errors.fd],env});await new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",reject)});spawned=true;child.unref();await writeSshPrivateJson(path3.join(directory,"pid.json"),{pid:child.pid})}finally{await errors.close()}}finally{await output.close()}}catch{if(!spawned){await writeSshPrivateJson(path3.join(directory,"launch-failed.json"),{provisionRequestId:saved.boot.provisionRequestId});return observe(saved)}}for(let attempt=0;attempt<100;attempt++){const observed=await observe(saved);if(observed["state"]!=="STARTING"&&!(observed["state"]==="BLOCKED"&&observed["pid"]===null))return observed;await new Promise(resolve=>setTimeout(resolve,50))}return observe(saved)}__name(ensure,"ensure");async function workspaceUpload(request,expected,verifyStorage,sessionScope){const{metadata,bytes}=workspaceUploadRequest(request["files"]);const root=absolute(request["root"]);const cwd=sessionScope?.cwdRelative??workspaceFilePath(request["cwdRelative"]);const target={nodeId:request["nodeId"],root,cwd,expected,identity:request["identity"]??null,marker:request["marker"]??null,...sessionScope?{sessionFileScope:sessionScope}:{},...metadata};const canonical=__name(value=>value&&typeof value==="object"&&!Array.isArray(value)?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,item])=>[key,canonical(item)])):value,"canonical");const requestDigest=createHash3("sha256").update(JSON.stringify(canonical(target))).digest("hex");const stateDirectory=absolute(request["stateDirectory"]);await privateDirectory(stateDirectory);const directory=path3.join(stateDirectory,"workspace-uploads",metadata.uploadId);await privateDirectory(directory);const claimPath=path3.join(directory,"claim.json");const receiptPath=path3.join(directory,"receipt.json");let claim=await optionalJson(claimPath);let started=false;if(claim===void 0){if(await optionalJson(receiptPath)!==void 0)refuse3("Workspace upload claim is unavailable.");const proposed={version:1,target,requestDigest,pid:bytes===void 0?null:process.pid};started=await createSshPrivateJson(claimPath,proposed);claim=started?proposed:await readSshPrivateJson(claimPath)}const saved=object(claim);exact(saved,["version","target","requestDigest","pid"]);if(saved["version"]!==1||saved["requestDigest"]!==requestDigest||!isDeepStrictEqual(saved["target"],target))throw new WorkspaceFileError("ssh_runtime_file_upload_conflict");const pid=saved["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Workspace upload process identity is invalid.");const receipt=await optionalJson(receiptPath);if(receipt!==void 0){const result2=object(receipt);if(!["completed","failed"].includes(String(result2["state"]))||result2["state"]==="failed"&&typeof result2["code"]!=="string"||!isDeepStrictEqual(receipt,workspaceUploadResult(metadata,result2["state"],result2["code"])))refuse3("Workspace upload receipt is invalid.");return receipt}let result;if(pid===null){result=workspaceUploadResult(metadata,"failed","ssh_runtime_file_upload_not_started")}else if(started&&bytes!==void 0){result=await writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope)}else{let live=true;try{live=alive(Number(pid))}catch{}if(live)return workspaceUploadResult(metadata,"pending");result=await inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope)}await writeSshPrivateJson(receiptPath,result);return result}__name(workspaceUpload,"workspaceUpload");async function executeSshBootstrap(value){const request=object(value);if(request["protocolVersion"]!==1||!ID.test(text(request["nodeId"])))refuse3("Runtime bootstrap protocol is invalid.");const nodeId=text(request["nodeId"]);const stateDirectory=absolute(request["stateDirectory"]);const operation=text(request["operation"]);if(operation==="probe"||operation==="ensure"){if(Number(process.versions.node.split(".")[0])<22){throw new SshBootstrapError("ssh_runtime_node_unsupported","Runtime requires Node.js 22 or later.")}}if(operation==="probe"){const root=absolute(request["root"]);const roots=request["allowedRoots"];if(!Array.isArray(roots)||roots.length===0||!roots.some(candidate=>within(absolute(candidate),root)))refuse3("Directory is outside the configured roots.");if(within(root,stateDirectory)||within(stateDirectory,root))refuse3("Runtime state and Workspace roots must not overlap.");if(request["files"]!==void 0){const fileOperation=object(request["files"])["operation"];const uploading=["upload","upload-status"].includes(String(fileOperation));const identity2=request["identity"]===void 0?void 0:identityDocument(request["identity"]);const marker=identity2?markerDocument(request["marker"],identity2):void 0;if(identity2&&identity2.root!==root)refuse3("Storage root conflicts.");if(identity2&&!uploading)await verifySshStorage(identity2,marker);const expected=identity2??object(request["localRootIdentity"]);try{if(request["sessionFileScope"]!==void 0&&identity2)refuse3("Session file scopes require local storage.");const sessionScope=sessionWorkspaceFileScope(request["sessionFileScope"],request["cwdRelative"]);const fileIdentity={device:text(expected.device),inode:text(expected.inode)};const files=uploading?await workspaceUpload(request,fileIdentity,async()=>{if(identity2)await verifySshStorage(identity2,marker)},sessionScope):await readWorkspaceFiles(root,text(request["cwdRelative"]),request["files"],fileIdentity,sessionScope);if(identity2&&!uploading)await verifySshStorage(identity2,marker);return{qwenVersion:await getCliVersion(),files}}catch(error){if(error instanceof WorkspaceFileError)throw new SshBootstrapError(error.code,error.message);throw error}}const identity=await inspectSshStorage(root);if(request["cwdRelative"]!==void 0){const relative=text(request["cwdRelative"]);const cwd=path3.resolve(root,relative);if(path3.isAbsolute(relative)||!within(root,cwd)||cwd!==await fs3.realpath(cwd)||!(await fs3.stat(cwd)).isDirectory())refuse3("Working directory is unavailable.");await fs3.access(cwd,constants3.R_OK|constants3.W_OK|constants3.X_OK)}return{platform:process.platform,nodeVersion:process.version,qwenVersion:await getCliVersion(),identity,marker:await optionalJson(path3.join(root,MARKER))??null}}if(operation==="register-storage"){const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity);await writeSshPrivateJson(path3.join(identity.root,MARKER),marker);await verifySshStorage(identity,marker);return{identity,marker}}await privateDirectory(stateDirectory);if(operation==="ensure")return ensure(request,nodeId,stateDirectory);const directory=resourceDirectory(stateDirectory,text(request["resourceId"]));const record=await readSshRuntimeRecord(directory);if(record.nodeId!==nodeId||record.stateDirectory!==stateDirectory)refuse3("Runtime node identity conflicts.");let observed=await observe(record);if(operation==="observe")return observed;if(operation!=="stop")refuse3("Runtime bootstrap operation is unsupported.");const retirementId=text(request["retirementId"]);if(!UUID.test(retirementId))refuse3("Runtime retirement identity is invalid.");if(observed["state"]==="INTENT"){await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:record.boot.provisionRequestId,retirementId});observed=await observe(record)}const claim=object(await readSshPrivateJson(path3.join(directory,"launch.claim")));if(claim["retirementId"]!==void 0&&claim["retirementId"]!==retirementId)refuse3("Runtime retirement identity conflicts.");if(observed["state"]==="RETIRED"){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});return observed}if(observed["state"]==="FAILED"||claim["retirementId"]===retirementId){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});await verifySshStorage(record.identity,record.marker);await writeSshPrivateJson(path3.join(directory,"clean.json"),sshCleanProof(record,retirementId,new Date().toISOString()));return observe(record)}if(observed["state"]==="STARTING"||observed["state"]==="BLOCKED"&&observed["pid"]===null)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime startup has not completed.",true);if(observed["state"]!=="READY")throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime is not reachable for clean retirement.");await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});const ready=observed["ready"];try{await attest(record,ready);const response=await fetch(`${ready.url}${SSH_RETIRE_PATH}`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify({protocolVersion:1,resourceId:record.resourceId,retirementId}),redirect:"error",signal:AbortSignal.timeout(15e3)});if(!response.ok)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement is not proven.",true);await response.arrayBuffer()}catch(error){if(error instanceof SshBootstrapError)throw error;if((await observe(record))["state"]!=="RETIRED")throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement response is unavailable.",true)}for(let attempt=0;attempt<100;attempt++){const result=await observe(record);if(result["state"]==="RETIRED")return result;await new Promise(resolve=>setTimeout(resolve,50))}throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime process has not exited.",true)}__name(executeSshBootstrap,"executeSshBootstrap");async function runManagedRuntimeBootstrap(help=false,workspaceFileUpload=false){if(help){process.stdout.write(`${JSON.stringify({protocolVersion:1,capabilities:{workspaceFiles:1,workspaceFileUpload:1}})}
4
4
  `);return}let response;try{const chunks=[];let size=0;for await(const chunk of process.stdin){const bytes=Buffer.from(chunk);size+=bytes.length;if(size>(workspaceFileUpload?MAX_UPLOAD_REQUEST_BYTES:MAX_BYTES))refuse3("Runtime bootstrap request exceeds its limit.");chunks.push(bytes)}const source=new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks));const request=object(JSON.parse(source));const files=request["files"];const upload=files&&typeof files==="object"&&!Array.isArray(files)?["upload","upload-status"].includes(String(files["operation"])):false;if(workspaceFileUpload!==upload||upload&&request["operation"]!=="probe")refuse3("Workspace upload requires its dedicated bootstrap entry.");response={protocolVersion:1,ok:true,result:await executeSshBootstrap(request)}}catch(error){const known=error instanceof SshBootstrapError?error:new SshBootstrapError("ssh_runtime_state_unavailable","Runtime bootstrap state is unavailable.");response={protocolVersion:1,ok:false,error:{code:known.code,message:known.message,retryable:known.retryable}}}process.stdout.write(`${JSON.stringify(response)}
5
5
  `)}__name(runManagedRuntimeBootstrap,"runManagedRuntimeBootstrap");function sshResourcePath(record){return resourceDirectory(record.stateDirectory,record.resourceId)}__name(sshResourcePath,"sshResourcePath");export{SSH_RETIRE_PATH,SshBootstrapError,readSshPrivateJson,writeSshPrivateJson,inspectSshStorage,verifySshStorage,readSshRuntimeRecord,sshCleanProof,sshRuntimeHeaders,executeSshBootstrap,runManagedRuntimeBootstrap,sshResourcePath};
6
6
  /**