@qwen-code/qwen-code 0.25.4-preview.0 → 0.25.4-preview.1

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 (306) hide show
  1. package/bundled/browser-use/runtime/native-host.js +0 -0
  2. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_linux.sh +0 -0
  3. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_mac.sh +0 -0
  4. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_linux.sh +0 -0
  5. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_mac.sh +0 -0
  6. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_linux.sh +0 -0
  7. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_mac.sh +0 -0
  8. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_linux.sh +0 -0
  9. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_mac.sh +0 -0
  10. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_linux.sh +0 -0
  11. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_mac.sh +0 -0
  12. package/bundled/browser-use/runtime/node_modules/playwright-core/cli.js +0 -0
  13. package/bundled/browser-use/runtime/node_modules/playwright-core/lib/webp_codec.wasm +0 -0
  14. package/bundled/browser-use/runtime/node_modules/playwright-core/lib/xdg-open +0 -0
  15. package/bundled/browser-use/runtime/scripts/native-host-setup.js +0 -0
  16. package/chunks/{MaxSizedBox-M27H235V.js → MaxSizedBox-E4RKSA7W.js} +1 -1
  17. package/chunks/{StandaloneSessionPicker-LWWDDYOW.js → StandaloneSessionPicker-2D3UKLVS.js} +1 -1
  18. package/chunks/{acp-subagent-executor-NUV52JVS.js → acp-subagent-executor-UQYUN6AB.js} +1 -1
  19. package/chunks/{acpAgent-IUJDXLZM.js → acpAgent-P7WGK2BP.js} +3 -3
  20. package/chunks/{advisor-MSOUBMJ6.js → advisor-GCH2MBXT.js} +1 -1
  21. package/chunks/{agent-H7XIWYWQ.js → agent-57T4YAYP.js} +1 -1
  22. package/chunks/{agent-headless-XDN3D3S3.js → agent-headless-IBON3A7N.js} +1 -1
  23. package/chunks/{agent-host-client-AZP3PZXS.js → agent-host-client-LE7P72FR.js} +1 -1
  24. package/chunks/{agent-host-connections-JRVX7I6I.js → agent-host-connections-4DM57L26.js} +1 -1
  25. package/chunks/{anthropicContentGenerator-N7TV53LD.js → anthropicContentGenerator-C4TPFXUK.js} +1 -1
  26. package/chunks/{batch-MKSJFJUH.js → batch-YJJGMJWO.js} +1 -1
  27. package/chunks/{bridge-GNMKKHQ4.js → bridge-FIO2ENBG.js} +1 -1
  28. package/chunks/{channel-settings-store-Y4YCS7JX.js → channel-settings-store-TEBCLK2B.js} +1 -1
  29. package/chunks/{chunk-GPOUP5OK.js → chunk-27MTSS3T.js} +1 -1
  30. package/chunks/{chunk-C4ANA47H.js → chunk-2MGCRPM3.js} +1 -1
  31. package/chunks/{chunk-6DQNNRRC.js → chunk-2WBKWPSO.js} +1 -1
  32. package/chunks/{chunk-CATL2PQS.js → chunk-34WLYVDK.js} +5 -5
  33. package/chunks/{chunk-B7CXPNCV.js → chunk-3J2YNEHG.js} +1 -1
  34. package/chunks/{chunk-VTNHPXNL.js → chunk-3TBFTELA.js} +1 -1
  35. package/chunks/{chunk-7JT34VGK.js → chunk-46I6JBVL.js} +1 -1
  36. package/chunks/{chunk-FEMWELCV.js → chunk-4ZKFLOEH.js} +1 -1
  37. package/chunks/{chunk-7AYXAVTZ.js → chunk-5DUJIOOX.js} +3 -3
  38. package/chunks/{chunk-6QLHJSVW.js → chunk-6PWOLWTH.js} +1 -1
  39. package/chunks/{chunk-OW4QBRSR.js → chunk-6UZ65Z2P.js} +1 -1
  40. package/chunks/{chunk-V2JZO5MS.js → chunk-7DSJE3CL.js} +1 -1
  41. package/chunks/{chunk-TJMHIEYI.js → chunk-7LCY7GGX.js} +1 -1
  42. package/chunks/{chunk-TLJHBK3A.js → chunk-7RNTXEWH.js} +1 -1
  43. package/chunks/{chunk-YZ7OO4AQ.js → chunk-A3IF6IOB.js} +1 -1
  44. package/chunks/{chunk-VTF6AVZB.js → chunk-A6OQSOUO.js} +1 -1
  45. package/chunks/{chunk-Y7YDHCON.js → chunk-AJ6JUUP7.js} +1 -1
  46. package/chunks/{chunk-QTMHQGWQ.js → chunk-AOMEBVFW.js} +1 -1
  47. package/chunks/{chunk-KVTG2ZNH.js → chunk-AUNAS7AS.js} +1 -1
  48. package/chunks/{chunk-BOFD4CN3.js → chunk-AVIDPC5K.js} +1 -1
  49. package/chunks/{chunk-ETYTRKB2.js → chunk-BOLPBPWC.js} +1 -1
  50. package/chunks/{chunk-OAPA66DR.js → chunk-BQQBFDBY.js} +1 -1
  51. package/chunks/{chunk-NOS2CNOI.js → chunk-CN22ATWU.js} +1 -1
  52. package/chunks/{chunk-XYBEQRSZ.js → chunk-DIHJELGW.js} +1 -1
  53. package/chunks/{chunk-XCEL3EDX.js → chunk-DJFCI7TU.js} +1 -1
  54. package/chunks/{chunk-VKEL2XTM.js → chunk-DQPDMFS3.js} +1 -1
  55. package/chunks/{chunk-DJRFEZBY.js → chunk-DSYKB77N.js} +1 -1
  56. package/chunks/{chunk-UEW7Q26E.js → chunk-EDNOGHMN.js} +2 -2
  57. package/chunks/{chunk-RXNGYG64.js → chunk-EE36D2EV.js} +1 -1
  58. package/chunks/{chunk-NZKX7HYL.js → chunk-EGQDN3FJ.js} +1 -1
  59. package/chunks/{chunk-DFRSQK5Q.js → chunk-FHFBCG6N.js} +1 -1
  60. package/chunks/{chunk-PECV2VVZ.js → chunk-GI6T3RBV.js} +1 -1
  61. package/chunks/{chunk-37BNHIUB.js → chunk-GOLT5JXA.js} +1 -1
  62. package/chunks/{chunk-KITFF4GL.js → chunk-IDGXHMNL.js} +1 -1
  63. package/chunks/{chunk-6HIOSLUM.js → chunk-IIZWK7ZP.js} +1 -1
  64. package/chunks/{chunk-MPGEAX4K.js → chunk-IJC6ZH2S.js} +1 -1
  65. package/chunks/{chunk-TLYJVB5H.js → chunk-IO6LSEPV.js} +1 -1
  66. package/chunks/{chunk-QIJKEZZR.js → chunk-IYVNCBMS.js} +1 -1
  67. package/chunks/{chunk-S4GOHFRN.js → chunk-JHGOWK7M.js} +1 -1
  68. package/chunks/{chunk-GHRD2MMC.js → chunk-JRJY343T.js} +1 -1
  69. package/chunks/{chunk-WCYZSCG7.js → chunk-JVUXQU3W.js} +1 -1
  70. package/chunks/{chunk-DMCTJUIJ.js → chunk-K2K2YYWO.js} +1 -1
  71. package/chunks/{chunk-37OHWQHB.js → chunk-KF6HU732.js} +2 -2
  72. package/chunks/{chunk-5LSV73BG.js → chunk-KVWUOBH7.js} +1 -1
  73. package/chunks/{chunk-7V4BAHFT.js → chunk-LBWBGFHD.js} +1 -1
  74. package/chunks/{chunk-RKPHDO42.js → chunk-LDXZT3SG.js} +5 -5
  75. package/chunks/{chunk-BGFA2SAQ.js → chunk-LFOZ6AIH.js} +1 -1
  76. package/chunks/{chunk-4322TZID.js → chunk-LGQHT42X.js} +2 -2
  77. package/chunks/{chunk-PDXZ2CUO.js → chunk-M3O2XDHA.js} +1 -1
  78. package/chunks/{chunk-47K2NMP6.js → chunk-M3UC46LS.js} +1 -1
  79. package/chunks/{chunk-UFRY7WND.js → chunk-M7JLPTQI.js} +1 -1
  80. package/chunks/{chunk-SATEKHQP.js → chunk-MBUXP3IS.js} +1 -1
  81. package/chunks/{chunk-RN6JS263.js → chunk-MEZA3VVH.js} +1 -1
  82. package/chunks/{chunk-OBFKP7RI.js → chunk-MWN6TR36.js} +1 -1
  83. package/chunks/{chunk-VHJ43ZYJ.js → chunk-O7XRQWCG.js} +1 -1
  84. package/chunks/{chunk-H224LNV3.js → chunk-OYFRLT5E.js} +1 -1
  85. package/chunks/{chunk-3NWFV2YF.js → chunk-PMBGV76N.js} +1 -1
  86. package/chunks/{chunk-YFAPACDE.js → chunk-PVM4IVFL.js} +6 -6
  87. package/chunks/{chunk-7WS2EYMQ.js → chunk-PWHD4NK3.js} +1 -1
  88. package/chunks/{chunk-JZIQSEFO.js → chunk-Q54NROBX.js} +1 -1
  89. package/chunks/{chunk-FCLAPJ22.js → chunk-QE7R4DPT.js} +1 -1
  90. package/chunks/{chunk-J6TW7GNF.js → chunk-QIUTQICH.js} +1 -1
  91. package/chunks/{chunk-TWDCN5H2.js → chunk-QK63EULE.js} +1 -1
  92. package/chunks/{chunk-HZZT75LI.js → chunk-QTAC4W7J.js} +1 -1
  93. package/chunks/{chunk-P7DIAJNX.js → chunk-R7HBR4QQ.js} +1 -1
  94. package/chunks/{chunk-U2FJSKS3.js → chunk-RHEMFKMX.js} +1 -1
  95. package/chunks/{chunk-TRRY3QMM.js → chunk-RL57IU47.js} +1 -1
  96. package/chunks/{chunk-SPWDYRDH.js → chunk-S2OOQRLJ.js} +1 -1
  97. package/chunks/{chunk-QBRADQ7L.js → chunk-SWTMWNTZ.js} +1 -1
  98. package/chunks/{chunk-AZUDF52L.js → chunk-SXTKQHFZ.js} +1 -1
  99. package/chunks/{chunk-5RQRSPPD.js → chunk-T5S3MJIK.js} +1 -1
  100. package/chunks/{chunk-I3ORWQ2U.js → chunk-UDGDEIBB.js} +1 -1
  101. package/chunks/{chunk-EMDEBV33.js → chunk-UIFBF3E7.js} +1 -1
  102. package/chunks/{chunk-BGEMWNES.js → chunk-UQDPWI7D.js} +1 -1
  103. package/chunks/{chunk-I5LKOTZT.js → chunk-VON4MVIM.js} +1 -1
  104. package/chunks/{chunk-HJPO6MEW.js → chunk-W5D2T2JK.js} +1 -1
  105. package/chunks/{chunk-F6YYDRMH.js → chunk-WNGYYU67.js} +1 -1
  106. package/chunks/{chunk-S2GKUZZZ.js → chunk-WO3F62ZD.js} +1 -1
  107. package/chunks/{chunk-K7KW3ZJQ.js → chunk-WVY5Q6YY.js} +1 -1
  108. package/chunks/{chunk-GH6DPLWU.js → chunk-Y4Q667BW.js} +1 -1
  109. package/chunks/{chunk-FH74N7Y7.js → chunk-YJLMFUCS.js} +2 -2
  110. package/chunks/{chunk-C3Y2S5AM.js → chunk-YKHRCSKP.js} +1 -1
  111. package/chunks/{chunk-P4UJ7CXJ.js → chunk-YLIS36QA.js} +1 -1
  112. package/chunks/{chunk-4QIFOIBS.js → chunk-YVZ4XZRB.js} +1 -1
  113. package/chunks/{chunk-KGRD6G5J.js → chunk-Z27JJPKN.js} +1 -1
  114. package/chunks/{chunk-KOHHDB2L.js → chunk-ZCIS6MJZ.js} +1 -1
  115. package/chunks/{chunk-QNNDZYVW.js → chunk-ZHLQ222N.js} +1 -1
  116. package/chunks/{chunk-KWRZ3WJO.js → chunk-ZP7MTWMR.js} +1 -1
  117. package/chunks/{codex-subagent-executor-H44VDB5E.js → codex-subagent-executor-6OJVGF2S.js} +1 -1
  118. package/chunks/{config-utils-4X4SV4RL.js → config-utils-FI3A4QAN.js} +1 -1
  119. package/chunks/{contextCommand-4KVOHTAJ.js → contextCommand-YEBZQHG4.js} +1 -1
  120. package/chunks/{core-runtime-4RARI4NX.js → core-runtime-CFMHUAS7.js} +1 -1
  121. package/chunks/{create-sub-session-CNSRJFYG.js → create-sub-session-G26337FT.js} +1 -1
  122. package/chunks/{daemon-git-worktree-guard-6XQQPP2H.js → daemon-git-worktree-guard-ITU6NQIV.js} +1 -1
  123. package/chunks/{daemon-status-provider-PRTEQT5T.js → daemon-status-provider-CSWRGMRX.js} +1 -1
  124. package/chunks/{daemon-trust-policy-GXKJVZDU.js → daemon-trust-policy-IYD7NOGK.js} +1 -1
  125. package/chunks/{daemon-trust-policy-monitor-L2ORKHMM.js → daemon-trust-policy-monitor-OWUP5SYB.js} +1 -1
  126. package/chunks/{deferred-core-runtime-RZQFUSPX.js → deferred-core-runtime-CVCQU7O4.js} +1 -1
  127. package/chunks/{edit-W44XQCIS.js → edit-7YBQLILC.js} +1 -1
  128. package/chunks/{enterPlanMode-B456A2XO.js → enterPlanMode-L3PVSD2P.js} +1 -1
  129. package/chunks/{environment-DSGQSQFS.js → environment-BVEOYQHO.js} +1 -1
  130. package/chunks/{errors-KL725247.js → errors-VQWBGR6D.js} +1 -1
  131. package/chunks/{execution-tool-KT3EBWHG.js → execution-tool-P7CBXSGZ.js} +1 -1
  132. package/chunks/{execution-worker-LPQ4HMN4.js → execution-worker-RZXNYK4B.js} +1 -1
  133. package/chunks/{exitPlanMode-JLKS76IA.js → exitPlanMode-MBUTM3NW.js} +1 -1
  134. package/chunks/{fast-path-5UD52IHH.js → fast-path-T2FDUSHV.js} +1 -1
  135. package/chunks/{glob-LYA2H6X3.js → glob-RH7XXSYE.js} +1 -1
  136. package/chunks/{goal-tools-SHSIDLZX.js → goal-tools-K6XBCE5E.js} +1 -1
  137. package/chunks/{handleAutoUpdate-T4RE6CZN.js → handleAutoUpdate-PG7R3KPH.js} +1 -1
  138. package/chunks/{i18n-5DK327WA.js → i18n-EGTBMA3N.js} +1 -1
  139. package/chunks/{initializer-TJGE4OJA.js → initializer-RIKH4PCP.js} +1 -1
  140. package/chunks/{installationInfo-MZ62GDIC.js → installationInfo-BBADHZLD.js} +1 -1
  141. package/chunks/{interactive-mod-session-YCUBQ6RM.js → interactive-mod-session-7RDKAHZ4.js} +1 -1
  142. package/chunks/{list-4L3LYDQM.js → list-YEGWEHJX.js} +1 -1
  143. package/chunks/{llm-3JQWBZXV.js → llm-D3LHPY27.js} +4 -4
  144. package/chunks/{llm-content-generator-6UPJWPOM.js → llm-content-generator-BLTBMV66.js} +1 -1
  145. package/chunks/{loadedSettingsAdapter-STPKAFJG.js → loadedSettingsAdapter-PLGMKMFO.js} +1 -1
  146. package/chunks/{local-execution-environment-IE5BOI7Y.js → local-execution-environment-4LDKFNC4.js} +1 -1
  147. package/chunks/{loggingContentGenerator-4KKWPZJA.js → loggingContentGenerator-376R7DRI.js} +1 -1
  148. package/chunks/{manage-memory-CRV5SXZZ.js → manage-memory-2ZTIVKNU.js} +1 -1
  149. package/chunks/{managed-execution-engine-FHLEWVND.js → managed-execution-engine-5LOM3MXG.js} +1 -1
  150. package/chunks/{managed-npm-update-BRHPOKDU.js → managed-npm-update-2C5JYEXW.js} +1 -1
  151. package/chunks/{managed-runtime-attestation-worker-GIQKZ5BH.js → managed-runtime-attestation-worker-R2FECMZK.js} +1 -1
  152. package/chunks/{managed-runtime-bootstrap-P72BT46H.js → managed-runtime-bootstrap-KPLGH4UE.js} +1 -1
  153. package/chunks/{managed-runtime-session-worker-IYCJDB5K.js → managed-runtime-session-worker-EVKNPK3V.js} +1 -1
  154. package/chunks/{managed-runtime-ssh-worker-ONT4V5ZG.js → managed-runtime-ssh-worker-IA4HZ3PD.js} +1 -1
  155. package/chunks/{mcp-NXCQVE2Y.js → mcp-S67IJLI6.js} +1 -1
  156. package/chunks/{model-call-collection-3DNL45M5.js → model-call-collection-6OGPDTPG.js} +1 -1
  157. package/chunks/{model-configuration-6HRNYBWV.js → model-configuration-6RWVBOQS.js} +1 -1
  158. package/chunks/{modelConfigUtils-SKBN64ZW.js → modelConfigUtils-M3TVVYAO.js} +1 -1
  159. package/chunks/{monitor-7I7Q73UR.js → monitor-ZHOFTN7N.js} +1 -1
  160. package/chunks/{nonInteractiveCli-YLYRJUBE.js → nonInteractiveCli-6SUGPTJ4.js} +1 -1
  161. package/chunks/{nonInteractiveToolExecutor-U2ASWT63.js → nonInteractiveToolExecutor-SAHBGO3A.js} +1 -1
  162. package/chunks/{notebook-edit-WAD7IQCF.js → notebook-edit-ETUOQH6G.js} +1 -1
  163. package/chunks/{omni-POUUDVU3.js → omni-HV2UBGMZ.js} +1 -1
  164. package/chunks/{openaiContentGenerator-L7X6IVPL.js → openaiContentGenerator-RZCG7E4M.js} +1 -1
  165. package/chunks/{openaiResponsesContentGenerator-7XCMFI6P.js → openaiResponsesContentGenerator-X23L5JV3.js} +1 -1
  166. package/chunks/{pidfile-MQQT2ZDA.js → pidfile-26WXQCHG.js} +1 -1
  167. package/chunks/{processUtils-OZLF72NC.js → processUtils-WXLFGNBT.js} +1 -1
  168. package/chunks/{prompt-terminal-ledger-IYUF6SUU.js → prompt-terminal-ledger-EIZZHF4A.js} +1 -1
  169. package/chunks/{qwenContentGenerator-DKH3ILUO.js → qwenContentGenerator-GOY7Y6KH.js} +1 -1
  170. package/chunks/{reactive-degrade-KSNGHMBN.js → reactive-degrade-MNMTTHO5.js} +1 -1
  171. package/chunks/{read-file-VEELW4OQ.js → read-file-OJNGPNTQ.js} +1 -1
  172. package/chunks/{resumeHistoryUtils-4SFDTBXU.js → resumeHistoryUtils-QWOWF4VY.js} +1 -1
  173. package/chunks/{review-QA6HRLVU.js → review-5S24HP2V.js} +1 -1
  174. package/chunks/{ripGrep-4J6ASSE3.js → ripGrep-Y4PY2MQF.js} +1 -1
  175. package/chunks/{run-qwen-serve-EJ67LA5O.js → run-qwen-serve-EOUUDZUK.js} +2 -2
  176. package/chunks/{runtime-6E2FSB5U.js → runtime-ZBPOQX6E.js} +1 -1
  177. package/chunks/{sandboxConfig-4VE4LNRI.js → sandboxConfig-R7KDS3P5.js} +1 -1
  178. package/chunks/{scheduled-tasks-GM5EJMK7.js → scheduled-tasks-Q6V7D6K6.js} +1 -1
  179. package/chunks/{scheduler-HOSVIIOE.js → scheduler-EBQY6BOK.js} +1 -1
  180. package/chunks/{search-memory-HEAQCHIK.js → search-memory-HX6E23JC.js} +1 -1
  181. package/chunks/{send-message-FAQ7XEZ5.js → send-message-OZCCCH2F.js} +1 -1
  182. package/chunks/{serve-VNKPOWSW.js → serve-CMGCI4BK.js} +1 -1
  183. package/chunks/{server-U2XBJLOV.js → server-7LOAKPDN.js} +3 -3
  184. package/chunks/{session-AZGROSFX.js → session-LVQYZSJE.js} +1 -1
  185. package/chunks/{session-attachments-root-6M2ECUNK.js → session-attachments-root-NWG7JOMN.js} +1 -1
  186. package/chunks/{session-execution-engine-selector-PYDVOSJF.js → session-execution-engine-selector-PHH47ZMA.js} +1 -1
  187. package/chunks/{session-pr-refresh-3IS7DLEV.js → session-pr-refresh-5IACZPCY.js} +1 -1
  188. package/chunks/{sessionService-3FWNA4ZB.js → sessionService-7PFAWLHC.js} +1 -1
  189. package/chunks/{settings-VHKT7JJC.js → settings-CPZBOHN5.js} +1 -1
  190. package/chunks/{shell-TYOPVB7H.js → shell-A7NLPS2W.js} +1 -1
  191. package/chunks/{skill-GJQIE5AX.js → skill-VGANGVOD.js} +1 -1
  192. package/chunks/{skill-settings-76NI6SF3.js → skill-settings-TSZO3X6N.js} +1 -1
  193. package/chunks/{spawnChannel-FMSYLDKB.js → spawnChannel-2JQYNQKT.js} +1 -1
  194. package/chunks/{standalone-update-BPZQDQHD.js → standalone-update-QXC3RM6I.js} +1 -1
  195. package/chunks/{start-opentui-ui-X7XYV5N3.js → start-opentui-ui-BKJ4JHVK.js} +1 -1
  196. package/chunks/{startInteractiveUI-UZDF4JUB.js → startInteractiveUI-4QIPR7ZY.js} +1 -1
  197. package/chunks/{team-create-RFZNEF76.js → team-create-5MU6BGXX.js} +1 -1
  198. package/chunks/{team-plan-approval-MGW3JGSC.js → team-plan-approval-NZUJ6FSA.js} +1 -1
  199. package/chunks/{terminal-image-renderer-3UED5GZV.js → terminal-image-renderer-CTMJULJ2.js} +1 -1
  200. package/chunks/{theme-manager-SF6FSSZW.js → theme-manager-6H7GA6QR.js} +1 -1
  201. package/chunks/{tool-call-W2CJR74U.js → tool-call-XG4CAD5X.js} +1 -1
  202. package/chunks/{tool-result-media-XSFON2ZQ.js → tool-result-media-RJ5ONO7R.js} +1 -1
  203. package/chunks/{tool-search-7GY5YTOU.js → tool-search-KBINGEWV.js} +1 -1
  204. package/chunks/{total-session-admission-OATGW6M5.js → total-session-admission-XNWYCO7G.js} +1 -1
  205. package/chunks/{trustedFolders-AM4PSGUB.js → trustedFolders-JT5MOB3A.js} +1 -1
  206. package/chunks/{update-relaunch-YKY52XUT.js → update-relaunch-HXMQI3HO.js} +1 -1
  207. package/chunks/{updateCheck-RKQ5CPZM.js → updateCheck-XWE3TWL5.js} +1 -1
  208. package/chunks/{upload-config-CBT7ARZY.js → upload-config-ET7NRHU7.js} +1 -1
  209. package/chunks/{useAutoAcceptIndicator-Z3YWPUNO.js → useAutoAcceptIndicator-TPMYKNJX.js} +1 -1
  210. package/chunks/{validateNonInterActiveAuth-7CQHU2RF.js → validateNonInterActiveAuth-U52KMEDS.js} +1 -1
  211. package/chunks/{version-N2OB6KWP.js → version-CW4RTJ3H.js} +1 -1
  212. package/chunks/{web-fetch-L5XCBCBA.js → web-fetch-UPMJ3XIZ.js} +1 -1
  213. package/chunks/{web-search-4EHUA3LJ.js → web-search-PXABWQVC.js} +1 -1
  214. package/chunks/{workflow-FGAUAYIP.js → workflow-UQ4V3NBZ.js} +1 -1
  215. package/chunks/{workflow-ancestor-trust-F7RRN6I3.js → workflow-ancestor-trust-QII5KTUJ.js} +1 -1
  216. package/chunks/{workspace-agents-QW4TKC52.js → workspace-agents-Q3KKMDX2.js} +1 -1
  217. package/chunks/{workspace-providers-status-MFSZT3YA.js → workspace-providers-status-3ASB64FB.js} +1 -1
  218. package/chunks/{workspace-registration-store-WQRDSIEI.js → workspace-registration-store-2NPD6U3B.js} +1 -1
  219. package/chunks/{workspace-registry-FXZFRSCH.js → workspace-registry-6QJKRCDR.js} +1 -1
  220. package/chunks/{workspace-runtime-coordinator-LJ5YAT3A.js → workspace-runtime-coordinator-ZXUWDQIB.js} +1 -1
  221. package/chunks/{workspace-service-U632SUWU.js → workspace-service-YPYTYYUN.js} +1 -1
  222. package/chunks/{workspace-skills-status-M7YXM3LF.js → workspace-skills-status-VTFHQ6R7.js} +1 -1
  223. package/chunks/{workspace-trust-reconciler-NLJGGI4K.js → workspace-trust-reconciler-52CZVPKH.js} +1 -1
  224. package/chunks/{write-file-BJCKSXX7.js → write-file-FDBR76G5.js} +1 -1
  225. package/chunks/{zoom-image-TLJPD4DB.js → zoom-image-MYKWCCXO.js} +1 -1
  226. package/cli.js +2 -2
  227. package/execution-worker.js +1 -1
  228. package/export-transcript-document.js +1 -1
  229. package/package.json +4 -4
  230. package/vendor/landlock-run/arm64-linux/qwen-landlock-run +0 -0
  231. package/vendor/landlock-run/x64-linux/qwen-landlock-run +0 -0
  232. package/vendor/ripgrep/arm64-darwin/rg +0 -0
  233. package/vendor/ripgrep/arm64-linux/rg +0 -0
  234. package/vendor/ripgrep/x64-darwin/rg +0 -0
  235. package/vendor/ripgrep/x64-linux/rg +0 -0
  236. package/vendor/tree-sitter/tree-sitter-bash.wasm +0 -0
  237. package/vendor/tree-sitter/tree-sitter.wasm +0 -0
  238. package/web-shell/assets/{PierreFilePreview-D9tbdFw8.js → PierreFilePreview-DGTp45Z4.js} +1 -1
  239. package/web-shell/assets/{SpreadsheetPreview-CeFAk2s-.js → SpreadsheetPreview-DVC_YVei.js} +1 -1
  240. package/web-shell/assets/{WorkspaceFileBrowser-iaURw8SR.js → WorkspaceFileBrowser-DaQNpS06.js} +1 -1
  241. package/web-shell/assets/{abnfDiagram-VCTEODGH-Z4CT1NCF.js → abnfDiagram-VCTEODGH-wJbiOoPK.js} +1 -1
  242. package/web-shell/assets/{agents-route-B7o2Rq-a.js → agents-route-DUhhA1KI.js} +1 -1
  243. package/web-shell/assets/{arc-DcHBdUJQ.js → arc-CvpNMy1d.js} +1 -1
  244. package/web-shell/assets/{architectureDiagram-5GKGNRK7-DRDhEC81.js → architectureDiagram-5GKGNRK7-DIhi3dIz.js} +1 -1
  245. package/web-shell/assets/{blockDiagram-NRAW4CY4-CYRE6WIc.js → blockDiagram-NRAW4CY4-CoeyTlVJ.js} +1 -1
  246. package/web-shell/assets/{c4Diagram-UCG6FXSJ-CIM8N_Sj.js → c4Diagram-UCG6FXSJ-BYoK_I9M.js} +1 -1
  247. package/web-shell/assets/channel-DvtGOCg6.js +1 -0
  248. package/web-shell/assets/{chunk-2Q5K7J3B-Bbfka9Fe.js → chunk-2Q5K7J3B-BeD4GwPg.js} +1 -1
  249. package/web-shell/assets/{chunk-5VM5RSS4-C02zF3RY.js → chunk-5VM5RSS4-BpkJsB_y.js} +1 -1
  250. package/web-shell/assets/{chunk-F27PBJKO-Dn0wRD2F.js → chunk-F27PBJKO-BROEWQ1J.js} +1 -1
  251. package/web-shell/assets/{chunk-G27WJ6UU-Dwpl3l0W.js → chunk-G27WJ6UU-DA8Wtppt.js} +1 -1
  252. package/web-shell/assets/{chunk-JWPE2WC7-sQbzSoTR.js → chunk-JWPE2WC7-GqB-QFh5.js} +1 -1
  253. package/web-shell/assets/{chunk-LCL6LL3I-DNlNDtfr.js → chunk-LCL6LL3I-DIPUwYsX.js} +1 -1
  254. package/web-shell/assets/{chunk-POPQ4Y6H-BOgf1Dl3.js → chunk-POPQ4Y6H-DbnU-jxX.js} +1 -1
  255. package/web-shell/assets/{chunk-SVP7TREG-DOofWP00.js → chunk-SVP7TREG-DvH7bQ-w.js} +1 -1
  256. package/web-shell/assets/{chunk-XXDRQBXY-Bj9FxhWU.js → chunk-XXDRQBXY-DdVWVo3U.js} +1 -1
  257. package/web-shell/assets/classDiagram-DTDB5LWJ-9NR5W1rE.js +1 -0
  258. package/web-shell/assets/classDiagram-v2-JRS7N3AN-9NR5W1rE.js +1 -0
  259. package/web-shell/assets/{cose-bilkent-JH36ORCC-CUlPjyww.js → cose-bilkent-JH36ORCC-JgMKxP9H.js} +1 -1
  260. package/web-shell/assets/{cynefin-OW5HDTMX-5noArzI7.js → cynefin-OW5HDTMX-BVUpNgVm.js} +1 -1
  261. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-DELvTqmf.js → cynefinDiagram-5FMLGOSQ-CxAdk-iS.js} +1 -1
  262. package/web-shell/assets/{dagre-3AP2YEHR-CAL6Z3hL.js → dagre-3AP2YEHR-CvXWkM86.js} +1 -1
  263. package/web-shell/assets/{diagram-S7CK7UJ4-DQC2gaIi.js → diagram-S7CK7UJ4-DD_PS4nm.js} +1 -1
  264. package/web-shell/assets/{diagram-UQ7AKVKN-CkU6M-3R.js → diagram-UQ7AKVKN-EVZkTODD.js} +1 -1
  265. package/web-shell/assets/{diagram-VSXAHHWV-CvHpHwVx.js → diagram-VSXAHHWV-CGZc1pZU.js} +1 -1
  266. package/web-shell/assets/{diagram-VX7I27RA-D9l5F9iB.js → diagram-VX7I27RA-DjNql499.js} +1 -1
  267. package/web-shell/assets/{diagram-Z3DM3KII-DW-VFvYx.js → diagram-Z3DM3KII-CCa0WtmR.js} +1 -1
  268. package/web-shell/assets/{docx-preview-8MQfOGQh.js → docx-preview-DpVElxvj.js} +1 -1
  269. package/web-shell/assets/{ebnfDiagram-PWID7BFC-C0Q71wC_.js → ebnfDiagram-PWID7BFC-W2hoOJZF.js} +1 -1
  270. package/web-shell/assets/{erDiagram-SSCWMZ5O-DWDLRh1S.js → erDiagram-SSCWMZ5O-Dz5NxxEb.js} +1 -1
  271. package/web-shell/assets/{flowDiagram-A5DVABFB-CVzJnl1P.js → flowDiagram-A5DVABFB-BTMAn8b5.js} +1 -1
  272. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-B320pcgR.js → ganttDiagram-EL5Y4UJY-BaFrd5ZY.js} +1 -1
  273. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-Di4uZh-J.js → gitGraphDiagram-WWUBYQGX-IlmdUqRk.js} +1 -1
  274. package/web-shell/assets/{index-Csr8Hx_O.js → index-C2ez0ZjE.js} +1 -1
  275. package/web-shell/assets/{index-C9BecA_H.js → index-Cs-XBNmB.js} +101 -101
  276. package/web-shell/assets/{infoDiagram-RXCK75RN-CbafhxET.js → infoDiagram-RXCK75RN-BHs9kpar.js} +1 -1
  277. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-DrQuIDeR.js → ishikawaDiagram-5VMMS53U-DWCEQ85v.js} +1 -1
  278. package/web-shell/assets/{journeyDiagram-EYS64GPL-BschmjBj.js → journeyDiagram-EYS64GPL-RTDAw9yc.js} +1 -1
  279. package/web-shell/assets/{kanban-definition-3QL26DDD-B7x9BU9N.js → kanban-definition-3QL26DDD-B7Nl9bq6.js} +1 -1
  280. package/web-shell/assets/{layout-BewPaOyO.js → layout-BabjFEb1.js} +1 -1
  281. package/web-shell/assets/{linear-CnLILCVp.js → linear-CZuGjuQd.js} +1 -1
  282. package/web-shell/assets/{mermaid.core-Csj9KPfJ.js → mermaid.core-CK78bIGt.js} +6 -6
  283. package/web-shell/assets/{mindmap-definition-FBJOCRG2-CIGTi5gg.js → mindmap-definition-FBJOCRG2-BbcCi_jP.js} +1 -1
  284. package/web-shell/assets/{pegDiagram-XKGWAZYB-CuWBRQzb.js → pegDiagram-XKGWAZYB-DpLQ7u8i.js} +1 -1
  285. package/web-shell/assets/{pieDiagram-E7YTZNPT-Co5ukXCE.js → pieDiagram-E7YTZNPT-BpWFVtM0.js} +1 -1
  286. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-B0hzjh6o.js → quadrantDiagram-AXDQQJYC-CGzYlaN1.js} +1 -1
  287. package/web-shell/assets/{railroadDiagram-O6MQD6OU-nhkJB0xD.js → railroadDiagram-O6MQD6OU-BNQYW-Zi.js} +1 -1
  288. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-C7NpxjVR.js → requirementDiagram-EFPCY7ZU-C4fCdIDW.js} +1 -1
  289. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CUWlnhZC.js → sankeyDiagram-P5KCCOFB-BvbbAnMA.js} +1 -1
  290. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BoykH0_J.js → sequenceDiagram-WJ2MYXX4-DGXNc6E1.js} +1 -1
  291. package/web-shell/assets/{sizeCapture-X5ZJPWSS-aF-PkSe5.js → sizeCapture-X5ZJPWSS-C4W45Xf5.js} +1 -1
  292. package/web-shell/assets/{stateDiagram-HBIQ2CUA-g5q0b922.js → stateDiagram-HBIQ2CUA-D3q0fen-.js} +1 -1
  293. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-XKoYIi05.js +1 -0
  294. package/web-shell/assets/{swimlanes-XN3QIQJK-BbASszfe.js → swimlanes-XN3QIQJK-D8n-ResR.js} +1 -1
  295. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-C7qJMSzs.js +8 -0
  296. package/web-shell/assets/{timeline-definition-24CTP7MA-AXIV0TJJ.js → timeline-definition-24CTP7MA-Cio4y1mM.js} +1 -1
  297. package/web-shell/assets/{vennDiagram-4TSXK5OY-B-E0rj1h.js → vennDiagram-4TSXK5OY-DVlg0xnc.js} +1 -1
  298. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DiOOYJ2D.js → wardleyDiagram-VM6X3IG4-CgeIsimQ.js} +1 -1
  299. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-De_z7HkS.js → xychartDiagram-S5SC5T6Z-UXjyTLnU.js} +1 -1
  300. package/web-shell/index.html +1 -1
  301. package/web-shell/sw.js +1 -1
  302. package/web-shell/assets/channel-Bwr9aS_E.js +0 -1
  303. package/web-shell/assets/classDiagram-DTDB5LWJ-BmY8Mmyo.js +0 -1
  304. package/web-shell/assets/classDiagram-v2-JRS7N3AN-BmY8Mmyo.js +0 -1
  305. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CTOjUMow.js +0 -1
  306. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bz6ia3oL.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{buildManagedAutoMemoryPrompt,createMemoryScopedAgentConfig,deriveConfig,ensureAutoMemoryScaffold,ensureUserAutoMemoryScaffold,isAllowedMemoryPath,readAutoMemoryIndex,readUserAutoMemoryIndex,rebuildManagedAutoMemoryIndex,rebuildUserAutoMemoryIndex,renderWriterKeywordVocabularySnapshot,runForkedAgent}from"./chunk-RKPHDO42.js";import{scanAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments}from"./chunk-GNQGC2DJ.js";import{getAutoMemoryRoot,getUserAutoMemoryRoot}from"./chunk-37KFLBKZ.js";import{ToolNames}from"./chunk-2UNFJQ2D.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import path from"node:path";var debugLogger=createDebugLogger("AUTO_MEMORY_REMEMBER");function buildManagedRememberPrompt(fact,projectRoot,options={}){const trimmed=fact.trim();const projectDir=projectRoot?getAutoMemoryRoot(projectRoot):void 0;const userDir=getUserAutoMemoryRoot();const dirHint=projectDir===void 0?"":options.scope==="project"?` Store this memory only in PROJECT memory at \`${projectDir}\`. This explicit project target overrides the memory type's default destination; do not read or write USER memory at \`${userDir}\`.`:options.scope==="user"?` Store this memory only in USER memory at \`${userDir}\`. This explicit user target overrides the memory type's default destination; do not read or write PROJECT memory at \`${projectDir}\`.`:` Choose the destination directory by the type's \`<scope>\`: USER memory at \`${userDir}\` for cross-project facts, PROJECT memory at \`${projectDir}\` for this-project-only facts.`;const content=options.wrapUserContent?`<user-content>
3
+ import{buildManagedAutoMemoryPrompt,createMemoryScopedAgentConfig,deriveConfig,ensureAutoMemoryScaffold,ensureUserAutoMemoryScaffold,isAllowedMemoryPath,readAutoMemoryIndex,readUserAutoMemoryIndex,rebuildManagedAutoMemoryIndex,rebuildUserAutoMemoryIndex,renderWriterKeywordVocabularySnapshot,runForkedAgent}from"./chunk-LDXZT3SG.js";import{scanAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments}from"./chunk-GNQGC2DJ.js";import{getAutoMemoryRoot,getUserAutoMemoryRoot}from"./chunk-37KFLBKZ.js";import{ToolNames}from"./chunk-2UNFJQ2D.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import path from"node:path";var debugLogger=createDebugLogger("AUTO_MEMORY_REMEMBER");function buildManagedRememberPrompt(fact,projectRoot,options={}){const trimmed=fact.trim();const projectDir=projectRoot?getAutoMemoryRoot(projectRoot):void 0;const userDir=getUserAutoMemoryRoot();const dirHint=projectDir===void 0?"":options.scope==="project"?` Store this memory only in PROJECT memory at \`${projectDir}\`. This explicit project target overrides the memory type's default destination; do not read or write USER memory at \`${userDir}\`.`:options.scope==="user"?` Store this memory only in USER memory at \`${userDir}\`. This explicit user target overrides the memory type's default destination; do not read or write PROJECT memory at \`${projectDir}\`.`:` Choose the destination directory by the type's \`<scope>\`: USER memory at \`${userDir}\` for cross-project facts, PROJECT memory at \`${projectDir}\` for this-project-only facts.`;const content=options.wrapUserContent?`<user-content>
4
4
  ${trimmed}
5
5
  </user-content>`:trimmed;return`Please save the following to your memory system.${dirHint} Choose the most appropriate memory type (user, feedback, project, or reference) based on the content:
6
6
 
@@ -2,7 +2,7 @@
2
2
  "use strict";
3
3
  import{resolvePolicyToolSettings}from"./chunk-IV3HAIUN.js";import{MEDIA_MEMORY_FILE_NAME}from"./chunk-UYYQB2TU.js";import{DEFAULT_OMNI_PROCESSING_LIMITS,conditionUsesNamespace,evaluateFixedPolicyCondition}from"./chunk-GBFZYVZ4.js";import{OBJECT_EXTENSION_RE}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile}from"./chunk-ZBHL2CXR.js";import{OmniJsonCacheFile}from"./chunk-AMGUAA4G.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-U2ASWT63.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-SAHBGO3A.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{SCHEDULED_TASK_RUN_SOURCE_ID_PREFIX}from"./chunk-4QIFOIBS.js";import{ChannelDeliveryError,MAX_CHANNEL_DELIVERY_TEXT_LENGTH}from"./chunk-O6ZQAVRG.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{MAX_CHANNEL_DELIVERY_NAME_LENGTH,MAX_CHANNEL_DELIVERY_TARGET_ID_LENGTH}from"./chunk-VMQO3VPA.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var TRUNCATED_TEXT_SUFFIX="\n\n[Channel delivery truncated because the result exceeded the delivery size limit.]";function isBoundedString(value,maxLength){return typeof value==="string"&&value.trim().length>0&&value.length<=maxLength}__name(isBoundedString,"isBoundedString");function parseChannelDelivery(value){if(typeof value!=="object"||value===null){throw new ChannelDeliveryError("channel_delivery_invalid","Invalid channel delivery.")}const delivery=value;const rawTarget=delivery["target"];if(delivery["kind"]!=="channel"||typeof rawTarget!=="object"||rawTarget===null||!Object.keys(delivery).every(key=>key==="kind"||key==="target")){throw new ChannelDeliveryError("channel_delivery_invalid","Invalid channel delivery.")}const target=rawTarget;if(!isBoundedString(target["channelName"],MAX_CHANNEL_DELIVERY_NAME_LENGTH)||target["type"]!=="user"&&target["type"]!=="chat"||!isBoundedString(target["id"],MAX_CHANNEL_DELIVERY_TARGET_ID_LENGTH)||!Object.keys(target).every(key=>key==="channelName"||key==="type"||key==="id")){throw new ChannelDeliveryError("channel_delivery_invalid","Invalid channel delivery.")}return{kind:"channel",target:{channelName:target["channelName"],type:target["type"],id:target["id"]}}}__name(parseChannelDelivery,"parseChannelDelivery");function normalizeChannelDeliveryText(text){if(text.length<=MAX_CHANNEL_DELIVERY_TEXT_LENGTH)return text;const prefixLimit=MAX_CHANNEL_DELIVERY_TEXT_LENGTH-TRUNCATED_TEXT_SUFFIX.length;let prefix=text.slice(0,prefixLimit);const lastCodeUnit=prefix.charCodeAt(prefix.length-1);if(lastCodeUnit>=55296&&lastCodeUnit<=56319){prefix=prefix.slice(0,-1)}return`${prefix}${TRUNCATED_TEXT_SUFFIX}`}__name(normalizeChannelDeliveryText,"normalizeChannelDeliveryText");function normalizeChannelDelivery(deliveryId,delivery,text){if(typeof text!=="string"||text.trim().length===0){throw new ChannelDeliveryError("channel_delivery_invalid","Channel delivery text is empty.")}return{deliveryId,channelName:delivery.target.channelName,target:{type:delivery.target.type,id:delivery.target.id},text:normalizeChannelDeliveryText(text)}}__name(normalizeChannelDelivery,"normalizeChannelDelivery");init_esbuild_shims();function scheduledTaskRunSourceId(taskId){return`${SCHEDULED_TASK_RUN_SOURCE_ID_PREFIX}${taskId}`}__name(scheduledTaskRunSourceId,"scheduledTaskRunSourceId");var SCHEDULED_TASK_RUN_INSTRUCTION="This is a scheduled task run. Execute the instructions below now. Do not create or modify a schedule unless the instructions explicitly ask you to.";function cleanMetadataLine(value){return stripTerminalControlSequences(value).replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"").trim().replace(/\s+/g," ")}__name(cleanMetadataLine,"cleanMetadataLine");var MAX_RUN_SESSION_NAME_LENGTH=60;function pad2(n){return String(n).padStart(2,"0")}__name(pad2,"pad2");function scheduledTaskRunSessionName(label,triggeredAt){const at=new Date(triggeredAt);const suffix=` \xB7 ${pad2(at.getMonth()+1)}-${pad2(at.getDate())} ${pad2(at.getHours())}:${pad2(at.getMinutes())}`;const cleaned=cleanMetadataLine(label);const budget=MAX_RUN_SESSION_NAME_LENGTH-suffix.length;let short=cleaned;if(cleaned.length>budget){let cut=budget-1;const boundary=cleaned.charCodeAt(cut-1);if(boundary>=55296&&boundary<=56319)cut-=1;short=`${cleaned.slice(0,cut)}\u2026`}return`${short}${suffix}`}__name(scheduledTaskRunSessionName,"scheduledTaskRunSessionName");function buildScheduledTaskRunPrompt(input){const name=cleanMetadataLine(input.name??input.id)||input.id;const cron=cleanMetadataLine(input.cron);return[`Scheduled task: ${name}`,`Task ID: ${input.id}`,`Schedule: ${cron}`,`Triggered at: ${new Date(input.triggeredAt).toISOString()}`,`Trigger: ${input.trigger}`,"Session: new chat for this run","",SCHEDULED_TASK_RUN_INSTRUCTION,"",input.prompt].join("\n")}__name(buildScheduledTaskRunPrompt,"buildScheduledTaskRunPrompt");export{parseChannelDelivery,normalizeChannelDeliveryText,normalizeChannelDelivery,scheduledTaskRunSourceId,scheduledTaskRunSessionName,buildScheduledTaskRunPrompt};
3
+ import{SCHEDULED_TASK_RUN_SOURCE_ID_PREFIX}from"./chunk-YVZ4XZRB.js";import{ChannelDeliveryError,MAX_CHANNEL_DELIVERY_TEXT_LENGTH}from"./chunk-O6ZQAVRG.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{MAX_CHANNEL_DELIVERY_NAME_LENGTH,MAX_CHANNEL_DELIVERY_TARGET_ID_LENGTH}from"./chunk-VMQO3VPA.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var TRUNCATED_TEXT_SUFFIX="\n\n[Channel delivery truncated because the result exceeded the delivery size limit.]";function isBoundedString(value,maxLength){return typeof value==="string"&&value.trim().length>0&&value.length<=maxLength}__name(isBoundedString,"isBoundedString");function parseChannelDelivery(value){if(typeof value!=="object"||value===null){throw new ChannelDeliveryError("channel_delivery_invalid","Invalid channel delivery.")}const delivery=value;const rawTarget=delivery["target"];if(delivery["kind"]!=="channel"||typeof rawTarget!=="object"||rawTarget===null||!Object.keys(delivery).every(key=>key==="kind"||key==="target")){throw new ChannelDeliveryError("channel_delivery_invalid","Invalid channel delivery.")}const target=rawTarget;if(!isBoundedString(target["channelName"],MAX_CHANNEL_DELIVERY_NAME_LENGTH)||target["type"]!=="user"&&target["type"]!=="chat"||!isBoundedString(target["id"],MAX_CHANNEL_DELIVERY_TARGET_ID_LENGTH)||!Object.keys(target).every(key=>key==="channelName"||key==="type"||key==="id")){throw new ChannelDeliveryError("channel_delivery_invalid","Invalid channel delivery.")}return{kind:"channel",target:{channelName:target["channelName"],type:target["type"],id:target["id"]}}}__name(parseChannelDelivery,"parseChannelDelivery");function normalizeChannelDeliveryText(text){if(text.length<=MAX_CHANNEL_DELIVERY_TEXT_LENGTH)return text;const prefixLimit=MAX_CHANNEL_DELIVERY_TEXT_LENGTH-TRUNCATED_TEXT_SUFFIX.length;let prefix=text.slice(0,prefixLimit);const lastCodeUnit=prefix.charCodeAt(prefix.length-1);if(lastCodeUnit>=55296&&lastCodeUnit<=56319){prefix=prefix.slice(0,-1)}return`${prefix}${TRUNCATED_TEXT_SUFFIX}`}__name(normalizeChannelDeliveryText,"normalizeChannelDeliveryText");function normalizeChannelDelivery(deliveryId,delivery,text){if(typeof text!=="string"||text.trim().length===0){throw new ChannelDeliveryError("channel_delivery_invalid","Channel delivery text is empty.")}return{deliveryId,channelName:delivery.target.channelName,target:{type:delivery.target.type,id:delivery.target.id},text:normalizeChannelDeliveryText(text)}}__name(normalizeChannelDelivery,"normalizeChannelDelivery");init_esbuild_shims();function scheduledTaskRunSourceId(taskId){return`${SCHEDULED_TASK_RUN_SOURCE_ID_PREFIX}${taskId}`}__name(scheduledTaskRunSourceId,"scheduledTaskRunSourceId");var SCHEDULED_TASK_RUN_INSTRUCTION="This is a scheduled task run. Execute the instructions below now. Do not create or modify a schedule unless the instructions explicitly ask you to.";function cleanMetadataLine(value){return stripTerminalControlSequences(value).replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"").trim().replace(/\s+/g," ")}__name(cleanMetadataLine,"cleanMetadataLine");var MAX_RUN_SESSION_NAME_LENGTH=60;function pad2(n){return String(n).padStart(2,"0")}__name(pad2,"pad2");function scheduledTaskRunSessionName(label,triggeredAt){const at=new Date(triggeredAt);const suffix=` \xB7 ${pad2(at.getMonth()+1)}-${pad2(at.getDate())} ${pad2(at.getHours())}:${pad2(at.getMinutes())}`;const cleaned=cleanMetadataLine(label);const budget=MAX_RUN_SESSION_NAME_LENGTH-suffix.length;let short=cleaned;if(cleaned.length>budget){let cut=budget-1;const boundary=cleaned.charCodeAt(cut-1);if(boundary>=55296&&boundary<=56319)cut-=1;short=`${cleaned.slice(0,cut)}\u2026`}return`${short}${suffix}`}__name(scheduledTaskRunSessionName,"scheduledTaskRunSessionName");function buildScheduledTaskRunPrompt(input){const name=cleanMetadataLine(input.name??input.id)||input.id;const cron=cleanMetadataLine(input.cron);return[`Scheduled task: ${name}`,`Task ID: ${input.id}`,`Schedule: ${cron}`,`Triggered at: ${new Date(input.triggeredAt).toISOString()}`,`Trigger: ${input.trigger}`,"Session: new chat for this run","",SCHEDULED_TASK_RUN_INSTRUCTION,"",input.prompt].join("\n")}__name(buildScheduledTaskRunPrompt,"buildScheduledTaskRunPrompt");export{parseChannelDelivery,normalizeChannelDeliveryText,normalizeChannelDelivery,scheduledTaskRunSourceId,scheduledTaskRunSessionName,buildScheduledTaskRunPrompt};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{ProcessRegistry}from"./chunk-ESSOEHTE.js";import{createStderrForwarder}from"./chunk-SC6ZKUED.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError,ndJsonStream}from"./chunk-WSOEJTOC.js";import{AgentEventEmitter,renderSubagentSystemPrompt}from"./chunk-RKPHDO42.js";import{sanitizeChildEnv}from"./chunk-LFKUPU57.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";import{Readable,Writable}from"node:stream";init_esbuild_shims();var INIT_TIMEOUT_MS=1e4;var debugLogger=createDebugLogger("EXTERNAL_AGENT");function externalModelLabel(command){return`external-acp:${command.split(/[\\/]/).pop()??command}`}__name(externalModelLabel,"externalModelLabel");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var EXTERNAL_ACTION_PROMPT_MAX=300;function stripControlChars(value){let out="";for(const ch of value){const code=ch.codePointAt(0)??0;out+=code>=32&&code!==127&&!(code>=128&&code<=159)?ch:" "}return out}__name(stripControlChars,"stripControlChars");function describeExternalAction(toolCall){const title=stripControlChars(toolCall.title??toolCall.kind??"External action");const raw=toolCall.rawInput;if(!isRecord(raw))return title;const detail=stripControlChars(JSON.stringify(raw));const rendered=`${title}: ${detail}`;return rendered.length>EXTERNAL_ACTION_PROMPT_MAX?`${rendered.slice(0,EXTERNAL_ACTION_PROMPT_MAX)}\u2026`:rendered}__name(describeExternalAction,"describeExternalAction");function assertExternalAgentSpawnPlatformSupported(platform=process.platform){if(platform==="win32"){throw new Error("External agents are not supported on Windows in this release: the executor spawn is POSIX-only. An npm-installed adapter resolves to a `.cmd` launcher that cannot be spawned without a shell, and the process-tree reaping is POSIX-specific. Run the external agent on macOS/Linux (or WSL). Windows support is a tracked follow-up.")}}__name(assertExternalAgentSpawnPlatformSupported,"assertExternalAgentSpawnPlatformSupported");function resolvePermissionMode(permissionMode,approvalMode){switch((approvalMode??permissionMode??"").trim().toLowerCase()){case"auto":case"acceptedits":case"auto-edit":return"acceptEdits";case"plan":return"plan";case"bypasspermissions":case"bypass":case"yolo":return"bypass";default:return"default"}}__name(resolvePermissionMode,"resolvePermissionMode");var POLICY_MODE_ALIASES={bypass:["bypassPermissions","yolo"],acceptEdits:["acceptEdits","auto-edit","auto"],plan:["plan"],default:["default"]};function selectPeerModeId(policy,availableModeIds){return POLICY_MODE_ALIASES[policy].find(id=>availableModeIds.includes(id))}__name(selectPeerModeId,"selectPeerModeId");function optionKindForOutcome(outcome){switch(outcome){case"proceed_once":case"proceed_once_and_switch_to_default":return"allow_once";case"proceed_always":case"proceed_always_server":case"proceed_always_tool":case"proceed_always_project":case"proceed_always_user":return"allow_always";case"modify_with_editor":case"cancel":case"restore_previous":return"reject_once";default:{const exhaustive=outcome;void exhaustive;return"reject_once"}}}__name(optionKindForOutcome,"optionKindForOutcome");function selectPermissionOption(options,outcome){if(outcome==="cancel")return void 0;if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}const kind=optionKindForOutcome(outcome);return(options.find(option=>option.kind===kind)??(kind==="allow_always"?options.find(option=>option.kind==="allow_once"):void 0)??options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectPermissionOption,"selectPermissionOption");function selectRejectOption(options){if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}return(options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectRejectOption,"selectRejectOption");function isExpectedExternalAgentCleanupExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited uncleanly during shutdown \(code=[^,]+, signal=[^)]+\)$/.test(error.message)}__name(isExpectedExternalAgentCleanupExit,"isExpectedExternalAgentCleanupExit");function isUnprovenExternalAgentTreeExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited before its initial process-tree snapshot completed$/.test(error.message)}__name(isUnprovenExternalAgentTreeExit,"isUnprovenExternalAgentTreeExit");var ExternalAgentTimeoutError=class extends Error{static{__name(this,"ExternalAgentTimeoutError")}constructor(timeoutMs){super(`External ACP operation timed out after ${timeoutMs}ms`);this.name="ExternalAgentTimeoutError"}};var AcpSubagentExecutor=class _AcpSubagentExecutor{constructor(params,child,emitter){this.params=params;this.child=child;this.emitter=emitter;this.coreView={getEventEmitter:__name(()=>emitter,"getEventEmitter"),modelConfig:{...params.modelConfig,model:externalModelLabel(params.spec.command)}};void child.exited.then(()=>this.fail(new Error(`external agent "${params.name}" exited`)),error=>this.fail(error))}static{__name(this,"AcpSubagentExecutor")}connection;sessionId="";finalText="";thoughtText="";terminateMode="ERROR";round=0;durationMs=0;turnStartedAt=0;toolCalls=0;toolSucceeded=0;toolFailed=0;executing=false;started=false;disposed=false;cancelled=false;disposePromise;provider;pendingPermissions=new Map;tools=new Map;toolNames=new Map;finishedTools=new Set;failure=new AbortController;coreView;static async create(params){assertExternalAgentSpawnPlatformSupported();if(params.runConfig.max_turns!==void 0){throw new Error("External ACP agents cannot enforce max_turns.")}const minutes=params.runConfig.max_time_minutes;if(minutes!==void 0&&(!Number.isFinite(minutes)||minutes<=0||minutes*6e4>2147483647)){throw new Error("External ACP max_time_minutes must be positive, finite, and within the Node timer range.")}const child=spawn(params.spec.command,params.spec.args??[],{cwd:params.runtimeContext.getTargetDir(),stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:true,env:sanitizeChildEnv(process.env)});const tracked=new ProcessRegistry().reserve().attach(child,{ownsProcessTree:true});const executor=new _AcpSubagentExecutor(params,tracked,params.eventEmitter??new AgentEventEmitter);child.on("error",error=>executor.fail(error));child.stdin.on("error",error=>executor.fail(error));child.stdout.on("error",error=>executor.fail(error));const forwarder=createStderrForwarder({prefix:`[external-agent ${params.name}] `});child.stderr.setEncoding("utf8");child.stderr.on("data",forwarder.onData);child.stderr.on("end",forwarder.onEnd);child.stderr.on("error",()=>{});try{executor.connection=new ClientSideConnection(()=>executor.buildClient(),ndJsonStream(Writable.toWeb(child.stdin),Readable.toWeb(child.stdout)));void executor.connection.closed.then(()=>executor.fail(new Error("External ACP connection closed")));await executor.wait(executor.connect(),INIT_TIMEOUT_MS);return executor}catch(error){await executor.dispose();throw error}}buildClient(){return{sessionUpdate:__name(async params=>this.onSessionUpdate(params),"sessionUpdate"),requestPermission:__name(params=>this.onRequestPermission(params),"requestPermission"),readTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/read_text_file")},"readTextFile"),writeTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/write_text_file")},"writeTextFile"),extMethod:__name(async method=>{throw RequestError.methodNotFound(method)},"extMethod"),extNotification:__name(async()=>{},"extNotification")}}async connect(){const initialized=await this.connection.initialize({protocolVersion:PROTOCOL_VERSION,clientCapabilities:{fs:{readTextFile:false,writeTextFile:false}}});if(initialized.protocolVersion!==PROTOCOL_VERSION){throw new Error("Unsupported external ACP protocol version")}const session=await this.connection.newSession({cwd:this.params.runtimeContext.getTargetDir(),mcpServers:[]});if(!session.sessionId)throw new Error("External ACP agent returned no sessionId");this.sessionId=session.sessionId;const policy=resolvePermissionMode(this.params.permissionMode,this.params.approvalMode);const availableIds=session.modes?.availableModes.map(mode=>mode.id)??[];const modeId=selectPeerModeId(policy,availableIds);if(!modeId){throw new Error(`External ACP agent does not advertise any mode for the host's ${policy} approval policy (advertised: ${availableIds.join(", ")||"none"})`)}await this.connection.setSessionMode({sessionId:this.sessionId,modeId})}fail(error){this.failure.abort(error);this.drainPermissions()}async wait(operation,timeoutMs,signal){let timer;let onFailure=__name(()=>{},"onFailure");let onAbort=__name(()=>{},"onAbort");const stopped=new Promise((_resolve,reject)=>{onFailure=__name(()=>reject(this.failure.signal.reason),"onFailure");onAbort=__name(()=>reject(signal?.reason??new Error("External agent cancelled")),"onAbort");this.failure.signal.addEventListener("abort",onFailure,{once:true});signal?.addEventListener("abort",onAbort,{once:true});if(this.failure.signal.aborted)onFailure();if(signal?.aborted)onAbort();if(timeoutMs!==void 0){timer=setTimeout(()=>reject(new ExternalAgentTimeoutError(timeoutMs)),timeoutMs)}});try{return await Promise.race([operation,stopped])}finally{clearTimeout(timer);this.failure.signal.removeEventListener("abort",onFailure);signal?.removeEventListener("abort",onAbort)}}async execute(context,signal,options={}){if(context.get("initial_messages_override")!==void 0){throw new Error("External ACP agents cannot import in-process conversation history")}const continuation=this.started;const system=continuation?"":renderSubagentSystemPrompt(this.params.promptConfig,context,this.params.runtimeContext);const task=String(context.get("task_prompt")??"Get Started!");const catalog=system?this.params.runtimeContext.getAutoMemoryContext():"";await this.runTurn([...system?[{type:"text",text:system}]:[],{type:"text",text:task},...catalog?[{type:"text",text:catalog}]:[]],signal,options,continuation?[task]:void 0)}async executeExternalInputs(inputs,signal,options={}){if(inputs.length===0)return;await this.runTurn(this.inputPrompt(inputs),signal,options,inputs)}inputPrompt(inputs){return inputs.map(input=>({type:"text",text:typeof input==="string"?input:input.text}))}emitInputs(inputs){for(const input of inputs){this.emitter.emit("external_message",{subagentId:this.id,kind:typeof input==="string"?"message":input.kind,text:typeof input==="string"?input:input.text,timestamp:Date.now()})}}async runTurn(prompt,signal,options={},inputs){if(this.executing)throw new Error("External ACP agents do not support concurrent turns");if(this.disposed||this.failure.signal.aborted)throw new Error("External ACP agent is closed");this.executing=true;this.started=true;this.cancelled=false;this.finalText="";this.thoughtText="";this.terminateMode="ERROR";if(options.resetStats!==false){this.round=this.durationMs=this.toolCalls=this.toolSucceeded=this.toolFailed=0}this.tools.clear();this.toolNames.clear();this.finishedTools.clear();this.turnStartedAt=Date.now();const timeoutMs=this.params.runConfig.max_time_minutes===void 0?void 0:this.params.runConfig.max_time_minutes*6e4;const cancel=__name(()=>{this.cancelled=true;this.drainPermissions();void this.connection.cancel({sessionId:this.sessionId}).catch(()=>{})},"cancel");signal?.addEventListener("abort",cancel,{once:true});let timedOut=false;try{this.emitter.emit("start",{subagentId:this.id,name:this.params.name,model:this.coreView.modelConfig.model,tools:[],timestamp:Date.now()});if(signal?.aborted){this.terminateMode="CANCELLED";return}const entryRound=this.round;let next=prompt;do{this.round++;const remaining=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remaining!==void 0&&remaining<=0){this.terminateMode="TIMEOUT";break}if(inputs&&this.round===entryRound+1)this.emitInputs(inputs);const result=await this.wait(this.connection.prompt({sessionId:this.sessionId,prompt:next}),remaining,signal);this.terminateMode=this.stopMode(result.stopReason);if(this.terminateMode!=="GOAL")break;if(signal?.aborted){this.terminateMode="CANCELLED";break}const remainingNext=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remainingNext!==void 0&&remainingNext<=0){this.terminateMode="TIMEOUT";break}const queued=this.provider?.()??[];if(queued.length===0)break;this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.finalText="";this.thoughtText="";this.emitInputs(queued);next=this.inputPrompt(queued)}while(!signal?.aborted);if(signal?.aborted)this.terminateMode="CANCELLED"}catch(error){timedOut=error instanceof ExternalAgentTimeoutError;this.terminateMode=signal?.aborted?"CANCELLED":timedOut?"TIMEOUT":"ERROR";if(this.emitter.rawListeners("error").length>0&&!signal?.aborted){this.emitter.emit("error",{subagentId:this.id,error:error instanceof Error?error.message:String(error),timestamp:Date.now()})}await this.dispose();if(!signal?.aborted&&!timedOut)throw error}finally{signal?.removeEventListener("abort",cancel);this.durationMs+=Date.now()-this.turnStartedAt;this.executing=false;this.drainPermissions();this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.flushOpenTools();this.emitter.emit("finish",{subagentId:this.id,terminateReason:this.terminateMode,rounds:this.round,totalDurationMs:this.durationMs,totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,timestamp:Date.now()})}}stopMode(reason){switch(reason){case"end_turn":return"GOAL";case"max_turn_requests":return"MAX_TURNS";case"cancelled":return"CANCELLED";case"refusal":return"ERROR";default:return"ERROR"}}get id(){return this.params.subagentId??this.params.name}getFinalText(){return this.finalText}getTerminateMode(){return this.terminateMode}getCore(){return this.coreView}setExternalMessageProvider(provider){this.provider=provider}getExecutionSummary(){return{rounds:this.round,totalDurationMs:this.durationMs+(this.executing?Date.now()-this.turnStartedAt:0),totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,successRate:this.toolCalls?this.toolSucceeded/this.toolCalls*100:0,inputTokens:0,outputTokens:0,thoughtTokens:0,cachedTokens:0,totalTokens:0,toolUsage:[]}}dispose(){this.disposed=true;this.fail(new Error("External ACP agent disposed"));return this.disposePromise??=this.child.terminate().catch(error=>{if(isUnprovenExternalAgentTreeExit(error)){const detail=error instanceof Error?error.message:String(error);debugLogger.warn(`External ACP agent process tree was not proven gone after disposal: ${detail}`);if(this.emitter.rawListeners("error").length>0){this.emitter.emit("error",{subagentId:this.id,error:`External agent process tree not proven gone after disposal: ${detail}`,timestamp:Date.now()})}return}if(!isExpectedExternalAgentCleanupExit(error))throw error})}drainPermissions(){for(const cancel of this.pendingPermissions.values())cancel();this.pendingPermissions.clear()}onSessionUpdate({sessionId,update}){if(sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted)return;switch(update.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":{const thought=update.sessionUpdate==="agent_thought_chunk";const text=update.content.type==="text"?update.content.text:JSON.stringify(update.content);if(thought)this.thoughtText+=text;else this.finalText+=text;this.emitter.emit("stream_text",{subagentId:this.id,round:this.round,text,thought,timestamp:Date.now()});break}case"tool_call":this.updateTool(update);break;case"tool_call_update":this.updateTool(update);break;default:break}}updateTool(update){if(update._meta?.["toolLifecycle"]!==void 0&&update.status===void 0&&update.content===void 0)return;const callId=update.toolCallId;if(this.finishedTools.has(callId))return;const previous=this.tools.get(callId);const tool={toolCallId:callId,title:previous?.title??"External tool",...previous,...Object.fromEntries(Object.entries(update).filter(([,value])=>value!==null&&value!==void 0))};this.tools.set(callId,tool);const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;if(!previous){this.toolNames.set(callId,name);this.toolCalls++;this.emitter.emit("tool_call",{subagentId:this.id,round:this.round,callId,name,args:isRecord(tool.rawInput)?tool.rawInput:{input:tool.rawInput},description:tool.title,timestamp:Date.now()})}if(tool.status!=="completed"&&tool.status!=="failed")return;this.finishedTools.add(callId);this.tools.delete(callId);const success=tool.status==="completed";if(success)this.toolSucceeded++;else this.toolFailed++;this.toolNames.delete(callId);const response={input:tool.rawInput??null,toolName:reportedName,output:tool.rawOutput??null,content:tool.content??null,status:tool.status};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success,responseParts,resultDisplay:JSON.stringify(tool.rawOutput??tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}flushOpenTools(){for(const[callId,tool]of this.tools){const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;this.toolFailed++;const response={input:tool.rawInput??null,toolName:reportedName,output:null,content:tool.content??null,status:"failed"};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success:false,responseParts,resultDisplay:JSON.stringify(tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}this.tools.clear();this.toolNames.clear()}async onRequestPermission(params){const cancelled={outcome:{outcome:"cancelled"}};const runtime=this.params.runtimeContext;const callId=params.toolCall.toolCallId;const meta=params.toolCall._meta?.["claudeCode"];const name=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:params.toolCall.kind??"external_tool";if(params.sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted||this.pendingPermissions.has(callId)||params.options.length===0||new Set(params.options.map(option=>option.optionId)).size!==params.options.length)return cancelled;if(name.replaceAll("_","").toLowerCase()==="askuserquestion"||runtime.getShouldAvoidPermissionPrompts()||!runtime.isInteractive()&&!runtime.getExperimentalZedIntegration()&&runtime.getInputFormat()!=="stream-json"||this.emitter.rawListeners("tool_waiting_approval").length===0){const rejectOptionId=selectRejectOption(params.options);return rejectOptionId?{outcome:{outcome:"selected",optionId:rejectOptionId}}:cancelled}return new Promise(resolve=>{const finish=__name(optionId=>{if(this.pendingPermissions.get(callId)!==deny)return;this.pendingPermissions.delete(callId);resolve(optionId?{outcome:{outcome:"selected",optionId}}:cancelled)},"finish");const deny=__name(()=>finish(),"deny");this.pendingPermissions.set(callId,deny);try{this.emitter.emit("tool_waiting_approval",{subagentId:this.id,round:this.round,callId,name,args:isRecord(params.toolCall.rawInput)?params.toolCall.rawInput:{},description:params.toolCall.title??"External action",confirmationDetails:{type:"info",title:params.toolCall.title??"External action",prompt:describeExternalAction(params.toolCall),renderPromptAsPlainText:true,hideAlwaysAllow:true},respond:__name(async outcome=>finish(selectPermissionOption(params.options,outcome)??(outcome==="cancel"?selectRejectOption(params.options):void 0)),"respond"),timestamp:Date.now()})}catch{deny()}})}};var acpExternalAgentExecutor={create:__name(params=>AcpSubagentExecutor.create(params),"create")};export{externalModelLabel,describeExternalAction,assertExternalAgentSpawnPlatformSupported,resolvePermissionMode,selectPeerModeId,optionKindForOutcome,selectPermissionOption,selectRejectOption,isExpectedExternalAgentCleanupExit,isUnprovenExternalAgentTreeExit,acpExternalAgentExecutor};
3
+ import{ProcessRegistry}from"./chunk-ESSOEHTE.js";import{createStderrForwarder}from"./chunk-SC6ZKUED.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError,ndJsonStream}from"./chunk-WSOEJTOC.js";import{AgentEventEmitter,renderSubagentSystemPrompt}from"./chunk-LDXZT3SG.js";import{sanitizeChildEnv}from"./chunk-LFKUPU57.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";import{Readable,Writable}from"node:stream";init_esbuild_shims();var INIT_TIMEOUT_MS=1e4;var debugLogger=createDebugLogger("EXTERNAL_AGENT");function externalModelLabel(command){return`external-acp:${command.split(/[\\/]/).pop()??command}`}__name(externalModelLabel,"externalModelLabel");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var EXTERNAL_ACTION_PROMPT_MAX=300;function stripControlChars(value){let out="";for(const ch of value){const code=ch.codePointAt(0)??0;out+=code>=32&&code!==127&&!(code>=128&&code<=159)?ch:" "}return out}__name(stripControlChars,"stripControlChars");function describeExternalAction(toolCall){const title=stripControlChars(toolCall.title??toolCall.kind??"External action");const raw=toolCall.rawInput;if(!isRecord(raw))return title;const detail=stripControlChars(JSON.stringify(raw));const rendered=`${title}: ${detail}`;return rendered.length>EXTERNAL_ACTION_PROMPT_MAX?`${rendered.slice(0,EXTERNAL_ACTION_PROMPT_MAX)}\u2026`:rendered}__name(describeExternalAction,"describeExternalAction");function assertExternalAgentSpawnPlatformSupported(platform=process.platform){if(platform==="win32"){throw new Error("External agents are not supported on Windows in this release: the executor spawn is POSIX-only. An npm-installed adapter resolves to a `.cmd` launcher that cannot be spawned without a shell, and the process-tree reaping is POSIX-specific. Run the external agent on macOS/Linux (or WSL). Windows support is a tracked follow-up.")}}__name(assertExternalAgentSpawnPlatformSupported,"assertExternalAgentSpawnPlatformSupported");function resolvePermissionMode(permissionMode,approvalMode){switch((approvalMode??permissionMode??"").trim().toLowerCase()){case"auto":case"acceptedits":case"auto-edit":return"acceptEdits";case"plan":return"plan";case"bypasspermissions":case"bypass":case"yolo":return"bypass";default:return"default"}}__name(resolvePermissionMode,"resolvePermissionMode");var POLICY_MODE_ALIASES={bypass:["bypassPermissions","yolo"],acceptEdits:["acceptEdits","auto-edit","auto"],plan:["plan"],default:["default"]};function selectPeerModeId(policy,availableModeIds){return POLICY_MODE_ALIASES[policy].find(id=>availableModeIds.includes(id))}__name(selectPeerModeId,"selectPeerModeId");function optionKindForOutcome(outcome){switch(outcome){case"proceed_once":case"proceed_once_and_switch_to_default":return"allow_once";case"proceed_always":case"proceed_always_server":case"proceed_always_tool":case"proceed_always_project":case"proceed_always_user":return"allow_always";case"modify_with_editor":case"cancel":case"restore_previous":return"reject_once";default:{const exhaustive=outcome;void exhaustive;return"reject_once"}}}__name(optionKindForOutcome,"optionKindForOutcome");function selectPermissionOption(options,outcome){if(outcome==="cancel")return void 0;if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}const kind=optionKindForOutcome(outcome);return(options.find(option=>option.kind===kind)??(kind==="allow_always"?options.find(option=>option.kind==="allow_once"):void 0)??options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectPermissionOption,"selectPermissionOption");function selectRejectOption(options){if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}return(options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectRejectOption,"selectRejectOption");function isExpectedExternalAgentCleanupExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited uncleanly during shutdown \(code=[^,]+, signal=[^)]+\)$/.test(error.message)}__name(isExpectedExternalAgentCleanupExit,"isExpectedExternalAgentCleanupExit");function isUnprovenExternalAgentTreeExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited before its initial process-tree snapshot completed$/.test(error.message)}__name(isUnprovenExternalAgentTreeExit,"isUnprovenExternalAgentTreeExit");var ExternalAgentTimeoutError=class extends Error{static{__name(this,"ExternalAgentTimeoutError")}constructor(timeoutMs){super(`External ACP operation timed out after ${timeoutMs}ms`);this.name="ExternalAgentTimeoutError"}};var AcpSubagentExecutor=class _AcpSubagentExecutor{constructor(params,child,emitter){this.params=params;this.child=child;this.emitter=emitter;this.coreView={getEventEmitter:__name(()=>emitter,"getEventEmitter"),modelConfig:{...params.modelConfig,model:externalModelLabel(params.spec.command)}};void child.exited.then(()=>this.fail(new Error(`external agent "${params.name}" exited`)),error=>this.fail(error))}static{__name(this,"AcpSubagentExecutor")}connection;sessionId="";finalText="";thoughtText="";terminateMode="ERROR";round=0;durationMs=0;turnStartedAt=0;toolCalls=0;toolSucceeded=0;toolFailed=0;executing=false;started=false;disposed=false;cancelled=false;disposePromise;provider;pendingPermissions=new Map;tools=new Map;toolNames=new Map;finishedTools=new Set;failure=new AbortController;coreView;static async create(params){assertExternalAgentSpawnPlatformSupported();if(params.runConfig.max_turns!==void 0){throw new Error("External ACP agents cannot enforce max_turns.")}const minutes=params.runConfig.max_time_minutes;if(minutes!==void 0&&(!Number.isFinite(minutes)||minutes<=0||minutes*6e4>2147483647)){throw new Error("External ACP max_time_minutes must be positive, finite, and within the Node timer range.")}const child=spawn(params.spec.command,params.spec.args??[],{cwd:params.runtimeContext.getTargetDir(),stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:true,env:sanitizeChildEnv(process.env)});const tracked=new ProcessRegistry().reserve().attach(child,{ownsProcessTree:true});const executor=new _AcpSubagentExecutor(params,tracked,params.eventEmitter??new AgentEventEmitter);child.on("error",error=>executor.fail(error));child.stdin.on("error",error=>executor.fail(error));child.stdout.on("error",error=>executor.fail(error));const forwarder=createStderrForwarder({prefix:`[external-agent ${params.name}] `});child.stderr.setEncoding("utf8");child.stderr.on("data",forwarder.onData);child.stderr.on("end",forwarder.onEnd);child.stderr.on("error",()=>{});try{executor.connection=new ClientSideConnection(()=>executor.buildClient(),ndJsonStream(Writable.toWeb(child.stdin),Readable.toWeb(child.stdout)));void executor.connection.closed.then(()=>executor.fail(new Error("External ACP connection closed")));await executor.wait(executor.connect(),INIT_TIMEOUT_MS);return executor}catch(error){await executor.dispose();throw error}}buildClient(){return{sessionUpdate:__name(async params=>this.onSessionUpdate(params),"sessionUpdate"),requestPermission:__name(params=>this.onRequestPermission(params),"requestPermission"),readTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/read_text_file")},"readTextFile"),writeTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/write_text_file")},"writeTextFile"),extMethod:__name(async method=>{throw RequestError.methodNotFound(method)},"extMethod"),extNotification:__name(async()=>{},"extNotification")}}async connect(){const initialized=await this.connection.initialize({protocolVersion:PROTOCOL_VERSION,clientCapabilities:{fs:{readTextFile:false,writeTextFile:false}}});if(initialized.protocolVersion!==PROTOCOL_VERSION){throw new Error("Unsupported external ACP protocol version")}const session=await this.connection.newSession({cwd:this.params.runtimeContext.getTargetDir(),mcpServers:[]});if(!session.sessionId)throw new Error("External ACP agent returned no sessionId");this.sessionId=session.sessionId;const policy=resolvePermissionMode(this.params.permissionMode,this.params.approvalMode);const availableIds=session.modes?.availableModes.map(mode=>mode.id)??[];const modeId=selectPeerModeId(policy,availableIds);if(!modeId){throw new Error(`External ACP agent does not advertise any mode for the host's ${policy} approval policy (advertised: ${availableIds.join(", ")||"none"})`)}await this.connection.setSessionMode({sessionId:this.sessionId,modeId})}fail(error){this.failure.abort(error);this.drainPermissions()}async wait(operation,timeoutMs,signal){let timer;let onFailure=__name(()=>{},"onFailure");let onAbort=__name(()=>{},"onAbort");const stopped=new Promise((_resolve,reject)=>{onFailure=__name(()=>reject(this.failure.signal.reason),"onFailure");onAbort=__name(()=>reject(signal?.reason??new Error("External agent cancelled")),"onAbort");this.failure.signal.addEventListener("abort",onFailure,{once:true});signal?.addEventListener("abort",onAbort,{once:true});if(this.failure.signal.aborted)onFailure();if(signal?.aborted)onAbort();if(timeoutMs!==void 0){timer=setTimeout(()=>reject(new ExternalAgentTimeoutError(timeoutMs)),timeoutMs)}});try{return await Promise.race([operation,stopped])}finally{clearTimeout(timer);this.failure.signal.removeEventListener("abort",onFailure);signal?.removeEventListener("abort",onAbort)}}async execute(context,signal,options={}){if(context.get("initial_messages_override")!==void 0){throw new Error("External ACP agents cannot import in-process conversation history")}const continuation=this.started;const system=continuation?"":renderSubagentSystemPrompt(this.params.promptConfig,context,this.params.runtimeContext);const task=String(context.get("task_prompt")??"Get Started!");const catalog=system?this.params.runtimeContext.getAutoMemoryContext():"";await this.runTurn([...system?[{type:"text",text:system}]:[],{type:"text",text:task},...catalog?[{type:"text",text:catalog}]:[]],signal,options,continuation?[task]:void 0)}async executeExternalInputs(inputs,signal,options={}){if(inputs.length===0)return;await this.runTurn(this.inputPrompt(inputs),signal,options,inputs)}inputPrompt(inputs){return inputs.map(input=>({type:"text",text:typeof input==="string"?input:input.text}))}emitInputs(inputs){for(const input of inputs){this.emitter.emit("external_message",{subagentId:this.id,kind:typeof input==="string"?"message":input.kind,text:typeof input==="string"?input:input.text,timestamp:Date.now()})}}async runTurn(prompt,signal,options={},inputs){if(this.executing)throw new Error("External ACP agents do not support concurrent turns");if(this.disposed||this.failure.signal.aborted)throw new Error("External ACP agent is closed");this.executing=true;this.started=true;this.cancelled=false;this.finalText="";this.thoughtText="";this.terminateMode="ERROR";if(options.resetStats!==false){this.round=this.durationMs=this.toolCalls=this.toolSucceeded=this.toolFailed=0}this.tools.clear();this.toolNames.clear();this.finishedTools.clear();this.turnStartedAt=Date.now();const timeoutMs=this.params.runConfig.max_time_minutes===void 0?void 0:this.params.runConfig.max_time_minutes*6e4;const cancel=__name(()=>{this.cancelled=true;this.drainPermissions();void this.connection.cancel({sessionId:this.sessionId}).catch(()=>{})},"cancel");signal?.addEventListener("abort",cancel,{once:true});let timedOut=false;try{this.emitter.emit("start",{subagentId:this.id,name:this.params.name,model:this.coreView.modelConfig.model,tools:[],timestamp:Date.now()});if(signal?.aborted){this.terminateMode="CANCELLED";return}const entryRound=this.round;let next=prompt;do{this.round++;const remaining=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remaining!==void 0&&remaining<=0){this.terminateMode="TIMEOUT";break}if(inputs&&this.round===entryRound+1)this.emitInputs(inputs);const result=await this.wait(this.connection.prompt({sessionId:this.sessionId,prompt:next}),remaining,signal);this.terminateMode=this.stopMode(result.stopReason);if(this.terminateMode!=="GOAL")break;if(signal?.aborted){this.terminateMode="CANCELLED";break}const remainingNext=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remainingNext!==void 0&&remainingNext<=0){this.terminateMode="TIMEOUT";break}const queued=this.provider?.()??[];if(queued.length===0)break;this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.finalText="";this.thoughtText="";this.emitInputs(queued);next=this.inputPrompt(queued)}while(!signal?.aborted);if(signal?.aborted)this.terminateMode="CANCELLED"}catch(error){timedOut=error instanceof ExternalAgentTimeoutError;this.terminateMode=signal?.aborted?"CANCELLED":timedOut?"TIMEOUT":"ERROR";if(this.emitter.rawListeners("error").length>0&&!signal?.aborted){this.emitter.emit("error",{subagentId:this.id,error:error instanceof Error?error.message:String(error),timestamp:Date.now()})}await this.dispose();if(!signal?.aborted&&!timedOut)throw error}finally{signal?.removeEventListener("abort",cancel);this.durationMs+=Date.now()-this.turnStartedAt;this.executing=false;this.drainPermissions();this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.flushOpenTools();this.emitter.emit("finish",{subagentId:this.id,terminateReason:this.terminateMode,rounds:this.round,totalDurationMs:this.durationMs,totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,timestamp:Date.now()})}}stopMode(reason){switch(reason){case"end_turn":return"GOAL";case"max_turn_requests":return"MAX_TURNS";case"cancelled":return"CANCELLED";case"refusal":return"ERROR";default:return"ERROR"}}get id(){return this.params.subagentId??this.params.name}getFinalText(){return this.finalText}getTerminateMode(){return this.terminateMode}getCore(){return this.coreView}setExternalMessageProvider(provider){this.provider=provider}getExecutionSummary(){return{rounds:this.round,totalDurationMs:this.durationMs+(this.executing?Date.now()-this.turnStartedAt:0),totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,successRate:this.toolCalls?this.toolSucceeded/this.toolCalls*100:0,inputTokens:0,outputTokens:0,thoughtTokens:0,cachedTokens:0,totalTokens:0,toolUsage:[]}}dispose(){this.disposed=true;this.fail(new Error("External ACP agent disposed"));return this.disposePromise??=this.child.terminate().catch(error=>{if(isUnprovenExternalAgentTreeExit(error)){const detail=error instanceof Error?error.message:String(error);debugLogger.warn(`External ACP agent process tree was not proven gone after disposal: ${detail}`);if(this.emitter.rawListeners("error").length>0){this.emitter.emit("error",{subagentId:this.id,error:`External agent process tree not proven gone after disposal: ${detail}`,timestamp:Date.now()})}return}if(!isExpectedExternalAgentCleanupExit(error))throw error})}drainPermissions(){for(const cancel of this.pendingPermissions.values())cancel();this.pendingPermissions.clear()}onSessionUpdate({sessionId,update}){if(sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted)return;switch(update.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":{const thought=update.sessionUpdate==="agent_thought_chunk";const text=update.content.type==="text"?update.content.text:JSON.stringify(update.content);if(thought)this.thoughtText+=text;else this.finalText+=text;this.emitter.emit("stream_text",{subagentId:this.id,round:this.round,text,thought,timestamp:Date.now()});break}case"tool_call":this.updateTool(update);break;case"tool_call_update":this.updateTool(update);break;default:break}}updateTool(update){if(update._meta?.["toolLifecycle"]!==void 0&&update.status===void 0&&update.content===void 0)return;const callId=update.toolCallId;if(this.finishedTools.has(callId))return;const previous=this.tools.get(callId);const tool={toolCallId:callId,title:previous?.title??"External tool",...previous,...Object.fromEntries(Object.entries(update).filter(([,value])=>value!==null&&value!==void 0))};this.tools.set(callId,tool);const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;if(!previous){this.toolNames.set(callId,name);this.toolCalls++;this.emitter.emit("tool_call",{subagentId:this.id,round:this.round,callId,name,args:isRecord(tool.rawInput)?tool.rawInput:{input:tool.rawInput},description:tool.title,timestamp:Date.now()})}if(tool.status!=="completed"&&tool.status!=="failed")return;this.finishedTools.add(callId);this.tools.delete(callId);const success=tool.status==="completed";if(success)this.toolSucceeded++;else this.toolFailed++;this.toolNames.delete(callId);const response={input:tool.rawInput??null,toolName:reportedName,output:tool.rawOutput??null,content:tool.content??null,status:tool.status};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success,responseParts,resultDisplay:JSON.stringify(tool.rawOutput??tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}flushOpenTools(){for(const[callId,tool]of this.tools){const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;this.toolFailed++;const response={input:tool.rawInput??null,toolName:reportedName,output:null,content:tool.content??null,status:"failed"};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success:false,responseParts,resultDisplay:JSON.stringify(tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}this.tools.clear();this.toolNames.clear()}async onRequestPermission(params){const cancelled={outcome:{outcome:"cancelled"}};const runtime=this.params.runtimeContext;const callId=params.toolCall.toolCallId;const meta=params.toolCall._meta?.["claudeCode"];const name=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:params.toolCall.kind??"external_tool";if(params.sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted||this.pendingPermissions.has(callId)||params.options.length===0||new Set(params.options.map(option=>option.optionId)).size!==params.options.length)return cancelled;if(name.replaceAll("_","").toLowerCase()==="askuserquestion"||runtime.getShouldAvoidPermissionPrompts()||!runtime.isInteractive()&&!runtime.getExperimentalZedIntegration()&&runtime.getInputFormat()!=="stream-json"||this.emitter.rawListeners("tool_waiting_approval").length===0){const rejectOptionId=selectRejectOption(params.options);return rejectOptionId?{outcome:{outcome:"selected",optionId:rejectOptionId}}:cancelled}return new Promise(resolve=>{const finish=__name(optionId=>{if(this.pendingPermissions.get(callId)!==deny)return;this.pendingPermissions.delete(callId);resolve(optionId?{outcome:{outcome:"selected",optionId}}:cancelled)},"finish");const deny=__name(()=>finish(),"deny");this.pendingPermissions.set(callId,deny);try{this.emitter.emit("tool_waiting_approval",{subagentId:this.id,round:this.round,callId,name,args:isRecord(params.toolCall.rawInput)?params.toolCall.rawInput:{},description:params.toolCall.title??"External action",confirmationDetails:{type:"info",title:params.toolCall.title??"External action",prompt:describeExternalAction(params.toolCall),renderPromptAsPlainText:true,hideAlwaysAllow:true},respond:__name(async outcome=>finish(selectPermissionOption(params.options,outcome)??(outcome==="cancel"?selectRejectOption(params.options):void 0)),"respond"),timestamp:Date.now()})}catch{deny()}})}};var acpExternalAgentExecutor={create:__name(params=>AcpSubagentExecutor.create(params),"create")};export{externalModelLabel,describeExternalAction,assertExternalAgentSpawnPlatformSupported,resolvePermissionMode,selectPeerModeId,optionKindForOutcome,selectPermissionOption,selectRejectOption,isExpectedExternalAgentCleanupExit,isUnprovenExternalAgentTreeExit,acpExternalAgentExecutor};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen