@kern0x1b/penstock-cli 26.10.5 → 26.10.6

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 (194) hide show
  1. package/dist/{chunk-account-C8EHysMH.js → chunk-account-CMvFjqGw.js} +1 -1
  2. package/dist/{chunk-agentFailure-piRAFLGH.js → chunk-agentFailure-BiU8hJ-k.js} +1 -1
  3. package/dist/{chunk-agentLaunch-C5Uo40vv.js → chunk-agentLaunch-CRWlfuXv.js} +1 -1
  4. package/dist/{chunk-agentServe-4O0syoYQ.js → chunk-agentServe-M3jzEiHj.js} +1 -1
  5. package/dist/{chunk-analyze-Brxlb4U1.js → chunk-analyze-CCZJQpbU.js} +1 -1
  6. package/dist/chunk-analyze-D_2dPr5n.js +1 -0
  7. package/dist/chunk-apply-Dmo_XdOA.js +1 -0
  8. package/dist/{chunk-bot-I4kuhjyv.js → chunk-bot-51CfGKVL.js} +3 -3
  9. package/dist/chunk-codeFactSet-BqEOkvBS.js +1 -0
  10. package/dist/{chunk-codeIndex-CzENd6hG.js → chunk-codeIndex-olvCG85q.js} +1 -1
  11. package/dist/{chunk-codeLinks-D-gzUjYv.js → chunk-codeLinks-DW721PAt.js} +1 -1
  12. package/dist/chunk-codeLinks-S_BEJVPa.js +1 -0
  13. package/dist/{chunk-command-BctoT00W.js → chunk-command-B-7DfFou.js} +1 -1
  14. package/dist/chunk-command-CyUljAAc.js +1 -0
  15. package/dist/{chunk-command-Jl1msVwF.js → chunk-command-D7WS1aRl.js} +1 -1
  16. package/dist/chunk-commands-CMEkVxle.js +1 -0
  17. package/dist/{chunk-compose-BV9Jg348.js → chunk-compose-DCAQQndd.js} +1 -1
  18. package/dist/{chunk-connectors-CVfz5pSg.js → chunk-connectors-DG6IqkGl.js} +1 -1
  19. package/dist/{chunk-connectors-eXPldvkc.js → chunk-connectors-UpMjbdpU.js} +1 -1
  20. package/dist/{chunk-context-DPJmldqg.js → chunk-context-B-5CZFAT.js} +1 -1
  21. package/dist/{chunk-convert-B1sgT9kl.js → chunk-convert-B7srqZpZ.js} +1 -1
  22. package/dist/chunk-deploy-CGLF2dB1.js +1 -0
  23. package/dist/{chunk-deploy-DOXu2-8q.js → chunk-deploy-Clj9f2y-.js} +1 -1
  24. package/dist/chunk-diagram-CIy-F5iz.js +1 -0
  25. package/dist/{chunk-diagram-BaVwLa4h.js → chunk-diagram-DYoeuAJx.js} +1 -1
  26. package/dist/{chunk-diagramDefects-7UG_Iwsr.js → chunk-diagramDefects-DlVCfZci.js} +1 -1
  27. package/dist/{chunk-diagrams-6suPQBVQ.js → chunk-diagrams-wnFsPOKv.js} +1 -1
  28. package/dist/{chunk-diff-D1m_eKvv.js → chunk-diff-BJ2sJwcs.js} +1 -1
  29. package/dist/chunk-diff-BelMuQhT.js +1 -0
  30. package/dist/chunk-dispatch-CescmVW-.js +6 -0
  31. package/dist/{chunk-docs-CwY3Ce9M.js → chunk-docs-DzOiA9zg.js} +4 -4
  32. package/dist/{chunk-doctor-m0mnVdDE.js → chunk-doctor-GDNwRCg3.js} +1 -1
  33. package/dist/{chunk-drawing-shRfnrs9.js → chunk-drawing-C2qewK8L.js} +1 -1
  34. package/dist/{chunk-editPreview-BgH1JVOD.js → chunk-editPreview-DGu4slO6.js} +1 -1
  35. package/dist/chunk-export-CDFdw7Eh.js +1 -0
  36. package/dist/{chunk-export-D5kPD4Or.js → chunk-export-DP1Hab-_.js} +1 -1
  37. package/dist/{chunk-facts-DA3Y-k9a.js → chunk-facts-CfA8qH5b.js} +1 -1
  38. package/dist/{chunk-failure-BsimkHy_.js → chunk-failure-BK7fu4Yo.js} +1 -1
  39. package/dist/{chunk-features-BfRg2kR5.js → chunk-features-CiC2Yoej.js} +1 -1
  40. package/dist/chunk-features-Dq1Gvqp3.js +1 -0
  41. package/dist/chunk-folders-BO8qUHUV.js +1 -0
  42. package/dist/{chunk-folders-13vx0i0n.js → chunk-folders-yTMgOqLo.js} +1 -1
  43. package/dist/chunk-formChecks-BOiD8Idv.js +1 -0
  44. package/dist/chunk-help-DKtpVSxI.js +85 -0
  45. package/dist/chunk-importCommand-_CnKIoNk.js +1 -0
  46. package/dist/{chunk-init-AIh_7yE0.js → chunk-init-3zEab7KI.js} +3 -3
  47. package/dist/chunk-license-Cvnp1Aee.js +1 -0
  48. package/dist/{chunk-license-x3oHbKe2.js → chunk-license-DU4P8P8A.js} +1 -1
  49. package/dist/{chunk-lint-C_fAcLIg.js → chunk-lint-Df2davEY.js} +1 -1
  50. package/dist/{chunk-load-BVJUBU5S.js → chunk-load-CRmIvn7e.js} +1 -1
  51. package/dist/chunk-main-BY7JEoe1.js +1 -0
  52. package/dist/chunk-mcp-DKX2xT8d.js +77 -0
  53. package/dist/{chunk-mcpLaunch-C13ViiIP.js → chunk-mcpLaunch-DpDE0hW-.js} +1 -1
  54. package/dist/chunk-migrate-BaNzQNyD.js +2 -0
  55. package/dist/chunk-migrate-DcxIkacG.js +1 -0
  56. package/dist/{chunk-penstockCli-CqiOKC75.js → chunk-penstockCli-B0_wWDGy.js} +1 -1
  57. package/dist/chunk-plural-Di3FH8HP.js +1 -0
  58. package/dist/{chunk-pr-tC3-PSNM.js → chunk-pr-DXs1coaS.js} +1 -1
  59. package/dist/{chunk-project-qT-Fk_Rz.js → chunk-project-BS-4dy5o.js} +1 -1
  60. package/dist/{chunk-report-CDz78nCI.js → chunk-report-CtkTRSGT.js} +1 -1
  61. package/dist/{chunk-review-BqZSohXR.js → chunk-review-WIpFGKkc.js} +1 -1
  62. package/dist/{chunk-rules-DJlL7K_Q.js → chunk-rules-CoJAmvwu.js} +1 -1
  63. package/dist/{chunk-security-5SU-bq3A.js → chunk-security-BKVRwb6V.js} +10 -10
  64. package/dist/{chunk-share-YSewfw3F.js → chunk-share-B3W30sbt.js} +3 -3
  65. package/dist/chunk-src-CxTpK8wk.js +890 -0
  66. package/dist/{chunk-stages-C-nhLoBW.js → chunk-stages-Gm5BZUp5.js} +1 -1
  67. package/dist/chunk-status-X9Ny-Nu8.js +1 -0
  68. package/dist/{chunk-systemError-B-1nL94i.js → chunk-systemError-F6bMRwXU.js} +1 -1
  69. package/dist/chunk-systemError-cGwrYkmo.js +1 -0
  70. package/dist/{chunk-table-CJtiXv0e.js → chunk-table-B2WTbpMl.js} +1 -1
  71. package/dist/chunk-taskTest-B3gfOti1.js +1 -0
  72. package/dist/{chunk-taskTest-4rIxp0rL.js → chunk-taskTest-D-WDCLD5.js} +2 -2
  73. package/dist/{chunk-templates-Bxe3J0qy.js → chunk-templates-BdsiNRJ3.js} +1 -1
  74. package/dist/chunk-testCases-ba8k3BJD.js +4 -0
  75. package/dist/chunk-testCases-gXzkCxF5.js +1 -0
  76. package/dist/chunk-tests-BLBZ1eh2.js +1 -0
  77. package/dist/chunk-tests-DxL0JMtB.js +23 -0
  78. package/dist/chunk-translator-BAjzyPKE.js +22 -0
  79. package/dist/{chunk-trust-u1vZ6Yk0.js → chunk-trust-Ci9pDa27.js} +1 -1
  80. package/dist/{chunk-trust-yKw_pXRj.js → chunk-trust-DlJIoKs8.js} +1 -1
  81. package/dist/{chunk-workerVariables-CCLcoR0U.js → chunk-workerVariables-BnLSud8o.js} +1 -1
  82. package/dist/{chunk-wrapper-AJWl6ru-.js → chunk-wrapper-DqqRt0FZ.js} +1 -1
  83. package/dist/chunk-wrapper-E_u1_-Db.js +1 -0
  84. package/dist/locales/de.json +103 -2
  85. package/dist/locales/es.json +103 -2
  86. package/dist/locales/fr.json +103 -2
  87. package/dist/locales/ja.json +103 -2
  88. package/dist/locales/ko.json +103 -2
  89. package/dist/locales/pt-BR.json +103 -2
  90. package/dist/locales/ru.json +103 -2
  91. package/dist/locales/zh.json +103 -2
  92. package/dist/penstock.js +1 -1
  93. package/dist/web/assets/{AgentSettings-C3Er_rlW.js → AgentSettings-4B4hSxBk.js} +1 -1
  94. package/dist/web/assets/{AgentsDialog-Bo7kikb6.js → AgentsDialog-C32ALLtE.js} +1 -1
  95. package/dist/web/assets/{BpmnCanvas-Dw5zgCN3.js → BpmnCanvas-CZOJiq6t.js} +1 -1
  96. package/dist/web/assets/{BpmnDocument-CuU0biX9.js → BpmnDocument-BNLfXWLG.js} +4 -4
  97. package/dist/web/assets/{ConflictDialog-GxZ-d8SK.js → ConflictDialog-mUJYs1zz.js} +1 -1
  98. package/dist/web/assets/{DiffDocument-Bh3hFmmi.js → DiffDocument-C7csJl3x.js} +1 -1
  99. package/dist/web/assets/{DmnDocument-C8HpJAcE.js → DmnDocument-B2dyX49k.js} +1 -1
  100. package/dist/web/assets/{FormDocument-CH-4KB3x.js → FormDocument-ChSqEPE5.js} +1 -1
  101. package/dist/web/assets/{FormStepView-DraPVoAN.js → FormStepView-j4C0Qovo.js} +1 -1
  102. package/dist/web/assets/{GraphAwareLayoutService-C8J8YHJI.js → GraphAwareLayoutService-DD2iXfXi.js} +1 -1
  103. package/dist/web/assets/{NewFileDialog-j09JqpPj.js → NewFileDialog-eeIqqmXc.js} +1 -1
  104. package/dist/web/assets/{QuickOpen-CeBhsCzA.js → QuickOpen-C0I0FRt2.js} +1 -1
  105. package/dist/web/assets/{ScriptPane-DDikZDv6.js → ScriptPane-BAvcgLWX.js} +2 -2
  106. package/dist/web/assets/{ScriptRunDialog-DdzJ0pvT.js → ScriptRunDialog-DLlMiJiK.js} +1 -1
  107. package/dist/web/assets/{SettingsDialog-JUc5zUR9.js → SettingsDialog-C3ts5aiN.js} +1 -1
  108. package/dist/web/assets/{ShortcutsDialog-DECqWPNE.js → ShortcutsDialog-DVV504pS.js} +1 -1
  109. package/dist/web/assets/{SourceDocument-X8ajUcxM.js → SourceDocument-DRgUPazk.js} +1 -1
  110. package/dist/web/assets/{TextDocument-0z7qojAh.js → TextDocument-Bm0sPjft.js} +1 -1
  111. package/dist/web/assets/{UnreadableFileLayer-D3G59F4u.js → UnreadableFileLayer-DbW33CnE.js} +1 -1
  112. package/dist/web/assets/{UploadDialog-CiahYkTc.js → UploadDialog-BSl3zFNn.js} +1 -1
  113. package/dist/web/assets/{apply-HqvoGwLE.js → apply-B3FkgxjU.js} +1 -1
  114. package/dist/web/assets/{bpmnTheme-cOvp4qFc.js → bpmnTheme-C3HdVV1D.js} +1 -1
  115. package/dist/web/assets/bridgeInstance-BZBhe5hF.js +851 -0
  116. package/dist/web/assets/{commands-nPznxvPp.js → commands-DHPxsavW.js} +1 -1
  117. package/dist/web/assets/de-BH_bnU4H.js +1 -0
  118. package/dist/web/assets/{dialog-CtGB1LHI.js → dialog-LcHsiQKJ.js} +1 -1
  119. package/dist/web/assets/{diff-NgYeO98t.js → diff-bpdDl0KE.js} +1 -1
  120. package/dist/web/assets/{documentBridge-QW0IZ9Bq.js → documentBridge-4fZNBdp4.js} +2 -2
  121. package/dist/web/assets/{documents-KeXEdK1U.js → documents-FOVGbYYF.js} +1 -1
  122. package/dist/web/assets/{duplicate-DNPpPVse.js → duplicate-CdCuOnUl.js} +1 -1
  123. package/dist/web/assets/{engines-DU0BfbYM.js → engines-C884tl-T.js} +1 -1
  124. package/dist/web/assets/es-D7v7zkxC.js +1 -0
  125. package/dist/web/assets/{formChecks-sU20kKkU.js → formChecks-Bvuzw2sb.js} +1 -1
  126. package/dist/web/assets/fr-CuzAJTai.js +1 -0
  127. package/dist/web/assets/frontend-Y1MvD_Uo.js +1 -0
  128. package/dist/web/assets/httpHost-CnF86WJB.js +1 -0
  129. package/dist/web/assets/{index.es-BqVUpGyA.js → index.es-0rLw__5_.js} +1 -1
  130. package/dist/web/assets/{index.es-DqkfrvWI.js → index.es-BP1Cc_0e.js} +1 -1
  131. package/dist/web/assets/{intelligence-Ck_Q9upa.js → intelligence-E2EBYhHr.js} +1 -1
  132. package/dist/web/assets/ja-BgElyPpa.js +1 -0
  133. package/dist/web/assets/{jspdf.es.min-CM3S4IDt.js → jspdf.es.min-BSRrqhq_.js} +3 -3
  134. package/dist/web/assets/ko-j1Oi9MKH.js +1 -0
  135. package/dist/web/assets/{lib-DAKOOgix.js → lib-De3fPoUi.js} +1 -1
  136. package/dist/web/assets/{platform-CkWAyNst.js → platform-CjEV0T5t.js} +1 -1
  137. package/dist/web/assets/{preferences-nBrFGN89.js → preferences-CmXdxfFo.js} +1 -1
  138. package/dist/web/assets/pt-BR-CRWG2th4.js +1 -0
  139. package/dist/web/assets/ru-KJyuYSUL.js +1 -0
  140. package/dist/web/assets/{run-B3YvrVeP.js → run-B9EUa035.js} +1 -1
  141. package/dist/web/assets/{samples-BVuIm-bu.js → samples-03zukOEM.js} +1 -1
  142. package/dist/web/assets/{testCaseRuns-DYKnccnc.js → testCaseRuns-BYhJPipg.js} +1 -1
  143. package/dist/web/assets/translator-OIpY8kTG.js +1 -0
  144. package/dist/web/assets/{ui-3pEQJ50t.js → ui-BLMlfdD3.js} +1 -1
  145. package/dist/web/assets/{useTrace-BAXnn0Bt.js → useTrace-Cr28sh4A.js} +1 -1
  146. package/dist/web/assets/{web-B2zkonPE.js → web-Q9VZNxQi.js} +5 -5
  147. package/dist/web/assets/zh-CukDLcVz.js +1 -0
  148. package/dist/web/index.html +19 -19
  149. package/package.json +1 -1
  150. package/dist/chunk-analyze-CUxuBgNS.js +0 -1
  151. package/dist/chunk-apply-BAMwoXG9.js +0 -1
  152. package/dist/chunk-baseline-DvS2S0am.js +0 -1
  153. package/dist/chunk-codeFactSet-DOOlbIIj.js +0 -1
  154. package/dist/chunk-codeLinks-DLxEBWPi.js +0 -1
  155. package/dist/chunk-command-BR4memGJ.js +0 -1
  156. package/dist/chunk-commands-CeRlfHY-.js +0 -1
  157. package/dist/chunk-deploy-C4KJK-tw.js +0 -1
  158. package/dist/chunk-diagram-CCA1-fT5.js +0 -1
  159. package/dist/chunk-diff-BC8gZX5w.js +0 -1
  160. package/dist/chunk-dispatch-CW2CJI0C.js +0 -6
  161. package/dist/chunk-export-9AWsr5ai.js +0 -1
  162. package/dist/chunk-features-BwnwB6jL.js +0 -1
  163. package/dist/chunk-folders-C1Nes4Ap.js +0 -1
  164. package/dist/chunk-formChecks-acRgARZ3.js +0 -1
  165. package/dist/chunk-help-CFhmAhz8.js +0 -85
  166. package/dist/chunk-importCommand-5SJxu2k4.js +0 -1
  167. package/dist/chunk-license-B_To2110.js +0 -1
  168. package/dist/chunk-main-D3S4Xr__.js +0 -1
  169. package/dist/chunk-mcp-ByMCWlXC.js +0 -76
  170. package/dist/chunk-migrate-CLQ-hrae.js +0 -1
  171. package/dist/chunk-migrate-CVUR1K7f.js +0 -1
  172. package/dist/chunk-plural-Bq_4vgOr.js +0 -1
  173. package/dist/chunk-src-BLyg_6UX.js +0 -879
  174. package/dist/chunk-status-DgeSOz3A.js +0 -1
  175. package/dist/chunk-systemError-2me5k57V.js +0 -1
  176. package/dist/chunk-taskTest-rng12v_b.js +0 -1
  177. package/dist/chunk-testCases-CwQ-Mi7L.js +0 -1
  178. package/dist/chunk-testCases-xculyxH_.js +0 -4
  179. package/dist/chunk-tests-C-kNQNpq.js +0 -1
  180. package/dist/chunk-tests-C3XJ9LMT.js +0 -23
  181. package/dist/chunk-translator-BFUJmSkR.js +0 -21
  182. package/dist/chunk-wrapper-Bxz1Lgp5.js +0 -1
  183. package/dist/web/assets/bridgeInstance-DQk-c8L1.js +0 -850
  184. package/dist/web/assets/de-Dj813wjn.js +0 -1
  185. package/dist/web/assets/es-CyJDEw4H.js +0 -1
  186. package/dist/web/assets/fr-B1lqrd3d.js +0 -1
  187. package/dist/web/assets/frontend-caI7mOAL.js +0 -1
  188. package/dist/web/assets/httpHost-Dqit__mm.js +0 -1
  189. package/dist/web/assets/ja-BUAM_DzQ.js +0 -1
  190. package/dist/web/assets/ko-7l4EjTF9.js +0 -1
  191. package/dist/web/assets/pt-BR-CxxRL7kF.js +0 -1
  192. package/dist/web/assets/ru-C4gbkVXL.js +0 -1
  193. package/dist/web/assets/translator-B2N3PQBL.js +0 -1
  194. package/dist/web/assets/zh-DIYPlVjz.js +0 -1
@@ -1 +1 @@
1
- import{_ as e,a as t,b as n,c as r,d as i,g as a,i as o,l as s,n as c,s as l,u,v as d,y as f}from"./chunk-license-x3oHbKe2.js";import{r as p}from"./chunk-translator-BFUJmSkR.js";import{n as m}from"./chunk-features-BfRg2kR5.js";import{t as h}from"./chunk-table-CJtiXv0e.js";import{spawn as g}from"node:child_process";import{createInterface as _}from"node:readline/promises";function v(e){return e.ask?e.ask:async e=>{let t=_({input:process.stdin,output:process.stderr});try{return(await t.question(e)).trim()}finally{t.close()}}}function y(e){return e.say??(e=>process.stderr.write(`${e}\n`))}const b=/["\u0000-\u001f]/;function x(e,t=process.platform){let n;try{n=new URL(e).protocol}catch{return null}return n!==`http:`&&n!==`https:`||b.test(e)?null:t===`darwin`?{command:`open`,args:[e],verbatim:!1}:t===`win32`?{command:`cmd`,args:[`/c`,`start`,`""`,`"${e}"`],verbatim:!0}:{command:`xdg-open`,args:[e],verbatim:!1}}function S(e){let t=x(e);if(t)try{g(t.command,t.args,{stdio:`ignore`,detached:!0,windowsVerbatimArguments:t.verbatim}).unref()}catch{return}}function C(e){return e.interactive??(process.stdin.isTTY===!0&&process.stderr.isTTY===!0)}function w(){return[p(`app.cli.license.notInteractive`)]}async function T(e,t){let n=v(t),i=y(t);await f(e,t),i(p(`app.cli.license.codeOnItsWay`,{email:e}));let a=null;for(let e=0;e<3&&!a;e+=1){let e=await n(p(`app.cli.license.codeQuestion`));if(!e)return null;try{a=await r(e,t)}catch(e){if(!(e instanceof c))throw e;i(e.message)}}return a}async function E(e,t){let n=v(t),r=y(t),i=await T(e,t);if(!i)return{ok:!1,lines:[p(`app.cli.license.nothingChangedAgain`)]};let a=await s(i,t);for(;a.kind===`full`;){let e=(t.now??Date.now)();r(p(`app.cli.license.tooManyMachines`,{tier:o[a.key.tier],machines:a.activations.length}));let c=a.activations.map((t,n)=>({num:`${n+1}.`,machine:t.label,since:p(`app.cli.license.since`,{when:l(t.createdAt,e)})}));h(c,{columns:[{name:`num`,align:`right`,minWidth:2},{name:`machine`,minWidth:16},{name:`since`,minWidth:14}],headers:!1}).forEach(e=>r(` ${e}`));let u=await n(p(`app.cli.license.freeWhich`)),f=a.activations[Number(u)-1];if(!f)return{ok:!1,lines:[p(`app.cli.nothingChanged`)]};await d(a.key.key,f.id,t),a=await s(i,t)}return a.kind===`none`?{ok:!1,lines:[p(`app.cli.license.noneBought`,{email:e}),p(`app.cli.license.buyOrSignIn`)]}:{ok:!0,lines:[p(`app.cli.license.activeHere`,{tier:o[a.tier],again:a.reused?p(`app.cli.license.again`):``})]}}async function D(e,t={}){if(!C(t))return{ok:!1,lines:w()};try{let n=e[0]??await v(t)(p(`app.cli.license.emailQuestion`));return n?await E(n,t):{ok:!1,lines:[p(`app.cli.nothingChanged`)]}}catch(e){return N(e)}}async function O(t,r={}){let i=t[0]??`pro`;if(i!==`pro`&&i!==`team`)return{ok:!1,lines:[p(`app.cli.license.buyUsage`)]};if(!C(r))return{ok:!1,lines:w()};let a=y(r),s=r.wait??(e=>new Promise(t=>setTimeout(t,e)));try{let t=await u(r);if(t.source===`activation`&&t.tier===i)return{ok:!0,lines:[p(`app.cli.license.alreadyActive`,{tier:o[i]})]};let l=await n(i,void 0,r);(r.open??S)(l.url),a(p(`app.cli.license.checkoutOpen`,{tier:o[i]})),a(` ${l.url}`),a(p(`app.cli.license.waitingForPayment`));let d=(r.now??Date.now)()+36e5,f=0;for(;(r.now??Date.now)()<d;){let t;try{t=await e(l.secret,r),f=0}catch(e){if(e instanceof c||(f+=1)>5)throw e;await s(3e3);continue}if(t.status===`succeeded`){let e=t.email??await v(r)(p(`app.cli.license.paidEmailQuestion`));return a(p(`app.cli.license.paid`)),await E(e,r)}if(t.status===`failed`)return{ok:!1,lines:[p(`app.cli.license.paymentFailed`)]};if(t.status===`expired`)return{ok:!1,lines:[p(`app.cli.license.checkoutExpired`)]};await s(3e3)}return{ok:!1,lines:[p(`app.cli.license.stoppedWaiting`)]}}catch(e){return N(e)}}async function k(e={}){try{let t=await i(e);return t===`released`?{ok:!0,lines:[p(`app.cli.license.released`)]}:t===`cleared`?{ok:!0,lines:[p(`app.cli.license.cleared`)]}:{ok:!1,lines:[p(`app.cli.license.nothingToRelease`)]}}catch(e){return N(e)}}function A(e){let t=e.trialEndsAt?.slice(0,10);return e.source===`trial`&&t?{ok:!1,lines:[p(`app.cli.license.trial`,{left:/\d+ days? left/.exec(e.detail)?.[0]??p(`app.cli.license.running`),ends:t}),p(`app.cli.license.keyComesWithPurchase`),p(`app.cli.license.enterAKey`)]}:{ok:!1,lines:[p(`app.cli.license.noneOnThisMachine`,{trial:t?p(`app.cli.license.trialEnded`,{ends:t}):``}),p(`app.cli.license.orBuyOne`)]}}async function j(e,t){let n=await u(t);if(n.source!==`activation`)return A(n);if(!C(t))return{ok:!1,lines:w()};let r=e??await v(t)(p(`app.cli.license.emailQuestion`));if(!r)return{ok:!1,lines:[p(`app.cli.nothingChanged`)]};let i=await T(r,t);if(!i)return{ok:!1,lines:[p(`app.cli.license.nothingChangedAgain`)]};let s=await a(i,t);if(s.length===0)return{ok:!1,lines:[p(`app.cli.license.noneBought`,{email:r})]};let c=s.filter(e=>e.tier===`team`);return c.length===0?{ok:!1,lines:[p(`app.cli.license.teamOnly`),p(`app.cli.license.buyTeam`)]}:{ok:!0,lines:[...c.map(e=>`${o[e.tier].padEnd(5)} ${e.key}`),``,p(`app.cli.license.keepKeySecret`)]}}async function M(e,n={}){let[r,i]=e;try{switch(r){case`activate`:{if(!i)return{ok:!1,lines:[p(`app.cli.license.activateUsage`)]};await t(i,n);let e=await u(n);return{ok:!0,lines:[p(`app.cli.license.activeHerePlain`,{tier:o[e.tier]})]}}case`deactivate`:return await k(n);case`key`:return await j(i,n);case void 0:case`status`:{let e=await u(n),t=[{property:p(`app.cli.license.tierRow`),value:o[e.tier]},{property:p(`app.cli.license.statusRow`),value:e.detail}],r=h(t,{columns:[{name:`property`,header:p(`app.cli.header.property`),minWidth:10},{name:`value`,header:p(`app.cli.header.value`)}],headers:!1});if(e.tier===`free`||e.source===`trial`){r.push(``,p(`app.cli.license.buyAndSignIn`));let e=m();e&&r.push(e)}return{ok:!0,lines:r}}default:return{ok:!1,lines:[p(`app.cli.license.usage`)]}}}catch(e){return N(e)}}function N(e){return e instanceof c?{ok:!1,lines:[e.message]}:{ok:!1,lines:[p(`app.cli.license.serviceUnreachable`,{reason:e instanceof Error?e.message:String(e)})]}}export{M as licenseCommand,D as loginCommand,k as logoutCommand,O as upgradeCommand};
1
+ import{_ as e,a as t,b as n,c as r,d as i,g as a,i as o,l as s,n as c,s as l,u,v as d,y as f}from"./chunk-license-DU4P8P8A.js";import{r as p}from"./chunk-translator-BAjzyPKE.js";import{n as m}from"./chunk-features-CiC2Yoej.js";import{t as h}from"./chunk-table-B2WTbpMl.js";import{spawn as g}from"node:child_process";import{createInterface as _}from"node:readline/promises";function v(e){return e.ask?e.ask:async e=>{let t=_({input:process.stdin,output:process.stderr});try{return(await t.question(e)).trim()}finally{t.close()}}}function y(e){return e.say??(e=>process.stderr.write(`${e}\n`))}const b=/["\u0000-\u001f]/;function x(e,t=process.platform){let n;try{n=new URL(e).protocol}catch{return null}return n!==`http:`&&n!==`https:`||b.test(e)?null:t===`darwin`?{command:`open`,args:[e],verbatim:!1}:t===`win32`?{command:`cmd`,args:[`/c`,`start`,`""`,`"${e}"`],verbatim:!0}:{command:`xdg-open`,args:[e],verbatim:!1}}function S(e){let t=x(e);if(t)try{g(t.command,t.args,{stdio:`ignore`,detached:!0,windowsVerbatimArguments:t.verbatim}).unref()}catch{return}}function C(e){return e.interactive??(process.stdin.isTTY===!0&&process.stderr.isTTY===!0)}function w(){return[p(`app.cli.license.notInteractive`)]}async function T(e,t){let n=v(t),i=y(t);await f(e,t),i(p(`app.cli.license.codeOnItsWay`,{email:e}));let a=null;for(let e=0;e<3&&!a;e+=1){let e=await n(p(`app.cli.license.codeQuestion`));if(!e)return null;try{a=await r(e,t)}catch(e){if(!(e instanceof c))throw e;i(e.message)}}return a}async function E(e,t){let n=v(t),r=y(t),i=await T(e,t);if(!i)return{ok:!1,lines:[p(`app.cli.license.nothingChangedAgain`)]};let a=await s(i,t);for(;a.kind===`full`;){let e=(t.now??Date.now)();r(p(`app.cli.license.tooManyMachines`,{tier:o[a.key.tier],machines:a.activations.length}));let c=a.activations.map((t,n)=>({num:`${n+1}.`,machine:t.label,since:p(`app.cli.license.since`,{when:l(t.createdAt,e)})}));h(c,{columns:[{name:`num`,align:`right`,minWidth:2},{name:`machine`,minWidth:16},{name:`since`,minWidth:14}],headers:!1}).forEach(e=>r(` ${e}`));let u=await n(p(`app.cli.license.freeWhich`)),f=a.activations[Number(u)-1];if(!f)return{ok:!1,lines:[p(`app.cli.nothingChanged`)]};await d(a.key.key,f.id,t),a=await s(i,t)}return a.kind===`none`?{ok:!1,lines:[p(`app.cli.license.noneBought`,{email:e}),p(`app.cli.license.buyOrSignIn`)]}:{ok:!0,lines:[p(`app.cli.license.activeHere`,{tier:o[a.tier],again:a.reused?p(`app.cli.license.again`):``})]}}async function D(e,t={}){if(!C(t))return{ok:!1,lines:w()};try{let n=e[0]??await v(t)(p(`app.cli.license.emailQuestion`));return n?await E(n,t):{ok:!1,lines:[p(`app.cli.nothingChanged`)]}}catch(e){return N(e)}}async function O(t,r={}){let i=t[0]??`pro`;if(i!==`pro`&&i!==`team`)return{ok:!1,lines:[p(`app.cli.license.buyUsage`)]};if(!C(r))return{ok:!1,lines:w()};let a=y(r),s=r.wait??(e=>new Promise(t=>setTimeout(t,e)));try{let t=await u(r);if(t.source===`activation`&&t.tier===i)return{ok:!0,lines:[p(`app.cli.license.alreadyActive`,{tier:o[i]})]};let l=await n(i,void 0,r);(r.open??S)(l.url),a(p(`app.cli.license.checkoutOpen`,{tier:o[i]})),a(` ${l.url}`),a(p(`app.cli.license.waitingForPayment`));let d=(r.now??Date.now)()+36e5,f=0;for(;(r.now??Date.now)()<d;){let t;try{t=await e(l.secret,r),f=0}catch(e){if(e instanceof c||(f+=1)>5)throw e;await s(3e3);continue}if(t.status===`succeeded`){let e=t.email??await v(r)(p(`app.cli.license.paidEmailQuestion`));return a(p(`app.cli.license.paid`)),await E(e,r)}if(t.status===`failed`)return{ok:!1,lines:[p(`app.cli.license.paymentFailed`)]};if(t.status===`expired`)return{ok:!1,lines:[p(`app.cli.license.checkoutExpired`)]};await s(3e3)}return{ok:!1,lines:[p(`app.cli.license.stoppedWaiting`)]}}catch(e){return N(e)}}async function k(e={}){try{let t=await i(e);return t===`released`?{ok:!0,lines:[p(`app.cli.license.released`)]}:t===`cleared`?{ok:!0,lines:[p(`app.cli.license.cleared`)]}:{ok:!1,lines:[p(`app.cli.license.nothingToRelease`)]}}catch(e){return N(e)}}function A(e){let t=e.trialEndsAt?.slice(0,10);return e.source===`trial`&&t?{ok:!1,lines:[p(`app.cli.license.trial`,{left:/\d+ days? left/.exec(e.detail)?.[0]??p(`app.cli.license.running`),ends:t}),p(`app.cli.license.keyComesWithPurchase`),p(`app.cli.license.enterAKey`)]}:{ok:!1,lines:[p(`app.cli.license.noneOnThisMachine`,{trial:t?p(`app.cli.license.trialEnded`,{ends:t}):``}),p(`app.cli.license.orBuyOne`)]}}async function j(e,t){let n=await u(t);if(n.source!==`activation`)return A(n);if(!C(t))return{ok:!1,lines:w()};let r=e??await v(t)(p(`app.cli.license.emailQuestion`));if(!r)return{ok:!1,lines:[p(`app.cli.nothingChanged`)]};let i=await T(r,t);if(!i)return{ok:!1,lines:[p(`app.cli.license.nothingChangedAgain`)]};let s=await a(i,t);if(s.length===0)return{ok:!1,lines:[p(`app.cli.license.noneBought`,{email:r})]};let c=s.filter(e=>e.tier===`team`);return c.length===0?{ok:!1,lines:[p(`app.cli.license.teamOnly`),p(`app.cli.license.buyTeam`)]}:{ok:!0,lines:[...c.map(e=>`${o[e.tier].padEnd(5)} ${e.key}`),``,p(`app.cli.license.keepKeySecret`)]}}async function M(e,n={}){let[r,i]=e;try{switch(r){case`activate`:{if(!i)return{ok:!1,lines:[p(`app.cli.license.activateUsage`)]};await t(i,n);let e=await u(n);return{ok:!0,lines:[p(`app.cli.license.activeHerePlain`,{tier:o[e.tier]})]}}case`deactivate`:return await k(n);case`key`:return await j(i,n);case void 0:case`status`:{let e=await u(n),t=[{property:p(`app.cli.license.tierRow`),value:o[e.tier]},{property:p(`app.cli.license.statusRow`),value:e.detail}],r=h(t,{columns:[{name:`property`,header:p(`app.cli.header.property`),minWidth:10},{name:`value`,header:p(`app.cli.header.value`)}],headers:!1});if(e.tier===`free`||e.source===`trial`){r.push(``,p(`app.cli.license.buyAndSignIn`));let e=m();e&&r.push(e)}return{ok:!0,lines:r}}default:return{ok:!1,lines:[p(`app.cli.license.usage`)]}}}catch(e){return N(e)}}function N(e){return e instanceof c?{ok:!1,lines:[e.message]}:{ok:!1,lines:[p(`app.cli.license.serviceUnreachable`,{reason:e instanceof Error?e.message:String(e)})]}}export{M as licenseCommand,D as loginCommand,k as logoutCommand,O as upgradeCommand};
@@ -1 +1 @@
1
- import{r as e}from"./chunk-translator-BFUJmSkR.js";const t=[/\b(?:sk|pk|rk)[-_][-_A-Za-z0-9]{12,}/g,/\b(?:xox[abprs]|ghp|gho|ghu|ghs|github_pat|glpat|AKIA|AIza)[-_A-Za-z0-9]{12,}/g,/\bnpm_[A-Za-z0-9]{20,}/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,/\b([A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)[A-Za-z0-9_]*)["']?\s*[=:]\s*["']?\S+/gi,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*/g],n=[[/(:\/\/[^\s/:@]+:)[^\s/@]+@/g,`$1***@`],[/(authorization["']?\s*[:=]\s*)(?:basic|bearer)\s+\S+/gi,`$1***`]];function r(e){let r=e.replace(/[\u0000-\u0008\u000b-\u001f\u007f]+/g,` `);for(let[e,t]of n)r=r.replace(e,t);for(let e of t)r=r.replace(e,(e,t)=>typeof t==`string`&&/[=:]/.test(e)?`${t}=***`:`***`);return r}function i(e){return r(e).slice(0,200)}function a(e){return r(e).trim().slice(-200)}const o=`app.agent.exited`,s=`app.agent.installFailed`,c=`app.agent.npmMissing`,l=`app.agent.unpublished`,u=`app.agent.serviceExited`,d=`app.agent.serviceNotStarted`,f=/\bnpm (?:error|ERR!)|\b(?:ETARGET|E404|ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ETIMEDOUT)\b/i,p=/\bETARGET\b|\bE404\b|No matching version found/i,m=/\bneeds Node\.js\b|\bnot recognized as an internal or external command\b|\b(?:npm|npx|node): (?:command )?not found\b|\bcommand not found: (?:npm|npx|node)\b/i,h=/* @__PURE__ */ new Set([o,s,c,l,u,d]);function g(e){return f.test(e)?s:o}function _(e){return p.test(e)?l:m.test(e)?c:f.test(e)?s:u}function v(e){return e!==0}function y(t){switch(t.kind){case`timeout`:return{key:`app.agent.timeout`,detail:``};case`spawn`:return{key:t.code===`ENOENT`?c:d,detail:a(t.message)};case`exited`:{let n=t.code===null?`signal ${t.signal??`unknown`}`:e(`app.agent.exitCode`,{code:t.code}),r=a(t.tail);return{key:_(t.tail),detail:r===``?n:`${n}: ${r}`}}}}function b(e){return h.has(e)}function x(t){return b(t.key)?e(t.key):e(t.key,{detail:t.detail})}export{y as a,x as i,v as n,i as o,g as r,l as t};
1
+ import{r as e}from"./chunk-translator-BAjzyPKE.js";const t=[/\b(?:sk|pk|rk)[-_][-_A-Za-z0-9]{12,}/g,/\b(?:xox[abprs]|ghp|gho|ghu|ghs|github_pat|glpat|AKIA|AIza)[-_A-Za-z0-9]{12,}/g,/\bnpm_[A-Za-z0-9]{20,}/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,/\b([A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)[A-Za-z0-9_]*)["']?\s*[=:]\s*["']?\S+/gi,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*/g],n=[[/(:\/\/[^\s/:@]+:)[^\s/@]+@/g,`$1***@`],[/(authorization["']?\s*[:=]\s*)(?:basic|bearer)\s+\S+/gi,`$1***`]];function r(e){let r=e.replace(/[\u0000-\u0008\u000b-\u001f\u007f]+/g,` `);for(let[e,t]of n)r=r.replace(e,t);for(let e of t)r=r.replace(e,(e,t)=>typeof t==`string`&&/[=:]/.test(e)?`${t}=***`:`***`);return r}function i(e){return r(e).slice(0,200)}function a(e){return r(e).trim().slice(-200)}const o=`app.agent.exited`,s=`app.agent.installFailed`,c=`app.agent.npmMissing`,l=`app.agent.unpublished`,u=`app.agent.serviceExited`,d=`app.agent.serviceNotStarted`,f=/\bnpm (?:error|ERR!)|\b(?:ETARGET|E404|ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ETIMEDOUT)\b/i,p=/\bETARGET\b|\bE404\b|No matching version found/i,m=/\bneeds Node\.js\b|\bnot recognized as an internal or external command\b|\b(?:npm|npx|node): (?:command )?not found\b|\bcommand not found: (?:npm|npx|node)\b/i,h=/* @__PURE__ */ new Set([o,s,c,l,u,d]);function g(e){return f.test(e)?s:o}function _(e){return p.test(e)?l:m.test(e)?c:f.test(e)?s:u}function v(e){return e!==0}function y(t){switch(t.kind){case`timeout`:return{key:`app.agent.timeout`,detail:``};case`spawn`:return{key:t.code===`ENOENT`?c:d,detail:a(t.message)};case`exited`:{let n=t.code===null?`signal ${t.signal??`unknown`}`:e(`app.agent.exitCode`,{code:t.code}),r=a(t.tail);return{key:_(t.tail),detail:r===``?n:`${n}: ${r}`}}}}function b(e){return h.has(e)}function x(t){return b(t.key)?e(t.key):e(t.key,{detail:t.detail})}export{y as a,x as i,v as n,i as o,g as r,l as t};
@@ -1 +1 @@
1
- import{r as e}from"./chunk-translator-BFUJmSkR.js";import{H as t,Z as n,c as r,k as i,n as a,q as o,r as s}from"./chunk-mcpLaunch-C13ViiIP.js";import{r as c}from"./chunk-failure-BsimkHy_.js";import{o as l}from"./chunk-load-BVJUBU5S.js";import u from"node:path";import{constants as d,tmpdir as f}from"node:os";import{existsSync as p,mkdirSync as m,mkdtempSync as h,readFileSync as g,readdirSync as _,realpathSync as v,rmSync as y,statSync as b,writeFileSync as x}from"node:fs";import{spawn as S}from"node:child_process";import{randomBytes as C}from"node:crypto";const w=/^[a-z]+-(\d+)-[0-9a-f]{8}\.json$/;function T(e){return u.join(e,s.directory)}function E(e,t,n){let r=T(e);m(r,{recursive:!0,mode:448});let i=u.join(r,`${t}-${process.pid}-${C(4).toString(`hex`)}.json`);return x(i,n,{mode:384,flag:`wx`}),{file:i,remove:()=>y(i,{force:!0})}}function D(e){let t=T(e),n;try{n=_(t)}catch{return}for(let e of n){let n=w.exec(e);n&&!r(Number(n[1]))&&y(u.join(t,e),{force:!0})}}const O=[`claude`,`codex`,`gemini`,`opencode`],k=/^[A-Za-z0-9_-]+$/;function A(e){let t=(e.split(/[\\/]/).pop()??``).replace(/\.(exe|cmd|bat|com)$/i,``).toLowerCase();return O.find(e=>e===t)??`other`}function j(e,t,n){let r={...e.env};return typeof n.PENSTOCK_HOME==`string`&&n.PENSTOCK_HOME!==``&&(r.PENSTOCK_HOME=n.PENSTOCK_HOME),{command:e.command,args:[...e.args,`--project`,t],env:r}}function M(e){return k.test(e)?e:JSON.stringify(e)}function N(e){return`{${Object.entries(e).map(([e,t])=>`${M(e)}=${JSON.stringify(t)}`).join(`,`)}}`}function P(e){return JSON.stringify({mcpServers:{penstock:{type:`stdio`,command:e.command,args:e.args,env:e.env}}})}function F(e){let t=[`mcp_servers.penstock.command=${JSON.stringify(e.command)}`,`mcp_servers.penstock.args=${JSON.stringify(e.args)}`];return Object.keys(e.env).length>0&&t.push(`mcp_servers.penstock.env=${N(e.env)}`),t.flatMap(e=>[`-c`,e])}function I(e){if(e===void 0||e.trim()===``)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function L(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function R(e,t){let n=I(t),r={type:`local`,command:[e.command,...e.args],enabled:!0};return Object.keys(e.env).length>0&&(r.environment=e.env),JSON.stringify({...n,mcp:{...L(n.mcp),penstock:r}})}function z(e,t){let n=I(t),r={command:e.command,args:e.args};return Object.keys(e.env).length>0&&(r.env=e.env),JSON.stringify({...n,mcpServers:{...L(n.mcpServers),penstock:r}})}function B(e){if(e!==void 0&&e!==``)try{return g(e,`utf8`)}catch{return}}function V(e,t,n,r,i,a){let o=()=>void 0;switch(e){case`claude`:{let e=E(a,`mcp`,P(t));return{args:[...i.args,...n,`--mcp-config`,e.file],env:i.env,cleanup:e.remove}}case`codex`:return{args:[...F(t),...i.args,...n],env:i.env,cleanup:o};case`opencode`:return{args:[...i.args,...n],env:{...i.env,OPENCODE_CONFIG_CONTENT:R(t,r.OPENCODE_CONFIG_CONTENT)},cleanup:o};case`gemini`:{let e=h(u.join(f(),`penstock-agent-`)),a=u.join(e,`settings.json`);return x(a,z(t,B(r.GEMINI_CLI_SYSTEM_SETTINGS_PATH)),{mode:384}),{args:[...i.args,...n],env:{...i.env,GEMINI_CLI_SYSTEM_SETTINGS_PATH:a},cleanup:()=>y(e,{recursive:!0,force:!0})}}default:return{args:[...i.args,...n],env:{...i.env,PENSTOCK_MCP_CONFIG:JSON.stringify({mcpServers:{penstock:{command:t.command,args:t.args,env:t.env}}})},cleanup:o}}}function H(n){let r=[...t().map(e=>({id:e.id,name:e.name,found:o(e.binary,n.env,n.cwd)!==null,install:e.install})),...i(n.home).map(e=>({id:e.id,name:e.name,found:o(e.command,n.env,n.cwd)!==null,install:null}))],a=Math.max(...r.map(e=>e.id.length)),s=r.map(t=>{let n=t.found?e(`app.cli.agentLaunch.installed`):t.install?e(`app.cli.agentLaunch.missing`,{install:t.install}):e(`app.cli.agentLaunch.notFound`);return` ${t.id.padEnd(a)} ${t.name}: ${n}`});return{ok:!0,lines:[e(`app.cli.agentLaunch.heading`),...s,``,e(`app.cli.agentLaunch.how`)]}}function U(...e){return{ok:!1,lines:e,code:1}}function W(t){let n=u.resolve(t);return p(n)?b(n).isDirectory()?v(n):U(e(`app.cli.web.notAFolder`,{folder:n})):U(c(n))}function G(e,t){return e===null?128+((t===null?void 0:d.signals[t])??1):e}function K(e,t,n){return new Promise(r=>{let i=S(e.command,e.args,{cwd:n,env:t,stdio:`inherit`,windowsVerbatimArguments:e.verbatim}),a=e=>()=>{i.kill(e)},o=[[`SIGTERM`,a(`SIGTERM`)],[`SIGHUP`,a(`SIGHUP`)],[`SIGINT`,()=>void 0]];for(let[e,t]of o)process.on(e,t);let s=()=>{for(let[e,t]of o)process.off(e,t)};i.once(`error`,e=>{s(),r({failure:e.message})}),i.once(`close`,(e,t)=>{s(),r({code:G(e,t)})})})}async function q(r){if(r.agent===void 0)return H(r);let s=r.agent,c=t().find(e=>e.id===s),u=c?void 0:i(r.home).find(e=>e.id===s);if(!c&&!u){let n=[...t().map(e=>e.id),...i(r.home).map(e=>e.id)].join(`, `);return U(e(`app.cli.agentLaunch.unknown`,{agent:s,list:n}))}let d=c?.name??u?.name??s,f=c?c.binary:u?.command,p=o(f,r.env,r.cwd);if(p===null)return U(c?e(`app.cli.agentLaunch.notInstalled`,{name:d,install:c.install}):e(`app.cli.agentLaunch.commandMissing`,{name:d,command:f}));let m=r.cwd,h;if(r.project!==void 0){let e=W(r.project);if(typeof e!=`string`)return e;m=e,h=e}else h=v(l(r.cwd));let g=r.mcp===void 0?a():r.mcp;if(g===null)return U(e(`app.cli.agentLaunch.noMcp`));let _=j(g,h,r.env),y=c?c.id:A(f);y===`other`&&process.stderr.write(`${e(`app.cli.agentLaunch.customNote`,{name:d})}\n`);let b;try{D(r.home),b=V(y,_,r.passthrough,r.env,{args:u?.args??[],env:u?.env??{}},r.home)}catch(t){return U(e(`app.cli.agentLaunch.cannotPrepare`,{reason:t instanceof Error?t.message:String(t)}))}let x;try{x=n({command:p,args:b.args})}catch{return b.cleanup(),U(e(`app.cli.agentLaunch.unsafeArguments`,{name:d}))}try{let t=await K(x,{...r.env,...b.env},m);return`failure`in t?U(e(`app.cli.agentLaunch.cannotStart`,{name:d,reason:t.failure})):{ok:t.code===0,lines:[],code:t.code}}finally{b.cleanup()}}function J(e){let t=e.indexOf(`--`);return t<0?[]:e.slice(t+1)}export{q as launchAgent,J as passthroughOf};
1
+ import{r as e}from"./chunk-translator-BAjzyPKE.js";import{H as t,Z as n,c as r,k as i,n as a,q as o,r as s}from"./chunk-mcpLaunch-DpDE0hW-.js";import{r as c}from"./chunk-failure-BK7fu4Yo.js";import{o as l}from"./chunk-load-CRmIvn7e.js";import u from"node:path";import{constants as d,tmpdir as f}from"node:os";import{existsSync as p,mkdirSync as m,mkdtempSync as h,readFileSync as g,readdirSync as _,realpathSync as v,rmSync as y,statSync as b,writeFileSync as x}from"node:fs";import{spawn as S}from"node:child_process";import{randomBytes as C}from"node:crypto";const w=/^[a-z]+-(\d+)-[0-9a-f]{8}\.json$/;function T(e){return u.join(e,s.directory)}function E(e,t,n){let r=T(e);m(r,{recursive:!0,mode:448});let i=u.join(r,`${t}-${process.pid}-${C(4).toString(`hex`)}.json`);return x(i,n,{mode:384,flag:`wx`}),{file:i,remove:()=>y(i,{force:!0})}}function D(e){let t=T(e),n;try{n=_(t)}catch{return}for(let e of n){let n=w.exec(e);n&&!r(Number(n[1]))&&y(u.join(t,e),{force:!0})}}const O=[`claude`,`codex`,`gemini`,`opencode`],k=/^[A-Za-z0-9_-]+$/;function A(e){let t=(e.split(/[\\/]/).pop()??``).replace(/\.(exe|cmd|bat|com)$/i,``).toLowerCase();return O.find(e=>e===t)??`other`}function j(e,t,n){let r={...e.env};return typeof n.PENSTOCK_HOME==`string`&&n.PENSTOCK_HOME!==``&&(r.PENSTOCK_HOME=n.PENSTOCK_HOME),{command:e.command,args:[...e.args,`--project`,t],env:r}}function M(e){return k.test(e)?e:JSON.stringify(e)}function N(e){return`{${Object.entries(e).map(([e,t])=>`${M(e)}=${JSON.stringify(t)}`).join(`,`)}}`}function P(e){return JSON.stringify({mcpServers:{penstock:{type:`stdio`,command:e.command,args:e.args,env:e.env}}})}function F(e){let t=[`mcp_servers.penstock.command=${JSON.stringify(e.command)}`,`mcp_servers.penstock.args=${JSON.stringify(e.args)}`];return Object.keys(e.env).length>0&&t.push(`mcp_servers.penstock.env=${N(e.env)}`),t.flatMap(e=>[`-c`,e])}function I(e){if(e===void 0||e.trim()===``)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function L(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function R(e,t){let n=I(t),r={type:`local`,command:[e.command,...e.args],enabled:!0};return Object.keys(e.env).length>0&&(r.environment=e.env),JSON.stringify({...n,mcp:{...L(n.mcp),penstock:r}})}function z(e,t){let n=I(t),r={command:e.command,args:e.args};return Object.keys(e.env).length>0&&(r.env=e.env),JSON.stringify({...n,mcpServers:{...L(n.mcpServers),penstock:r}})}function B(e){if(e!==void 0&&e!==``)try{return g(e,`utf8`)}catch{return}}function V(e,t,n,r,i,a){let o=()=>void 0;switch(e){case`claude`:{let e=E(a,`mcp`,P(t));return{args:[...i.args,...n,`--mcp-config`,e.file],env:i.env,cleanup:e.remove}}case`codex`:return{args:[...F(t),...i.args,...n],env:i.env,cleanup:o};case`opencode`:return{args:[...i.args,...n],env:{...i.env,OPENCODE_CONFIG_CONTENT:R(t,r.OPENCODE_CONFIG_CONTENT)},cleanup:o};case`gemini`:{let e=h(u.join(f(),`penstock-agent-`)),a=u.join(e,`settings.json`);return x(a,z(t,B(r.GEMINI_CLI_SYSTEM_SETTINGS_PATH)),{mode:384}),{args:[...i.args,...n],env:{...i.env,GEMINI_CLI_SYSTEM_SETTINGS_PATH:a},cleanup:()=>y(e,{recursive:!0,force:!0})}}default:return{args:[...i.args,...n],env:{...i.env,PENSTOCK_MCP_CONFIG:JSON.stringify({mcpServers:{penstock:{command:t.command,args:t.args,env:t.env}}})},cleanup:o}}}function H(n){let r=[...t().map(e=>({id:e.id,name:e.name,found:o(e.binary,n.env,n.cwd)!==null,install:e.install})),...i(n.home).map(e=>({id:e.id,name:e.name,found:o(e.command,n.env,n.cwd)!==null,install:null}))],a=Math.max(...r.map(e=>e.id.length)),s=r.map(t=>{let n=t.found?e(`app.cli.agentLaunch.installed`):t.install?e(`app.cli.agentLaunch.missing`,{install:t.install}):e(`app.cli.agentLaunch.notFound`);return` ${t.id.padEnd(a)} ${t.name}: ${n}`});return{ok:!0,lines:[e(`app.cli.agentLaunch.heading`),...s,``,e(`app.cli.agentLaunch.how`)]}}function U(...e){return{ok:!1,lines:e,code:1}}function W(t){let n=u.resolve(t);return p(n)?b(n).isDirectory()?v(n):U(e(`app.cli.web.notAFolder`,{folder:n})):U(c(n))}function G(e,t){return e===null?128+((t===null?void 0:d.signals[t])??1):e}function K(e,t,n){return new Promise(r=>{let i=S(e.command,e.args,{cwd:n,env:t,stdio:`inherit`,windowsVerbatimArguments:e.verbatim}),a=e=>()=>{i.kill(e)},o=[[`SIGTERM`,a(`SIGTERM`)],[`SIGHUP`,a(`SIGHUP`)],[`SIGINT`,()=>void 0]];for(let[e,t]of o)process.on(e,t);let s=()=>{for(let[e,t]of o)process.off(e,t)};i.once(`error`,e=>{s(),r({failure:e.message})}),i.once(`close`,(e,t)=>{s(),r({code:G(e,t)})})})}async function q(r){if(r.agent===void 0)return H(r);let s=r.agent,c=t().find(e=>e.id===s),u=c?void 0:i(r.home).find(e=>e.id===s);if(!c&&!u){let n=[...t().map(e=>e.id),...i(r.home).map(e=>e.id)].join(`, `);return U(e(`app.cli.agentLaunch.unknown`,{agent:s,list:n}))}let d=c?.name??u?.name??s,f=c?c.binary:u?.command,p=o(f,r.env,r.cwd);if(p===null)return U(c?e(`app.cli.agentLaunch.notInstalled`,{name:d,install:c.install}):e(`app.cli.agentLaunch.commandMissing`,{name:d,command:f}));let m=r.cwd,h;if(r.project!==void 0){let e=W(r.project);if(typeof e!=`string`)return e;m=e,h=e}else h=v(l(r.cwd));let g=r.mcp===void 0?a():r.mcp;if(g===null)return U(e(`app.cli.agentLaunch.noMcp`));let _=j(g,h,r.env),y=c?c.id:A(f);y===`other`&&process.stderr.write(`${e(`app.cli.agentLaunch.customNote`,{name:d})}\n`);let b;try{D(r.home),b=V(y,_,r.passthrough,r.env,{args:u?.args??[],env:u?.env??{}},r.home)}catch(t){return U(e(`app.cli.agentLaunch.cannotPrepare`,{reason:t instanceof Error?t.message:String(t)}))}let x;try{x=n({command:p,args:b.args})}catch{return b.cleanup(),U(e(`app.cli.agentLaunch.unsafeArguments`,{name:d}))}try{let t=await K(x,{...r.env,...b.env},m);return`failure`in t?U(e(`app.cli.agentLaunch.cannotStart`,{name:d,reason:t.failure})):{ok:t.code===0,lines:[],code:t.code}}finally{b.cleanup()}}function J(e){let t=e.indexOf(`--`);return t<0?[]:e.slice(t+1)}export{q as launchAgent,J as passthroughOf};
@@ -1,4 +1,4 @@
1
- import{n as e}from"./chunk-version-CdS8_QQd.js";import{t}from"./chunk-atomicWrite-C6J1gDtO.js";import{u as n}from"./chunk-license-x3oHbKe2.js";import{r}from"./chunk-translator-BFUJmSkR.js";import{s as i,t as a}from"./chunk-features-BfRg2kR5.js";import{r as o,t as s}from"./chunk-preferencesFile-F6bAlNrk.js";import{A as c,B as l,C as u,D as ee,E as d,I as f,M as p,R as m,S as h,V as g,X as _,_ as v,a as y,b,c as x,d as te,f as S,g as C,h as w,l as ne,m as T,n as re,o as ie,p as E,r as D,s as O,t as k,u as A,v as ae,w as oe,x as j,y as se,z as ce}from"./chunk-mcpLaunch-C13ViiIP.js";import{o as M,r as le}from"./chunk-agentFailure-piRAFLGH.js";import{A as ue,C as de,D as fe,F as pe,I as me,M as he,N,O as P,P as F,S as ge,T as _e,_ as I,a as ve,b as ye,d as be,g as L,h as xe,j as Se,k as Ce,l as we,s as Te,v as Ee,w as R,y as De}from"./chunk-security-5SU-bq3A.js";import{r as Oe}from"./chunk-failure-BsimkHy_.js";import{r as ke}from"./chunk-editPreview-BgH1JVOD.js";import z from"node:path";import{mkdirSync as Ae,readFileSync as B,rmSync as V,statSync as H}from"node:fs";import{execFileSync as je,spawn as Me}from"node:child_process";import{randomBytes as Ne}from"node:crypto";import{createServer as Pe}from"node:http";import{RequestError as U}from"@agentclientprotocol/sdk";function W(e,t){return y(e,t).replace(/\.json$/,`.children.json`)}function Fe(e){return Array.isArray(e)?e.filter(e=>{let t=e;return typeof t==`object`&&!!t&&Number.isInteger(t.pid)&&(t.pid??0)>0&&typeof t.command==`string`&&t.command!==``}):[]}function G(e){try{return Fe(JSON.parse(B(e,`utf8`)))}catch{return[]}}function K(e,n){n.length===0?V(e,{force:!0}):(Ae(z.dirname(e),{recursive:!0,mode:448}),t(e,`${JSON.stringify(n)}\n`,384))}function Ie(e,t,n){let r=W(e,t);K(r,[...G(r).filter(e=>e.pid!==n.pid),n])}function Le(e,t,n){let r=W(e,t);K(r,G(r).filter(e=>e.pid!==n))}function Re(e){if(process.platform===`win32`)return null;try{return je(`ps`,[`-o`,`command=`,`-p`,String(e)],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()}catch{return null}}async function ze(e,t){let n=W(e,t),r=G(n).filter(e=>x(e.pid)&&Re(e.pid)?.includes(e.command));V(n,{force:!0});for(let e of r)A(e.pid,`SIGTERM`);if(r.length!==0){await new Promise(e=>setTimeout(e,1e3));for(let e of r)x(e.pid)&&A(e.pid,`SIGKILL`)}}var Be=class{graceMs;holds=0;attendedAt;idleAt;constructor(e,t){this.graceMs=e,this.attendedAt=t,this.idleAt=t}hold(e){this.holds+=1,this.touch(e);let t=!0;return e=>{t&&(t=!1,--this.holds,this.touch(e))}}tick(e,t,n){let r=this.holds>0;return r&&this.touch(e),t&&(this.idleAt=e),{unattended:!r&&e-this.attendedAt>=this.graceMs,leave:n?!t:!r&&e-this.idleAt>=this.graceMs}}touch(e){this.attendedAt=e,this.idleAt=e}};const q={required:[`file`],allowed:[`file`]},Ve={required:[`file`,`element`],allowed:[`file`,`element`]},He={required:[],allowed:[`project`]},Ue={list_diagrams:He,show_diagram:q,element_context:Ve,check_diagram:q,analyze_flow:q,list_scenarios:q,check_code_links:He,search_elements:{required:[`query`],allowed:[`query`,`project`]},diff_diagrams:{required:[`file`],allowed:[`file`,`other`,`ref`]}},We=Object.keys(Ue),Ge=[`file`,`operations`,`dryRun`],Ke=/* @__PURE__ */ new Set([`edit`,`delete`,`move`]),qe=/* @__PURE__ */ new Set([`read`,`search`,`other`]),Je=/* @__PURE__ */ new Set([`allowAlways`,`rejectAlways`]);function Ye(e,t){return RegExp(`(?:^|[^a-z0-9_]|__|penstock_)${t}(?![a-z0-9_])`,`i`).test(e.title)}function Xe(e,t){return RegExp(`^\\s*(?:tool:\\s*)?(?:mcp__penstock__|penstock(?:[_/:.]|\\s*[:/]\\s*))${t}\\s*$`,`i`).test(e.title)}function Ze(e){return Ye(e,`edit_diagram`)}function Qe(e,t){let n=t=>t.every(t=>typeof e[t]==`string`&&e[t]!==``);return Object.keys(e).every(e=>t.allowed.includes(e))&&n(t.required)&&n(Object.keys(e))}function $e(e,t){if(!qe.has(e.kind)||e.diffs.length>0)return!1;let n=We.find(t=>Xe(e,t));if(n===void 0)return!1;let r=rt(t);return r!==null&&Qe(r,Ue[n])}function et(e){return Ke.has(e.kind)||e.diffs.length>0||Ze(e)}function tt(e){return{...e,options:e.options.filter(e=>!Je.has(e.kind))}}function nt(e){return e.options.find(e=>e.kind===`allow`)?.id??null}function rt(e){let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{return null}return typeof t==`object`&&t&&!Array.isArray(t)?t:null}function it(e,t){if(!Xe(e,`edit_diagram`)||e.diffs.length>0)return!1;let n=rt(t);return n===null||n.dryRun!==!0||!Object.keys(n).every(e=>Ge.includes(e))?!1:typeof n.file==`string`&&n.file!==``&&n.operations!==void 0}function at(e){let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;return typeof n.file!=`string`||n.file===``||n.operations===void 0?null:{file:n.file,operations:n.operations}}const ot=2e5,J=8388608,st=16777216,Y=-32602,X=-32603,Z={outcome:{outcome:`cancelled`}},ct=`app.agent.authRequired`;function lt(e,t){let n=e instanceof U?e.data:null,r=[n?.message,n?.details].find(e=>typeof e==`string`&&e.trim()!==``);return r&&!t.includes(r)?`${t}: ${r}`:t}function ut(e){if(!(e instanceof U))return``;let t=([e.data?.message,e.message].find(e=>typeof e==`string`&&e.trim()!==``)??``).split(/\r?\n/).map(e=>e.trim()).find(e=>e!==``)??``;return M(Array.from(t).slice(0,300).join(``))}function dt(e,t,n,r){if(e instanceof ue)return{key:le(e.tail),detail:e.tail===``?e.how:`${e.how}: ${e.tail}`};if(e instanceof N)return{key:`app.agent.timeout`,detail:``};if(F(e))return{key:ct,detail:ut(e),signIn:r};let i=e?.code;if(e instanceof he||i===`ENOENT`||i===`EACCES`)return{key:`app.agent.notFound`,detail:p(n,t)??``};if(e instanceof _)return{key:`app.agent.unsafe`,detail:``};let a=e instanceof Error?e.message:String(e);return{key:`app.agent.failed`,detail:M(lt(e,a))}}function ft(){return Ne(9).toString(`base64url`)}var pt=class{host;timings;store;feed;chats=/* @__PURE__ */ new Map;processes=/* @__PURE__ */ new Map;live=/* @__PURE__ */ new Set;started=/* @__PURE__ */ new Map;owners=/* @__PURE__ */ new Map;offered=/* @__PURE__ */ new Map;dirty=/* @__PURE__ */ new Map;unsaved=/* @__PURE__ */ new Set;flushTimer=null;saveTimer=null;watcher=null;asked=0;on=!0;retiring=!1;checkedAt=0;disposed=!1;constructor(e,t={}){this.host=e,this.timings={connectMs:t.connectMs??3e4,flushMs:t.flushMs??40,killMs:t.killMs??2e3,stopMs:t.stopMs??1e4,saveMs:t.saveMs??400,prefsMs:t.prefsMs??1e3,watchMs:t.watchMs??1e3,signInMs:t.signInMs??3e5},this.store=new w(e.home,e.folder);for(let e of this.store.load())this.chats.set(e.id,C.from(e));this.feed=new fe(()=>this.replay(),t.feed),this.on=this.readEnabled()}enabled(){return this.refresh(!1),this.on}refresh(e=!0){if(this.disposed)return;let t=Date.now();if(!e&&t-this.checkedAt<this.timings.prefsMs)return;this.checkedAt=t;let n=this.readEnabled();n!==this.on&&(this.on=n,n||this.shutDown(),this.publish({type:`enabled`,enabled:n}),this.publishChats())}busy(){for(let e of this.chats.values())if(e.turn!==null||e.questions.length>0||e.queue.length>0)return!0;return!1}retire(){return this.retiring=!0,this.busy()}drained(){return Promise.all([...this.live].map(e=>e.exited(this.timings.killMs*2))).then(()=>void 0)}cancelUnanswered(){for(let e of this.chats.values()){if(e.questions.length===0)continue;let t=e.transcript.notice(r(`app.agent.unanswered`));this.publish(this.entryEvent(e,t)),this.touch(e),this.halt(e)}}stopQuiet(e){let t=performance.now();for(let n of this.chats.values()){let i=n.turn;if(!i||i.stopping||n.questions.length>0||t-i.heard<e)continue;let a=n.transcript.notice(r(`app.agent.quiet`));this.publish(this.entryEvent(n,a)),this.touch(n),this.halt(n)}}catalog(){return Ce({home:this.host.home,env:this.host.env,folder:this.host.folder,version:this.host.version})}choices(){return this.installed().map(e=>({...e,options:this.cached(e.id)}))}installed(){return ee(this.host.env,this.host.home,this.host.folder)}cached(e){let t=this.offered.get(e)??pe(this.host.home,e)?.options;if(!t)return[];let n=l(this.host.home,e);return t.map(e=>{let t=j.includes(e.category)?n[e.category]:void 0;return h(t!==void 0&&u(e,t)?{...e,current:t}:e)})}list(){let e=this.enabled();return e?{chats:this.dtos(),enabled:e}:{chats:[],enabled:e}}create(e){this.requireOn(),this.requireFree();let t=this.installed();if(e!==null&&!t.some(t=>t.id===e))throw E(404,`app.agent.reason.unknownAgent`,{agent:e.slice(0,80)});let n=e??c(t,this.host.home)??g(this.host.home)??t[0]?.id??`claude`,r=new C(ft(),n,Date.now());return this.chats.set(r.id,r),this.publishChats(),r.dto()}get(e){this.requireOn();let t=this.chat(e);return this.shown(t),t.describe()}rename(e,t){this.requireOn();let n=this.chat(e),r=t.replace(/[\u0000-\u001f\u007f]+/g,` `).trim();if(r===``||Array.from(r).length>120)throw E(400,`app.agent.reason.badTitle`,{limit:120});return n.title=r,this.touch(n),this.publishChats(),n.dto()}remove(e){this.requireOn();let t=this.chat(e);this.forget(t);try{this.store.remove(e)}catch(t){console.warn(r(`app.agent.log.notKept`,{id:e,reason:t instanceof Error?t.message:String(t)}))}this.publishChats()}async prompt(e,t,n=null){this.requireOn(),this.requireFree();let r=this.chat(e),i=t.trim();if(i===``||i.length>ot)throw E(400,`app.agent.reason.badText`,{limit:ot});if(await this.requireLicence(),this.requireOn(),this.requireFree(),this.chats.get(e)!==r)throw E(404,`app.agent.reason.noSuchChat`);let a=this.contextOf(n);if(this.remember(r,this.contextFile(n)),r.turn!==null||r.queue.length>0){if(r.queue.length>=20)throw E(409,`app.agent.reason.queueFull`,{limit:20});let e={id:ft(),text:i,context:a};return r.queue.push(e),this.watch(),this.publish({type:`queue`,chatId:r.id,queue:this.queueOf(r)}),this.drainSoon(r),{queued:!0,queueId:e.id}}return this.begin(r,i,a),{queued:!1,queueId:null}}unqueue(e,t){this.requireOn();let n=this.chat(e),r=n.queue.findIndex(e=>e.id===t);if(r<0)throw E(404,`app.agent.reason.noSuchQueued`);n.queue.splice(r,1),this.publish({type:`queue`,chatId:n.id,queue:this.queueOf(n)})}stop(e){this.requireOn(),this.halt(this.chat(e))}async signIn(e){this.requireOn();let t=this.chat(e),n=t.failure;if(t.turn!==null||n?.key!==ct||n.signIn!==!0)throw E(409,`app.agent.reason.noSignIn`);if(await this.requireLicence(),this.requireOn(),this.chats.get(e)!==t)throw E(404,`app.agent.reason.noSuchChat`);try{let e=await this.processOf(t.agentId),n=e.signInMethods[0];if(n===void 0)throw E(409,`app.agent.reason.noSignIn`);await e.authenticate(n,this.timings.signInMs)}catch(e){throw e instanceof S?e:this.signInFailure(e,t.agentId)}this.chats.get(e)===t&&t.failure===n&&(t.failure=null,this.touch(t),this.publish({type:`error`,chatId:t.id,error:null}),this.publishChats())}signInFailure(e,t){return e instanceof U?E(502,`app.agent.reason.signInRefused`,{reason:ut(e)}):T(e instanceof N?504:500,dt(e,this.host.home,t,!1))}answer(e,t,n){this.requireOn();let r=this.chat(e),i=r.questions[0];if(!i||i.permission.id!==t)throw E(409,`app.agent.reason.staleQuestion`);let a=i.permission.options.find(e=>e.id===n);if(!a)throw E(409,`app.agent.reason.badOption`,{option:n.slice(0,80)});r.questions.shift(),i.grants&&a.kind===`allow`&&this.grant(r,i.permission.tool),i.resolve(n),this.publish({type:`permission`,chatId:r.id,permission:r.questions[0]?.permission??null}),this.publishChats()}next(e,t){return this.refresh(!1),this.watch(),this.feed.next(e,t)}dispose(){if(!this.disposed){this.disposed=!0,this.watcher&&clearInterval(this.watcher),this.watcher=null,this.flush(),this.saveAll();for(let e of this.chats.values()){for(let t of e.questions.splice(0))t.resolve(null);e.turn?.stopping&&clearTimeout(e.turn.stopping)}this.shutDown(),this.saveAll(),this.feed.close()}}readEnabled(){try{return new s(this.host.home).aiChat()!==`off`}catch{return!0}}requireOn(){if(!this.enabled())throw E(409,`app.agent.reason.off`)}requireFree(){if(this.retiring)throw E(409,`app.agent.retiring`)}async requireLicence(){let e={env:this.host.env},t=await n(e);if(!(this.host.licensed?await this.host.licensed():a(t,e)))throw new S(402,i(t,`ai-chat`,e).join(`
1
+ import{n as e}from"./chunk-version-CdS8_QQd.js";import{t}from"./chunk-atomicWrite-C6J1gDtO.js";import{u as n}from"./chunk-license-DU4P8P8A.js";import{r}from"./chunk-translator-BAjzyPKE.js";import{s as i,t as a}from"./chunk-features-CiC2Yoej.js";import{r as o,t as s}from"./chunk-preferencesFile-F6bAlNrk.js";import{A as c,B as l,C as u,D as ee,E as d,I as f,M as p,R as m,S as h,V as g,X as _,_ as v,a as y,b,c as x,d as te,f as S,g as C,h as w,l as ne,m as T,n as re,o as ie,p as E,r as D,s as O,t as k,u as A,v as ae,w as oe,x as j,y as se,z as ce}from"./chunk-mcpLaunch-DpDE0hW-.js";import{o as M,r as le}from"./chunk-agentFailure-BiU8hJ-k.js";import{A as ue,C as de,D as fe,F as pe,I as me,M as he,N,O as P,P as F,S as ge,T as _e,_ as I,a as ve,b as ye,d as be,g as L,h as xe,j as Se,k as Ce,l as we,s as Te,v as Ee,w as R,y as De}from"./chunk-security-BKVRwb6V.js";import{r as Oe}from"./chunk-failure-BK7fu4Yo.js";import{r as ke}from"./chunk-editPreview-DGu4slO6.js";import z from"node:path";import{mkdirSync as Ae,readFileSync as B,rmSync as V,statSync as H}from"node:fs";import{execFileSync as je,spawn as Me}from"node:child_process";import{randomBytes as Ne}from"node:crypto";import{createServer as Pe}from"node:http";import{RequestError as U}from"@agentclientprotocol/sdk";function W(e,t){return y(e,t).replace(/\.json$/,`.children.json`)}function Fe(e){return Array.isArray(e)?e.filter(e=>{let t=e;return typeof t==`object`&&!!t&&Number.isInteger(t.pid)&&(t.pid??0)>0&&typeof t.command==`string`&&t.command!==``}):[]}function G(e){try{return Fe(JSON.parse(B(e,`utf8`)))}catch{return[]}}function K(e,n){n.length===0?V(e,{force:!0}):(Ae(z.dirname(e),{recursive:!0,mode:448}),t(e,`${JSON.stringify(n)}\n`,384))}function Ie(e,t,n){let r=W(e,t);K(r,[...G(r).filter(e=>e.pid!==n.pid),n])}function Le(e,t,n){let r=W(e,t);K(r,G(r).filter(e=>e.pid!==n))}function Re(e){if(process.platform===`win32`)return null;try{return je(`ps`,[`-o`,`command=`,`-p`,String(e)],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()}catch{return null}}async function ze(e,t){let n=W(e,t),r=G(n).filter(e=>x(e.pid)&&Re(e.pid)?.includes(e.command));V(n,{force:!0});for(let e of r)A(e.pid,`SIGTERM`);if(r.length!==0){await new Promise(e=>setTimeout(e,1e3));for(let e of r)x(e.pid)&&A(e.pid,`SIGKILL`)}}var Be=class{graceMs;holds=0;attendedAt;idleAt;constructor(e,t){this.graceMs=e,this.attendedAt=t,this.idleAt=t}hold(e){this.holds+=1,this.touch(e);let t=!0;return e=>{t&&(t=!1,--this.holds,this.touch(e))}}tick(e,t,n){let r=this.holds>0;return r&&this.touch(e),t&&(this.idleAt=e),{unattended:!r&&e-this.attendedAt>=this.graceMs,leave:n?!t:!r&&e-this.idleAt>=this.graceMs}}touch(e){this.attendedAt=e,this.idleAt=e}};const q={required:[`file`],allowed:[`file`]},Ve={required:[`file`,`element`],allowed:[`file`,`element`]},He={required:[],allowed:[`project`]},Ue={list_diagrams:He,show_diagram:q,element_context:Ve,check_diagram:q,analyze_flow:q,list_scenarios:q,check_code_links:He,search_elements:{required:[`query`],allowed:[`query`,`project`]},diff_diagrams:{required:[`file`],allowed:[`file`,`other`,`ref`]}},We=Object.keys(Ue),Ge=[`file`,`operations`,`dryRun`],Ke=/* @__PURE__ */ new Set([`edit`,`delete`,`move`]),qe=/* @__PURE__ */ new Set([`read`,`search`,`other`]),Je=/* @__PURE__ */ new Set([`allowAlways`,`rejectAlways`]);function Ye(e,t){return RegExp(`(?:^|[^a-z0-9_]|__|penstock_)${t}(?![a-z0-9_])`,`i`).test(e.title)}function Xe(e,t){return RegExp(`^\\s*(?:tool:\\s*)?(?:mcp__penstock__|penstock(?:[_/:.]|\\s*[:/]\\s*))${t}\\s*$`,`i`).test(e.title)}function Ze(e){return Ye(e,`edit_diagram`)}function Qe(e,t){let n=t=>t.every(t=>typeof e[t]==`string`&&e[t]!==``);return Object.keys(e).every(e=>t.allowed.includes(e))&&n(t.required)&&n(Object.keys(e))}function $e(e,t){if(!qe.has(e.kind)||e.diffs.length>0)return!1;let n=We.find(t=>Xe(e,t));if(n===void 0)return!1;let r=rt(t);return r!==null&&Qe(r,Ue[n])}function et(e){return Ke.has(e.kind)||e.diffs.length>0||Ze(e)}function tt(e){return{...e,options:e.options.filter(e=>!Je.has(e.kind))}}function nt(e){return e.options.find(e=>e.kind===`allow`)?.id??null}function rt(e){let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{return null}return typeof t==`object`&&t&&!Array.isArray(t)?t:null}function it(e,t){if(!Xe(e,`edit_diagram`)||e.diffs.length>0)return!1;let n=rt(t);return n===null||n.dryRun!==!0||!Object.keys(n).every(e=>Ge.includes(e))?!1:typeof n.file==`string`&&n.file!==``&&n.operations!==void 0}function at(e){let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;return typeof n.file!=`string`||n.file===``||n.operations===void 0?null:{file:n.file,operations:n.operations}}const ot=2e5,J=8388608,st=16777216,Y=-32602,X=-32603,Z={outcome:{outcome:`cancelled`}},ct=`app.agent.authRequired`;function lt(e,t){let n=e instanceof U?e.data:null,r=[n?.message,n?.details].find(e=>typeof e==`string`&&e.trim()!==``);return r&&!t.includes(r)?`${t}: ${r}`:t}function ut(e){if(!(e instanceof U))return``;let t=([e.data?.message,e.message].find(e=>typeof e==`string`&&e.trim()!==``)??``).split(/\r?\n/).map(e=>e.trim()).find(e=>e!==``)??``;return M(Array.from(t).slice(0,300).join(``))}function dt(e,t,n,r){if(e instanceof ue)return{key:le(e.tail),detail:e.tail===``?e.how:`${e.how}: ${e.tail}`};if(e instanceof N)return{key:`app.agent.timeout`,detail:``};if(F(e))return{key:ct,detail:ut(e),signIn:r};let i=e?.code;if(e instanceof he||i===`ENOENT`||i===`EACCES`)return{key:`app.agent.notFound`,detail:p(n,t)??``};if(e instanceof _)return{key:`app.agent.unsafe`,detail:``};let a=e instanceof Error?e.message:String(e);return{key:`app.agent.failed`,detail:M(lt(e,a))}}function ft(){return Ne(9).toString(`base64url`)}var pt=class{host;timings;store;feed;chats=/* @__PURE__ */ new Map;processes=/* @__PURE__ */ new Map;live=/* @__PURE__ */ new Set;started=/* @__PURE__ */ new Map;owners=/* @__PURE__ */ new Map;offered=/* @__PURE__ */ new Map;dirty=/* @__PURE__ */ new Map;unsaved=/* @__PURE__ */ new Set;flushTimer=null;saveTimer=null;watcher=null;asked=0;on=!0;retiring=!1;checkedAt=0;disposed=!1;constructor(e,t={}){this.host=e,this.timings={connectMs:t.connectMs??3e4,flushMs:t.flushMs??40,killMs:t.killMs??2e3,stopMs:t.stopMs??1e4,saveMs:t.saveMs??400,prefsMs:t.prefsMs??1e3,watchMs:t.watchMs??1e3,signInMs:t.signInMs??3e5},this.store=new w(e.home,e.folder);for(let e of this.store.load())this.chats.set(e.id,C.from(e));this.feed=new fe(()=>this.replay(),t.feed),this.on=this.readEnabled()}enabled(){return this.refresh(!1),this.on}refresh(e=!0){if(this.disposed)return;let t=Date.now();if(!e&&t-this.checkedAt<this.timings.prefsMs)return;this.checkedAt=t;let n=this.readEnabled();n!==this.on&&(this.on=n,n||this.shutDown(),this.publish({type:`enabled`,enabled:n}),this.publishChats())}busy(){for(let e of this.chats.values())if(e.turn!==null||e.questions.length>0||e.queue.length>0)return!0;return!1}retire(){return this.retiring=!0,this.busy()}drained(){return Promise.all([...this.live].map(e=>e.exited(this.timings.killMs*2))).then(()=>void 0)}cancelUnanswered(){for(let e of this.chats.values()){if(e.questions.length===0)continue;let t=e.transcript.notice(r(`app.agent.unanswered`));this.publish(this.entryEvent(e,t)),this.touch(e),this.halt(e)}}stopQuiet(e){let t=performance.now();for(let n of this.chats.values()){let i=n.turn;if(!i||i.stopping||n.questions.length>0||t-i.heard<e)continue;let a=n.transcript.notice(r(`app.agent.quiet`));this.publish(this.entryEvent(n,a)),this.touch(n),this.halt(n)}}catalog(){return Ce({home:this.host.home,env:this.host.env,folder:this.host.folder,version:this.host.version})}choices(){return this.installed().map(e=>({...e,options:this.cached(e.id)}))}installed(){return ee(this.host.env,this.host.home,this.host.folder)}cached(e){let t=this.offered.get(e)??pe(this.host.home,e)?.options;if(!t)return[];let n=l(this.host.home,e);return t.map(e=>{let t=j.includes(e.category)?n[e.category]:void 0;return h(t!==void 0&&u(e,t)?{...e,current:t}:e)})}list(){let e=this.enabled();return e?{chats:this.dtos(),enabled:e}:{chats:[],enabled:e}}create(e){this.requireOn(),this.requireFree();let t=this.installed();if(e!==null&&!t.some(t=>t.id===e))throw E(404,`app.agent.reason.unknownAgent`,{agent:e.slice(0,80)});let n=e??c(t,this.host.home)??g(this.host.home)??t[0]?.id??`claude`,r=new C(ft(),n,Date.now());return this.chats.set(r.id,r),this.publishChats(),r.dto()}get(e){this.requireOn();let t=this.chat(e);return this.shown(t),t.describe()}rename(e,t){this.requireOn();let n=this.chat(e),r=t.replace(/[\u0000-\u001f\u007f]+/g,` `).trim();if(r===``||Array.from(r).length>120)throw E(400,`app.agent.reason.badTitle`,{limit:120});return n.title=r,this.touch(n),this.publishChats(),n.dto()}remove(e){this.requireOn();let t=this.chat(e);this.forget(t);try{this.store.remove(e)}catch(t){console.warn(r(`app.agent.log.notKept`,{id:e,reason:t instanceof Error?t.message:String(t)}))}this.publishChats()}async prompt(e,t,n=null){this.requireOn(),this.requireFree();let r=this.chat(e),i=t.trim();if(i===``||i.length>ot)throw E(400,`app.agent.reason.badText`,{limit:ot});if(await this.requireLicence(),this.requireOn(),this.requireFree(),this.chats.get(e)!==r)throw E(404,`app.agent.reason.noSuchChat`);let a=this.contextOf(n);if(this.remember(r,this.contextFile(n)),r.turn!==null||r.queue.length>0){if(r.queue.length>=20)throw E(409,`app.agent.reason.queueFull`,{limit:20});let e={id:ft(),text:i,context:a};return r.queue.push(e),this.watch(),this.publish({type:`queue`,chatId:r.id,queue:this.queueOf(r)}),this.drainSoon(r),{queued:!0,queueId:e.id}}return this.begin(r,i,a),{queued:!1,queueId:null}}unqueue(e,t){this.requireOn();let n=this.chat(e),r=n.queue.findIndex(e=>e.id===t);if(r<0)throw E(404,`app.agent.reason.noSuchQueued`);n.queue.splice(r,1),this.publish({type:`queue`,chatId:n.id,queue:this.queueOf(n)})}stop(e){this.requireOn(),this.halt(this.chat(e))}async signIn(e){this.requireOn();let t=this.chat(e),n=t.failure;if(t.turn!==null||n?.key!==ct||n.signIn!==!0)throw E(409,`app.agent.reason.noSignIn`);if(await this.requireLicence(),this.requireOn(),this.chats.get(e)!==t)throw E(404,`app.agent.reason.noSuchChat`);try{let e=await this.processOf(t.agentId),n=e.signInMethods[0];if(n===void 0)throw E(409,`app.agent.reason.noSignIn`);await e.authenticate(n,this.timings.signInMs)}catch(e){throw e instanceof S?e:this.signInFailure(e,t.agentId)}this.chats.get(e)===t&&t.failure===n&&(t.failure=null,this.touch(t),this.publish({type:`error`,chatId:t.id,error:null}),this.publishChats())}signInFailure(e,t){return e instanceof U?E(502,`app.agent.reason.signInRefused`,{reason:ut(e)}):T(e instanceof N?504:500,dt(e,this.host.home,t,!1))}answer(e,t,n){this.requireOn();let r=this.chat(e),i=r.questions[0];if(!i||i.permission.id!==t)throw E(409,`app.agent.reason.staleQuestion`);let a=i.permission.options.find(e=>e.id===n);if(!a)throw E(409,`app.agent.reason.badOption`,{option:n.slice(0,80)});r.questions.shift(),i.grants&&a.kind===`allow`&&this.grant(r,i.permission.tool),i.resolve(n),this.publish({type:`permission`,chatId:r.id,permission:r.questions[0]?.permission??null}),this.publishChats()}next(e,t){return this.refresh(!1),this.watch(),this.feed.next(e,t)}dispose(){if(!this.disposed){this.disposed=!0,this.watcher&&clearInterval(this.watcher),this.watcher=null,this.flush(),this.saveAll();for(let e of this.chats.values()){for(let t of e.questions.splice(0))t.resolve(null);e.turn?.stopping&&clearTimeout(e.turn.stopping)}this.shutDown(),this.saveAll(),this.feed.close()}}readEnabled(){try{return new s(this.host.home).aiChat()!==`off`}catch{return!0}}requireOn(){if(!this.enabled())throw E(409,`app.agent.reason.off`)}requireFree(){if(this.retiring)throw E(409,`app.agent.retiring`)}async requireLicence(){let e={env:this.host.env},t=await n(e);if(!(this.host.licensed?await this.host.licensed():a(t,e)))throw new S(402,i(t,`ai-chat`,e).join(`
2
2
  `))}chat(e){let t=this.chats.get(e);if(!t)throw E(404,`app.agent.reason.noSuchChat`);return t}forget(e){this.abandon(e),this.chats.delete(e.id),this.unsaved.delete(e),this.dirty.delete(e);for(let t of this.owners.values())e.sessionId&&t.delete(e.sessionId)}watch(){this.watcher||this.disposed||(this.watcher=setInterval(()=>this.tick(),this.timings.watchMs),this.watcher.unref())}tick(){if(!this.disposed&&(this.refresh(!1),this.on))for(let e of this.chats.values())e.queue.length>0&&e.turn===null&&this.drainSoon(e)}dtos(){return[...this.chats.values()].sort((e,t)=>t.updated-e.updated).map(e=>e.dto())}entryEvent(e,t){if(t.kind===`tool`)for(let n of t.tool.paths)this.remember(e,n);return t.kind===`tool`?{type:`tool`,chatId:e.id,tool:t.tool}:t.kind===`plan`?{type:`plan`,chatId:e.id,items:t.items}:{type:`entry`,chatId:e.id,entry:v(t)}}replay(){return[{type:`sync`},this.chatsEvent()]}chatsEvent(){let e=this.on;return{type:`chats`,chats:e?this.dtos():[],enabled:e}}publishChats(){this.flush(),this.feed.publish(this.chatsEvent())}publish(e){this.flush(),this.feed.publish(e)}queueOf(e){return e.queue.map(e=>({id:e.id,text:e.text}))}contextFile(e){if(!e||typeof e.file!=`string`||e.file===``)return null;try{return this.host.files.relative(this.host.files.resolve(e.file))}catch{return null}}remember(e,t){t!==null&&e.addFile(t)&&(this.markUnsaved(e),this.publishChats())}contextOf(e){if(!e)return null;let t=[],n=this.contextFile(e);n!==null&&t.push(r(`app.agent.contextFile`,{file:n}));let i=(e.elementIds??[]).filter(e=>typeof e==`string`&&e!==``&&e.length<=200).slice(0,50);return i.length>0&&t.push(r(`app.agent.contextElements`,{elements:i.join(`, `)})),t.length>0?t.join(`
3
3
  `):null}touch(e){e.updated=Date.now(),this.markUnsaved(e)}markUnsaved(e){e.worth&&(this.unsaved.add(e),!(this.saveTimer||this.disposed)&&(this.saveTimer=setTimeout(()=>{this.saveTimer=null,this.saveAll()},this.timings.saveMs),this.saveTimer.unref()))}saveAll(){this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=null;let e=[...this.unsaved];this.unsaved.clear();for(let t of e)this.chats.get(t.id)===t&&this.persist(t)}persist(e){try{let t=this.store.save(e.stored());e.turn===null&&t.entries.length!==e.transcript.list().length&&e.transcript.restore(t.entries)}catch(t){console.warn(r(`app.agent.log.notKept`,{id:e.id,reason:t instanceof Error?t.message:String(t)}))}}begin(e,t,n){e.turns+=1;let r={id:e.turns,cancelled:!1,stopping:null,heard:performance.now()};e.turn=r,e.failure=null,e.connecting=!0,e.grants=/* @__PURE__ */ new Map;let i=e.transcript.message(`user`,t,`user-${r.id}`);e.transcript.closeMessage(),e.title===null&&(e.title=ae(t)),this.touch(e),this.saveAll(),this.publish(this.entryEvent(e,i)),this.publishChats(),this.run(e,r,t,n)}async run(e,t,n,i){let a=null,o=`end_turn`;try{let a=await this.processOf(e.agentId);if(t.cancelled||e.turn!==t)return;let s=await this.sessionOf(e,a);if(t.cancelled||e.turn!==t)return;e.connecting=!1,this.publishChats();let c=[i,e.briefed===s?null:r(`app.agent.contextLinks`)].filter(e=>e!==null).join(`
4
4
  `);e.briefed=s;let l=[{type:`text`,text:n},...c?[{type:`text`,text:c}]:[]];o=await a.prompt(s,l),await new Promise(e=>setImmediate(e))}catch(n){if(t.cancelled||e.turn!==t)return;let r=e.process,i=!(n instanceof U)&&!(n instanceof N);if(i&&r&&await r.exited(this.timings.killMs),t.cancelled||e.turn!==t)return;if(r?.killedByUs){e.process=null,this.release(r),this.stoppedBy(e,t);return}a=dt(i&&r?.exitCause?r.exitCause:n,this.host.home,e.agentId,(r?.signInMethods.length??0)>0)}this.finish(e,t,a,o)}finish(e,t,n,r){if(e.turn===t){if(this.flush(),t.stopping&&clearTimeout(t.stopping),this.settleQuestions(e),e.turn=null,e.connecting=!1,e.failure=n,e.grants=/* @__PURE__ */ new Map,n)for(let t of e.transcript.failRunning())this.publish({type:`tool`,chatId:e.id,tool:t});else if(r===`cancelled`)for(let t of e.transcript.stopRunning())this.publish({type:`tool`,chatId:e.id,tool:t});this.touch(e),this.saveAll(),n&&this.publish({type:`error`,chatId:e.id,error:n}),this.publishChats(),this.afterTurn(e)}}afterTurn(e){e.wanted.size===0||!e.process?.alive?this.drainSoon(e):this.settle(e,!1).catch(()=>void 0).finally(()=>this.drainSoon(e))}drainSoon(e){e.queue.length!==0&&setImmediate(()=>{if(this.disposed||!this.on||e.turn||this.chats.get(e.id)!==e)return;let t=e.queue.shift();t&&(this.publish({type:`queue`,chatId:e.id,queue:this.queueOf(e)}),this.begin(e,t.text,t.context))})}settleQuestions(e){if(e.questions.length!==0){for(let t of e.questions.splice(0))t.resolve(null);this.publish({type:`permission`,chatId:e.id,permission:null})}}halt(e){this.settleQuestions(e);let t=e.turn;if(!t)return;if(e.connecting){t.cancelled=!0,e.turn=null,e.connecting=!1,this.touch(e),this.saveAll(),this.publishChats(),this.drainSoon(e);return}let n=e.process;n&&e.sessionId&&n.cancel(e.sessionId),!t.stopping&&(t.stopping=setTimeout(()=>{e.turn===t&&n&&(this.othersWorking(e)?this.stoppedBy(e,t,`app.agent.stopped`):(this.release(n),n.kill(!0)))},this.timings.stopMs),t.stopping.unref())}othersWorking(e){for(let t of this.chats.values())if(t!==e&&t.agentId===e.agentId&&t.turn!==null)return!0;return!1}abandon(e){this.settleQuestions(e);let t=e.turn;t&&(t.cancelled=!0,t.stopping&&clearTimeout(t.stopping),e.turn=null,e.process&&e.sessionId&&e.process.cancel(e.sessionId))}shutDown(){for(let e of this.chats.values()){this.settleQuestions(e);let t=e.turn;if(t){t.cancelled=!0,t.stopping&&clearTimeout(t.stopping),e.turn=null,e.connecting=!1;for(let t of e.transcript.stopRunning())this.publish({type:`tool`,chatId:e.id,tool:t});e.transcript.notice(r(`app.agent.stopped`)),this.touch(e)}e.queue=[]}for(let e of[...this.live])e.kill(!0);this.processes.clear(),this.started.clear()}processOf(e){let t=this.processes.get(e);if(t)return t;let n={update:e=>this.update(e),permission:(e,t)=>this.requestPermission(e,t),read:e=>this.readText(e),write:e=>this.writeText(e),gone:(e,t,n,r)=>this.gone(e,t,n,r)},r=(async()=>{let t=f(e,this.host.env,this.host.home,this.host.folder);if(!t)throw new he;let r=await Se.launch(t,{folder:this.host.folder,env:this.host.env,version:this.host.version,connectMs:this.timings.connectMs,killMs:this.timings.killMs},n);if(this.disposed||!this.on)throw r.kill(!0),Error(`closed`);return this.live.add(r),this.started.set(e,r),this.owners.set(r,/* @__PURE__ */ new Map),r.pid!==void 0&&Ie(this.host.home,this.host.folder,{pid:r.pid,command:r.command}),r})();return this.processes.set(e,r),r.catch(()=>{this.processes.get(e)===r&&this.processes.delete(e)}),r}mcpServers(){let e=this.host.mcp;return e?[{name:`penstock`,command:e.command,args:[...e.args,`--project`,this.host.folder],env:Object.entries(e.env??{}).map(([e,t])=>({name:e,value:t}))}]:[]}async sessionOf(e,t){let n=this.owners.get(t);if(e.process=t,e.sessionId&&n?.get(e.sessionId)===e)return e.sessionId;let i=e.sessionId;if(i&&t.loadSession){e.fenced=!0,n?.set(i,e);try{let n=await t.loadSessionById(i,this.host.folder,this.mcpServers());return this.offer(e,n),await this.settle(e,!1),i}catch(e){if(n?.delete(i),F(e)||e instanceof N)throw e}finally{e.fenced=!1}}let a=await t.newSession(this.host.folder,this.mcpServers());if(e.sessionId=a.sessionId,n?.set(a.sessionId,e),this.offered.set(e.agentId,a.options),this.offer(e,a.options),await this.settle(e,!0),i!==null){let t=e.transcript.notice(r(`app.agent.newSession`));this.publish(this.entryEvent(e,t))}return g(this.host.home)!==e.agentId&&m(this.host.home,e.agentId),this.markUnsaved(e),a.sessionId}offer(e,t){(t.length!==0||e.options.length!==0)&&(e.options=t,me(this.host.home,e.agentId,t),this.publishOptions(e))}publishOptions(e){this.publish({type:`options`,chatId:e.id,options:e.shownOptions()}),this.markUnsaved(e)}desired(e,t){let n=/* @__PURE__ */ new Map,r=t?l(this.host.home,e.agentId):{};for(let t of e.options){let i=e.wanted.get(t.id)??(j.includes(t.category)?r[t.category]:void 0);i!==void 0&&i!==t.current&&u(t,i)&&n.set(t.id,i)}return n}settle(e,t){let n=e.configured.then(async()=>{let n=e.process,r=e.sessionId;if(n&&n.alive&&r)for(let i of d(e.options)){let a=this.desired(e,t).get(i.id);if(a===void 0)continue;let o=e.options.find(e=>e.id===i.id);if(o)try{await this.change(e,n,r,o,a)}catch(t){if(F(t))throw t;e.wanted.delete(i.id)}}});return e.configured=n.catch(()=>void 0),n}async change(e,t,n,r,i){let a=await t.setOption(n,r,i);e.sessionId===n&&(e.options=a===null?e.options.map(e=>e.id===r.id?{...e,current:i}:e):a.length>0?a:e.options.map(e=>e.id===r.id?{...e,current:i}:e),e.wanted.get(r.id)===i&&e.wanted.delete(r.id),me(this.host.home,e.agentId,e.options),this.publishOptions(e))}shown(e){if(e.options.length===0){let t=this.offered.get(e.agentId)??pe(this.host.home,e.agentId)?.options;if(!t)return;e.options=t.map(e=>({...e}))}if(e.sessionId===null)for(let[t,n]of this.desired(e,!0))e.wanted.set(t,n)}async setOption(e,t,n){this.requireOn();let r=this.chat(e);this.shown(r);let i=r.options.find(e=>e.id===t);if(!i)throw E(404,`app.agent.reason.noSuchOption`,{option:t.slice(0,80)});if(!u(i,n))throw E(400,`app.agent.reason.badOptionValue`,{value:n.slice(0,80)});r.wanted.set(i.id,n),j.includes(i.category)&&ce(this.host.home,r.agentId,i.category,n),this.publishOptions(r);let a=r.process,o=r.sessionId;if(!r.turn&&a?.alive&&o&&this.owners.get(a)?.get(o)===r){let e=r.configured.then(()=>this.change(r,a,o,i,n));r.configured=e.catch(()=>void 0);try{await e}catch(e){throw r.wanted.delete(i.id),this.publishOptions(r),E(502,`app.agent.reason.optionRefused`,{reason:M(e instanceof Error?e.message:String(e))})}}return r.shownOptions()}gone(e,t,n,r){this.live.delete(e),e.pid!==void 0&&Le(this.host.home,this.host.folder,e.pid);let i=this.owners.get(e);if(this.owners.delete(e),this.release(e),i)for(let a of i.values()){if(a.process!==e)continue;a.process=null;let i=a.turn;i&&(r?this.stoppedBy(a,i):this.finish(a,i,{key:le(n),detail:n===``?t:`${t}: ${n}`},`end_turn`))}}release(e){this.started.get(e.agentId)===e&&(this.started.delete(e.agentId),this.processes.delete(e.agentId))}stoppedBy(e,t,n=`app.agent.killed`){if(e.turn!==t)return;this.flush(),t.stopping&&clearTimeout(t.stopping),this.settleQuestions(e),e.turn=null,e.connecting=!1,e.failure=null;for(let t of e.transcript.stopRunning())this.publish({type:`tool`,chatId:e.id,tool:t});let i=e.transcript.notice(r(n));this.publish(this.entryEvent(e,i)),this.touch(e),this.saveAll(),this.publishChats(),this.drainSoon(e)}ownerOf(e){for(let t of this.owners.values()){let n=t.get(e);if(n)return n}return null}schedule(e,t){let n=this.dirty.get(e);n||(n=/* @__PURE__ */ new Set,this.dirty.set(e,n)),n.add(t.id),!this.flushTimer&&(this.flushTimer=setTimeout(()=>this.flush(),this.timings.flushMs),this.flushTimer.unref())}flush(){if(this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.dirty.size===0)return;let e=[...this.dirty];this.dirty.clear();for(let[t,n]of e){for(let e of n){let n=t.transcript.find(e);n&&this.feed.publish(this.entryEvent(t,n))}this.markUnsaved(t)}}relative(e){if(!z.isAbsolute(e))return e;let t=this.host.files.relative(e);return t.startsWith(`..`)||t===``?e:t}update(e){let t=this.ownerOf(e.sessionId);if(!t||t.fenced)return;t.turn&&(t.turn.heard=performance.now());let n=e.update;switch(n.sessionUpdate){case`agent_message_chunk`:case`agent_thought_chunk`:{if(n.content.type!==`text`)return;let e=n.sessionUpdate===`agent_message_chunk`?`agent`:`thought`;this.schedule(t,t.transcript.message(e,n.content.text,n.messageId??null));return}case`tool_call`:{this.keepInput(t,n.toolCallId,n.rawInput);let e=t.transcript.upsertTool(b(n,void 0,e=>this.relative(e)));this.publish(this.entryEvent(t,e));return}case`tool_call_update`:{this.keepInput(t,n.toolCallId,n.rawInput),(n.status===`completed`||n.status===`failed`)&&t.grants.delete(n.toolCallId);let e=t.transcript.tool(n.toolCallId),r=t.transcript.upsertTool(b(n,e,e=>this.relative(e)));this.publish(this.entryEvent(t,r));return}case`config_option_update`:{let e=oe(n.configOptions,null);if(e.length===0)return;for(let n of e)t.wanted.get(n.id)===n.current&&t.wanted.delete(n.id);this.offer(t,e);return}case`current_mode_update`:if(!t.options.some(e=>e.legacy))return;t.options=t.options.map(e=>e.legacy&&u(e,n.currentModeId)?{...e,current:n.currentModeId}:e),this.publishOptions(t);return;case`plan`:{let e=t.transcript.plan(n.entries);this.publish(this.entryEvent(t,e)),this.publishChats();return}default:return}}keepInput(e,t,n){n!=null&&(e.rawInputs.set(t,n),e.rawInputs.size>40&&e.rawInputs.delete(e.rawInputs.keys().next().value))}async announced(e,t,n){let r=Date.now()+200;for(;!e.rawInputs.has(t)&&!n.aborted&&Date.now()<r;)await new Promise(e=>setTimeout(e,5))}async requestPermission(e,t){let n=this.ownerOf(e.sessionId);if(!n||n.fenced||t.aborted||!n.turn)return Z;this.asked+=1;let r=`ask:${this.asked}`,i=e.toolCall.toolCallId;if(e.toolCall.rawInput==null&&!n.rawInputs.has(i)&&await this.announced(n,i,t),t.aborted||!n.turn)return Z;let a=se(r,e.toolCall,e.options,n.transcript.tool(i),e=>this.relative(e)),o=e.toolCall.rawInput??n.rawInputs.get(i);if($e(a.tool,o)||it(a.tool,o)){let e=nt(a);if(e!==null)return{outcome:{outcome:`selected`,optionId:e}}}if(et(a.tool)&&(a=tt(a),Ze(a.tool)&&a.tool.diffs.length===0)){let r=await this.previewOf(n,e.toolCall.toolCallId,e.toolCall.rawInput);if(r&&(a={...a,tool:{...a.tool,...r}}),t.aborted||!n.turn)return Z}let s=a;return new Promise(e=>{let r={permission:s,grants:!0,resolve:t=>e(t===null?Z:{outcome:{outcome:`selected`,optionId:t}})},i=()=>{let e=n.questions.indexOf(r);e<0||(n.questions.splice(e,1),this.publish({type:`permission`,chatId:n.id,permission:n.questions[0]?.permission??null}),this.publishChats())};t.addEventListener(`abort`,()=>{i(),e(Z)}),this.ask(n,r)})}ask(e,t){let n=e.transcript.upsertTool(t.permission.tool);this.publish(this.entryEvent(e,n)),e.questions.push(t),e.questions.length===1&&(this.publish({type:`permission`,chatId:e.id,permission:t.permission}),this.publishChats())}async previewOf(e,t,n){let r=at(n??e.rawInputs.get(t));if(!r)return null;let i;try{i=this.host.files.resolve(r.file)}catch{return null}let a;try{a=await(this.host.preview??ke)(i,r.operations)}catch{return null}if(!a.ok)return null;let o=this.relative(i);return{diffs:[{path:o,oldText:a.before,newText:a.after}],paths:[o],locations:[{path:o,line:null}]}}grant(e,t){(t.kind===`edit`||t.kind===`delete`||t.kind===`move`||t.diffs.length>0)&&t.paths.length!==0&&e.grants.set(t.id,new Set(t.paths))}granted(e,t){for(let[n,r]of e.grants)if(r.delete(t))return r.size===0&&e.grants.delete(n),!0;return!1}target(e){try{return this.host.files.resolve(e)}catch(e){throw new U(Y,e instanceof Error?e.message:String(e))}}known(e){let t=this.ownerOf(e);if(!t||t.fenced)throw new U(Y,r(`app.agent.reason.notRunning`));return t}readText(e){let t=this.known(e.sessionId),n=this.target(e.path),i;try{let e=H(n);if(!e.isFile())throw new U(Y,r(`app.agent.reason.noSuchFile`));if(e.size>J)throw new U(X,r(`app.agent.reason.fileTooLarge`,{limit:J/1048576}));i=B(n,`utf8`)}catch(e){throw e instanceof U?e:new U(-32002,r(`app.agent.reason.noSuchFile`))}this.remember(t,this.relative(n));let a=Math.max(1,e.line??1);if(a===1&&(e.limit===void 0||e.limit===null))return{content:i};let o=i.split(`
@@ -1 +1 @@
1
- export{i as flowFindings,o as pathsCommand,c as unreadableDmn}from"./chunk-analyze-CUxuBgNS.js";
1
+ export{i as flowFindings,o as pathsCommand,c as unreadableDmn}from"./chunk-analyze-D_2dPr5n.js";
@@ -0,0 +1 @@
1
+ import{r as e}from"./chunk-translator-BAjzyPKE.js";import{$ as t,_n as n,et as r,n as i,tt as a,vn as o}from"./chunk-src-CxTpK8wk.js";import{n as s}from"./chunk-moddle-Dlk0NR-u.js";import{r as c}from"./chunk-docs-CY6ICsip.js";import{s as l}from"./chunk-failure-BK7fu4Yo.js";import{r as u}from"./chunk-context-B-5CZFAT.js";import{t as d}from"./chunk-report-CtkTRSGT.js";import{t as f}from"./chunk-plural-Di3FH8HP.js";import{t as p}from"./chunk-formChecks-BOiD8Idv.js";import{readFileSync as m}from"node:fs";function h(e,t){let n=e[t];return n?.name?.replace(/\s+/g,` `).trim()||(n?.$type?a(n.$type):t)}async function g(e){return await s(`plain`).fromXML(m(e,`utf8`))}async function _(e){return r((await g(e)).rootElement)}async function v(t,n){let r=[],i=[],a=0;for(let o of t){let t;try{t=await _(o)}catch(e){a+=1,i.push({file:u(o),scenarios:[]}),r.push(l(u(o),e));continue}i.push({file:u(o),scenarios:t}),n===`md`?(r.push(`## ${u(o)}`,``),t.forEach((t,n)=>{r.push(`### ${n+1}. ${t.start} → ${t.ends.join(`, `)||e(`app.output.end`)}`,``),t.decisions.forEach(t=>r.push(`- [ ] ${t.boundary?e(`app.output.boundaryFires`,{decision:t.decision,boundary:t.boundary}):e(`app.output.decisionWay`,{decision:t.decision,way:t.way})}${t.condition?` (\`${t.condition}\`)`:``}`)),r.push(e(`app.output.runsSteps`,{steps:t.steps.join(` → `)||e(`app.output.noSteps`)}),``)})):(r.push(`${u(o)} ${f(t.length,`app.output.count.scenario`)}`),t.forEach((t,n)=>{r.push(` ${String(n+1).padStart(2)}. ${[t.start,...t.steps,...t.ends].join(` → `)}`);for(let n of t.decisions){let t=n.boundary?e(`app.output.firesOn`,{boundary:n.boundary,decision:n.decision}):e(`app.output.decisionWay`,{decision:n.decision,way:n.way});r.push(` ${t}${n.condition?e(`app.output.when`,{condition:n.condition}):``}`)}}))}return n===`json`?{ok:a===0,lines:[JSON.stringify(i,null,2)]}:{ok:a===0,lines:r}}async function y(e){let{rootElement:n,elementsById:r}=await g(e);return{problems:t(n).problems,names:e=>h(r,e)}}async function b(e){let{rootElement:t}=await o(m(e,`utf8`));return i(t)}async function x(e){try{return await o(m(e,`utf8`)),null}catch(t){if(!(t instanceof n))throw t;return{file:e,rule:`dmn`,message:t.message,severity:`error`}}}function S(e){try{let t=m(e,`utf8`).slice(0,4096);return t.trimStart().startsWith(`{`)&&t.includes(`"components"`)}catch{return!1}}function C(e){return p(JSON.parse(m(e,`utf8`)))}async function w(t){let n=(e,n,r)=>{let i=c(e,n)?.severity===`warning`;return d(e,{file:t,rule:n,message:r,severity:i?`warning`:`error`})};if(/\.dmn$/i.test(t))return(await b(t)).map(e=>n(`table`,e.kind,e.detail));if(/\.form$/i.test(t))return C(t).map(e=>n(`form`,e.kind,e.detail));let{problems:r,names:i}=await y(t);return r.map(t=>n(`flow`,t.kind,t.trace.length>0?e(`app.rules.web.detailWithPath`,{detail:t.detail,path:t.trace.map(i).join(` → `)}):t.detail))}export{S as a,x as c,w as i,C as n,v as o,b as r,_ as s,y as t};
@@ -0,0 +1 @@
1
+ import{r as e}from"./chunk-translator-BAjzyPKE.js";import{rt as t}from"./chunk-src-CxTpK8wk.js";import{a as n,o as r,r as i}from"./chunk-moddle-Dlk0NR-u.js";import{f as a,g as o,m as s,y as c}from"./chunk-engine-CxgdJ2wO.js";function l(e){return typeof e==`string`?e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e[0].toUpperCase()+e.slice(1)).join(``):``}function u(e){return(e.$type??e.type??``).replace(/^[a-z0-9]+:/i,``)}function d(e){let t=e.replace(/[^A-Za-z0-9_.-]/g,`_`);return/^[A-Za-z_]/.test(t)?t:`_${t}`}function f(e,t,n){if(!n.fromName)return null;let r=l(t);return r?d((typeof n.pattern==`string`&&n.pattern?n.pattern:`{Type}_{Name}`).replace(`{Type}`,()=>u(e)).replace(`{Name}`,()=>r)):null}const p=1e6;function m(e,t){if(!t(e))return e;for(let n=2;n<p;n+=1){let r=`${e}_${n}`;if(!t(r))return r}return`${e}_${p}`}function h(e,t){let n=e?.defaults;if(typeof n!=`object`||!n||!Object.hasOwn(n,t))return{};let r=n[t];return typeof r==`object`&&r?r:{}}const g={task:{type:`bpmn:Task`},"user-task":{type:`bpmn:UserTask`},"service-task":{type:`bpmn:ServiceTask`},"script-task":{type:`bpmn:ScriptTask`},"send-task":{type:`bpmn:SendTask`},"receive-task":{type:`bpmn:ReceiveTask`},"business-rule-task":{type:`bpmn:BusinessRuleTask`},"manual-task":{type:`bpmn:ManualTask`},"call-activity":{type:`bpmn:CallActivity`},"sub-process":{type:`bpmn:SubProcess`},"end-event":{type:`bpmn:EndEvent`},"intermediate-catch-event":{type:`bpmn:IntermediateCatchEvent`},"intermediate-throw-event":{type:`bpmn:IntermediateThrowEvent`},"exclusive-gateway":{type:`bpmn:ExclusiveGateway`},"parallel-gateway":{type:`bpmn:ParallelGateway`},"inclusive-gateway":{type:`bpmn:InclusiveGateway`},"event-based-gateway":{type:`bpmn:EventBasedGateway`}},_={message:`bpmn:MessageEventDefinition`,timer:`bpmn:TimerEventDefinition`,signal:`bpmn:SignalEventDefinition`,error:`bpmn:ErrorEventDefinition`,escalation:`bpmn:EscalationEventDefinition`,conditional:`bpmn:ConditionalEventDefinition`,terminate:`bpmn:TerminateEventDefinition`},v=(e,t,n)=>({kind:t,description:`app.cli.edit.property.${e}`,on:n}),y=[`bpmn:Task`,`bpmn:UserTask`,`bpmn:ServiceTask`,`bpmn:ScriptTask`,`bpmn:SendTask`,`bpmn:ReceiveTask`,`bpmn:BusinessRuleTask`,`bpmn:ManualTask`,`bpmn:CallActivity`,`bpmn:SubProcess`],b=[`bpmn:ServiceTask`,`bpmn:SendTask`,`bpmn:BusinessRuleTask`,`bpmn:ScriptTask`],x={name:v(`name`,`string`),documentation:v(`documentation`,`string`)},S={...x,condition:v(`condition`,`string`,[`bpmn:SequenceFlow`]),class:v(`class`,`string`,b),delegateExpression:v(`delegateExpression`,`string`,b),expression:v(`expression`,`string`,b),resultVariable:v(`resultVariable`,`string`,b),topic:v(`topic`,`string`,b),asyncBefore:v(`asyncBefore`,`boolean`),asyncAfter:v(`asyncAfter`,`boolean`),assignee:v(`assignee`,`string`,[`bpmn:UserTask`]),candidateUsers:v(`candidateUsers`,`string`,[`bpmn:UserTask`]),candidateGroups:v(`candidateGroups`,`string`,[`bpmn:UserTask`]),formKey:v(`formKey`,`string`,[`bpmn:UserTask`,`bpmn:StartEvent`]),calledElement:v(`calledElement`,`string`,[`bpmn:CallActivity`]),decisionRef:v(`decisionRef`,`string`,[`bpmn:BusinessRuleTask`]),inputs:v(`inputs`,`mapping`,y),outputs:v(`outputs`,`mapping`,y)},C={...x,condition:v(`condition`,`string`,[`bpmn:SequenceFlow`]),class:v(`class`,`string`,[`bpmn:ServiceTask`,`bpmn:SendTask`,`bpmn:BusinessRuleTask`]),delegateExpression:v(`delegateExpression`,`string`,[`bpmn:ServiceTask`,`bpmn:SendTask`,`bpmn:BusinessRuleTask`]),expression:v(`expression`,`string`,[`bpmn:ServiceTask`,`bpmn:SendTask`,`bpmn:BusinessRuleTask`]),resultVariable:v(`resultVariable`,`string`,[`bpmn:ServiceTask`,`bpmn:ScriptTask`,`bpmn:BusinessRuleTask`]),async:v(`async`,`boolean`,[`bpmn:Task`,`bpmn:UserTask`,`bpmn:ServiceTask`,`bpmn:ScriptTask`,`bpmn:SendTask`,`bpmn:ReceiveTask`,`bpmn:BusinessRuleTask`,`bpmn:ManualTask`,`bpmn:CallActivity`,`bpmn:SubProcess`]),skipExpression:v(`skipExpression`,`string`,[`bpmn:Task`,`bpmn:UserTask`,`bpmn:ServiceTask`,`bpmn:ScriptTask`,`bpmn:SendTask`,`bpmn:ReceiveTask`,`bpmn:BusinessRuleTask`,`bpmn:ManualTask`]),assignee:v(`assignee`,`string`,[`bpmn:UserTask`]),candidateUsers:v(`candidateUsers`,`string`,[`bpmn:UserTask`]),candidateGroups:v(`candidateGroups`,`string`,[`bpmn:UserTask`]),formKey:v(`formKey`,`string`,[`bpmn:UserTask`,`bpmn:StartEvent`]),calledElement:v(`calledElement`,`string`,[`bpmn:CallActivity`])},w={classic:{...x,condition:v(`conditionSimple`,`string`,[`bpmn:SequenceFlow`])},"camunda-7":S,operaton:S,"cib-seven":S,flowable:C,activiti:C,"camunda-8":{...x,condition:v(`feelCondition`,`string`,[`bpmn:SequenceFlow`]),jobType:v(`jobType`,`string`,b),retries:v(`retries`,`integer`,b),assignee:v(`assignee`,`string`,[`bpmn:UserTask`]),candidateUsers:v(`candidateUsers`,`string`,[`bpmn:UserTask`]),candidateGroups:v(`candidateGroups`,`string`,[`bpmn:UserTask`]),formId:v(`formId`,`string`,[`bpmn:UserTask`]),processId:v(`processId`,`string`,[`bpmn:CallActivity`]),decisionId:v(`decisionId`,`string`,[`bpmn:BusinessRuleTask`]),inputs:v(`inputMappings`,`mapping`,y),outputs:v(`outputMappings`,`mapping`,y)}};var T=class extends Error{};function E(e,t){throw new T(`${e}: ${t}`)}function D(t,n,r){for(let i of Object.keys(t))n.includes(i)||E(r,e(`app.cli.edit.unknownField`,{key:i,allowed:n.join(`, `)}))}function O(t,n,r,i=!0){if(t!==void 0||i)return typeof t==`string`&&t.trim()||E(n,e(`app.cli.edit.mustBeAString`,{field:r})),t}function k(t,n,r){return typeof t==`number`&&Number.isFinite(t)||E(n,e(`app.cli.edit.mustBeANumber`,{field:r})),t}function A(t,n,r){(!t||typeof t!=`object`||Array.isArray(t))&&E(r,e(`app.cli.edit.propertiesMustBeAnObject`));let i=w[n],a={};for(let[o,s]of Object.entries(t)){let t=Object.hasOwn(i,o)?i[o]:void 0;t||E(r,e(`app.cli.edit.notAnEngineProperty`,{key:o,engine:n,allowed:Object.keys(i).join(`, `)})),t.kind===`string`&&typeof s!=`string`&&E(r,e(`app.cli.edit.mustBeAStringShort`,{key:o})),t.kind===`boolean`&&typeof s!=`boolean`&&E(r,e(`app.cli.edit.mustBeABoolean`,{key:o})),t.kind===`integer`&&(typeof s!=`number`||!Number.isInteger(s)||s<0)&&E(r,e(`app.cli.edit.mustBeAWholeNumber`,{key:o})),t.kind===`mapping`&&(!s||typeof s!=`object`||Array.isArray(s)||Object.values(s).some(e=>typeof e!=`string`))&&E(r,e(`app.cli.edit.mustMapNamesToStrings`,{key:o})),a[o]=s}return a}function j(e,t,n){let r=Object.hasOwn(w[e],t)?w[e][t]:void 0;return!!r&&(!r.on||r.on.includes(n))}function M(t,n){let r=Array.isArray(t)?t:[t];if(r.length===0)throw new T(e(`app.cli.edit.noOperations`));return r.map((t,r)=>{let i=e(`app.cli.edit.operationWhere`,{number:r+1});(!t||typeof t!=`object`||Array.isArray(t))&&E(i,e(`app.cli.edit.mustBeAnObject`));let a=t;switch(a.op){case`add`:return D(a,[`op`,`element`,`after`,`event`,`name`,`id`,`properties`],i),typeof a.element==`string`&&Object.hasOwn(g,a.element)||E(i,e(`app.cli.edit.elementMustBeOneOf`,{elements:Object.keys(g).join(`, `)})),a.event===void 0||typeof a.event==`string`&&Object.hasOwn(_,a.event)||E(i,e(`app.cli.edit.eventMustBeOneOf`,{events:Object.keys(_).join(`, `)})),a.event!==void 0&&!String(a.element).endsWith(`-event`)&&E(i,e(`app.cli.edit.eventOnlyForEvents`)),a.id!==void 0&&!/^[A-Za-z_][\w.-]*$/.test(String(a.id))&&E(i,e(`app.cli.edit.idMustBeValid`)),{op:`add`,element:a.element,after:O(a.after,i,`after`),event:a.event,name:O(a.name,i,`name`,!1),id:O(a.id,i,`id`,!1),properties:a.properties===void 0?void 0:A(a.properties,n,i)};case`connect`:return D(a,[`op`,`from`,`to`,`name`,`condition`],i),{op:`connect`,from:O(a.from,i,`from`),to:O(a.to,i,`to`),name:O(a.name,i,`name`,!1),condition:O(a.condition,i,`condition`,!1)};case`set`:return D(a,[`op`,`id`,`properties`],i),{op:`set`,id:O(a.id,i,`id`),properties:A(a.properties,n,i)};case`remove`:return D(a,[`op`,`id`],i),{op:`remove`,id:O(a.id,i,`id`)};case`move`:return D(a,[`op`,`id`,`dx`,`dy`],i),{op:`move`,id:O(a.id,i,`id`),dx:k(a.dx,i,`dx`),dy:k(a.dy,i,`dy`)};default:return E(i,e(`app.cli.edit.opMustBeOneOf`))}})}function N(n){let r=n?w[n]:{...w.classic,...w[`camunda-7`],...w[`camunda-8`]},i={type:`object`,additionalProperties:!1,properties:Object.fromEntries(Object.entries(r).map(([n,r])=>{let i=r.kind===`mapping`?{type:`object`,additionalProperties:{type:`string`}}:{type:r.kind},a=r.on?e(`app.cli.edit.schema.onlyOn`,{types:t(r.on.map(e=>e.replace(`bpmn:`,``)))}):``;return[n,{...i,description:`${e(r.description)}${a}`}]}))};return{$schema:`https://json-schema.org/draft/2020-12/schema`,title:n?e(`app.cli.edit.schema.titleFor`,{engine:n}):e(`app.cli.edit.schema.title`),type:`array`,minItems:1,items:{oneOf:[{type:`object`,additionalProperties:!1,required:[`op`,`element`,`after`],properties:{op:{const:`add`,description:e(`app.cli.edit.schema.add`)},element:{enum:Object.keys(g)},after:{type:`string`,description:e(`app.cli.edit.schema.after`)},event:{enum:Object.keys(_),description:e(`app.cli.edit.schema.event`)},name:{type:`string`},id:{type:`string`,description:e(`app.cli.edit.schema.newId`)},properties:i}},{type:`object`,additionalProperties:!1,required:[`op`,`from`,`to`],properties:{op:{const:`connect`,description:e(`app.cli.edit.schema.connect`)},from:{type:`string`},to:{type:`string`},name:{type:`string`},condition:{type:`string`}}},{type:`object`,additionalProperties:!1,required:[`op`,`id`,`properties`],properties:{op:{const:`set`,description:e(`app.cli.edit.schema.set`)},id:{type:`string`},properties:i}},{type:`object`,additionalProperties:!1,required:[`op`,`id`],properties:{op:{const:`remove`,description:e(`app.cli.edit.schema.remove`)},id:{type:`string`}}},{type:`object`,additionalProperties:!1,required:[`op`,`id`,`dx`,`dy`],properties:{op:{const:`move`,description:e(`app.cli.edit.schema.move`)},id:{type:`string`},dx:{type:`number`},dy:{type:`number`}}}]}}}const P={"bpmn:EndEvent":[`message`,`signal`,`error`,`escalation`,`terminate`],"bpmn:IntermediateThrowEvent":[`message`,`signal`,`escalation`],"bpmn:IntermediateCatchEvent":[`message`,`timer`,`signal`,`conditional`]},F=[`bpmn:ReceiveTask`,`bpmn:IntermediateCatchEvent`];function I(t,n){if(n&&(!(P[t]??[]).includes(n)||!Object.hasOwn(_,n)))throw new T(e(`app.patch.eventNotAllowed`,{type:u({type:t}),event:n}))}function L(t,n,r){if(t.id===n.id)throw new T(e(`app.patch.sameElement`,{id:t.id}));if(t.type===`bpmn:EndEvent`)throw new T(e(`app.cli.edit.afterEndEvent`,{id:t.id}));if(n.type===`bpmn:StartEvent`)throw new T(e(`app.patch.startEventTarget`,{id:n.id}));if(n.type===`bpmn:BoundaryEvent`)throw new T(e(`app.patch.boundaryTarget`,{id:n.id}));if(t.scope!==n.scope)throw new T(e(`app.patch.differentScopes`,{from:t.id,to:n.id}));if(t.type===`bpmn:EventBasedGateway`&&!F.includes(n.type))throw new T(e(`app.patch.eventBasedTarget`,{to:n.id}));if(r(t.id,n.id))throw new T(e(`app.patch.duplicateFlow`,{from:t.id,to:n.id}))}const ee=[0,1,-1,2,-2,3,-3,4,-4];function te(e){return e.endsWith(`Event`)?{width:36,height:36}:e.endsWith(`Gateway`)?{width:50,height:50}:e===`bpmn:SubProcess`?{width:350,height:200}:{width:100,height:80}}function ne(e,t,n=0){return e.x<t.x+t.width+n&&e.x+e.width+n>t.x&&e.y<t.y+t.height+n&&e.y+e.height+n>t.y}function R(e,t,n){if(!t||!/(Event|Gateway)$/.test(e))return;let r=Math.max(n.width,Math.min(t.length*7,120));return{x:Math.round(n.x+n.width/2-r/2),y:n.y+n.height+4,width:r,height:28}}function z(e,t){return t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}function B(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function V(e,t,n,r,i=50,a){let{width:o,height:s}=te(t),c=e.y+e.height/2,l=[];for(let t=0;t<6;t+=1)for(let n of ee)l.push({x:Math.round(e.x+e.width+i+t*(o+i)),y:Math.round(c-s/2+n*(s+i*.6)),width:o,height:s});let u=e=>!n.some(t=>ne(e,t,12)),d=e=>{let n=R(t,a,e);return u(e)&&(!n||u(n))},f=e=>!r||z(r,e);return l.find(e=>f(e)&&d(e))??l.find(d)??l[0]}function H(e,t){let n=B(e),r=B(t);if(t.x>=e.x+e.width){let i={x:e.x+e.width,y:n.y},a={x:t.x,y:r.y};if(i.y===a.y)return[i,a];let o=Math.round((i.x+a.x)/2);return[i,{x:o,y:i.y},{x:o,y:a.y},a]}let i=Math.max(e.y+e.height,t.y+t.height)+25;return[{x:n.x,y:e.y+e.height},{x:n.x,y:i},{x:r.x,y:i},{x:r.x,y:t.y+t.height}]}const U=[`class`,`delegateExpression`,`expression`,`topic`],W=[`class`,`delegateExpression`,`expression`];function G(t,n,r,i){for(let t of Object.keys(i))if(!j(n,t,r.type))throw new T(e(`app.cli.edit.doesNotApply`,{key:t,type:u(r),id:r.id}));for(let[e,a]of Object.entries(i))K(t,n,r,e,a)}function K(e,t,n,r,i){let{modeling:a,moddle:c}=e;if(r===`name`)return a.updateProperties(n,{name:i});if(r===`documentation`)return a.updateProperties(n,{documentation:[c.create(`bpmn:Documentation`,{text:i})]});if(r===`condition`)return a.updateProperties(n,{conditionExpression:c.create(`bpmn:FormalExpression`,{body:i})});if(s(t))return q(e,t,n,r,i);if(o(t))return J(e,t,n,r,i);if(t===`camunda-8`)return Y(e,n,r,i)}function q(e,t,n,r,i){let{modeling:o,moddle:s}=e,c=a(t);if(U.includes(r)){let e=Object.fromEntries([`class`,`delegateExpression`,`expression`,`topic`,`type`].map(e=>[`${c}:${e}`,void 0])),t=r===`topic`?{[`${c}:type`]:`external`,[`${c}:topic`]:i}:{[`${c}:${r}`]:i};return o.updateProperties(n,{...e,...t})}if(r===`inputs`||r===`outputs`){let t=X(e,n,`${c}:InputOutput`),a=Object.entries(i).map(([e,t])=>s.create(r===`inputs`?`${c}:InputParameter`:`${c}:OutputParameter`,{name:e,value:t}));return o.updateModdleProperties(n,t,{[r===`inputs`?`inputParameters`:`outputParameters`]:a})}return o.updateProperties(n,{[`${c}:${r}`]:i})}function J(e,t,n,r,i){let o=a(t);if(W.includes(r)){let t=Object.fromEntries([`class`,`delegateExpression`,`expression`,`type`].map(e=>[`${o}:${e}`,void 0]));return e.modeling.updateProperties(n,{...t,[`${o}:${r}`]:i})}return r===`resultVariable`?e.modeling.updateProperties(n,{[`${o}:${n.type===`bpmn:ServiceTask`?`resultVariableName`:`resultVariable`}`]:i}):e.modeling.updateProperties(n,{[`${o}:${r}`]:i})}function Y(e,t,n,r){let{modeling:i,moddle:a}=e,o=(n,r)=>{i.updateModdleProperties(t,X(e,t,n),r)};switch(n){case`jobType`:return o(`zeebe:TaskDefinition`,{type:r});case`retries`:return o(`zeebe:TaskDefinition`,{retries:String(r)});case`assignee`:case`candidateUsers`:case`candidateGroups`:return o(`zeebe:AssignmentDefinition`,{[n]:r});case`formId`:return o(`zeebe:FormDefinition`,{formId:r});case`processId`:return o(`zeebe:CalledElement`,{processId:r});case`decisionId`:return o(`zeebe:CalledDecision`,{decisionId:r});case`inputs`:case`outputs`:{let e=Object.entries(r).map(([e,t])=>a.create(n===`inputs`?`zeebe:Input`:`zeebe:Output`,{target:e,source:t}));return o(`zeebe:IoMapping`,{[n===`inputs`?`inputParameters`:`outputParameters`]:e})}}}function X(e,t,n){let{modeling:r,moddle:i}=e,a=t.businessObject.extensionElements;a||(a=i.create(`bpmn:ExtensionElements`,{values:[]}),r.updateProperties(t,{extensionElements:a}));let o=(a.values??[]).find(e=>e.$type===n);if(o)return o;let s=i.create(n);return s.$parent=a,r.updateModdleProperties(t,a,{values:[...a.values??[],s]}),s}function Z(e,t){let n={},r=e.extensionElements?.values??[],i=e=>r.find(t=>t.$type===e),c=(e,t)=>{t!=null&&t!==``&&(n[e]=t)};c(`documentation`,e.documentation?.[0]?.text),c(`condition`,e.conditionExpression?.body);let l=e.eventDefinitions?.[0]?.$type;if(l&&c(`event`,Object.entries(_).find(([,e])=>e===l)?.[0]),s(t)){let n=a(t);for(let t of Object.keys(w[`camunda-7`])){if([`inputs`,`outputs`,`name`,`documentation`,`condition`].includes(t))continue;let r=e.get(`${n}:${t}`);(typeof r!=`boolean`||Object.prototype.hasOwnProperty.call(e,t))&&c(t,r)}let r=i(`${n}:InputOutput`),o=e=>e?.length?Object.fromEntries(e.map(e=>[e.name,String(e.value??``)])):void 0;c(`inputs`,o(r?.inputParameters)),c(`outputs`,o(r?.outputParameters))}if(o(t)){let n=a(t);for(let r of Object.keys(w[t])){if([`name`,`documentation`,`condition`,`resultVariable`].includes(r))continue;let t=e.get(`${n}:${r}`);(typeof t!=`boolean`||Object.prototype.hasOwnProperty.call(e,r))&&c(r,t)}c(`resultVariable`,e.get(`${n}:resultVariableName`)??e.get(`${n}:resultVariable`))}if(t===`camunda-8`){let e=i(`zeebe:TaskDefinition`);c(`jobType`,e?.type),c(`retries`,e?.retries===void 0?void 0:Number(e.retries));let t=i(`zeebe:AssignmentDefinition`);c(`assignee`,t?.assignee),c(`candidateUsers`,t?.candidateUsers),c(`candidateGroups`,t?.candidateGroups),c(`formId`,i(`zeebe:FormDefinition`)?.formId),c(`processId`,i(`zeebe:CalledElement`)?.processId),c(`decisionId`,i(`zeebe:CalledDecision`)?.decisionId);let n=i(`zeebe:IoMapping`),r=e=>e?.length?Object.fromEntries(e.map(e=>[e.target,String(e.source??``)])):void 0;c(`inputs`,r(n?.inputParameters)),c(`outputs`,r(n?.outputParameters))}return n}const Q=`bpmn:SequenceFlow`;function re(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(36).padStart(7,`0`).slice(-7)}function ie(e){return e.endsWith(`Gateway`)?`Gateway`:e.endsWith(`Event`)?`Event`:`Activity`}function ae(e){switch(e.op){case`add`:return[e.after];case`connect`:return[e.from,e.to];default:return[e.id]}}function oe(e){let t=/* @__PURE__ */ new Map;return e.map((e,n)=>{let r=/* @__PURE__ */ new Set;for(let n of ae(e)){let e=t.get(n);e!==void 0&&r.add(e)}return e.op===`add`&&e.id&&!t.has(e.id)&&t.set(e.id,n),[...r].sort((e,t)=>e-t)})}var $=class{nodes=/* @__PURE__ */ new Map;flows=/* @__PURE__ */ new Map;shapes=/* @__PURE__ */ new Map;edges=/* @__PURE__ */ new Map;pairs=/* @__PURE__ */ new Set;taken=/* @__PURE__ */ new Set;plane;moddle;properties;definitions;engine;conventions;gap;constructor(e,t,n,r=50){this.definitions=e,this.engine=t,this.conventions=n,this.gap=r,this.moddle=i(e),this.plane=e.diagrams?.[0]?.plane,this.properties={moddle:this.moddle,modeling:{updateProperties:(e,t)=>{for(let[n,r]of Object.entries(t))e.businessObject.set(n,r)},updateModdleProperties:(e,t,n)=>{for(let[e,r]of Object.entries(n))t.set(e,r)}}},this.index()}index(){let e=e=>{typeof e==`string`&&this.taken.add(e)},t=/* @__PURE__ */ new Set,n=[this.definitions];for(;n.length>0;){let r=n.pop();if(r&&typeof r==`object`&&!t.has(r)){if(t.add(r),Array.isArray(r))n.push(...r);else{e(r.id);for(let[e,t]of Object.entries(r))!e.startsWith(`$`)&&t&&typeof t==`object`&&n.push(t)}}}for(let e of this.definitions.rootElements??[])if(e.$type===`bpmn:Process`&&this.walk(e),e.$type===`bpmn:Collaboration`){this.nodes.set(e.id,{bo:e,kind:`root`});for(let t of e.participants??[])this.nodes.set(t.id,{bo:t,kind:`container`}),t.processRef&&this.walk(t.processRef)}for(let e of this.plane?.planeElement??[]){let t=e.bpmnElement?.id;t&&(e.$type===`bpmndi:BPMNShape`&&this.shapes.set(t,e),e.$type===`bpmndi:BPMNEdge`&&this.edges.set(t,e))}}walk(e){this.nodes.has(e.id)||this.nodes.set(e.id,{bo:e,kind:`root`});for(let t of e.laneSets?.flatMap(e=>this.lanesOf(e))??[])this.nodes.set(t.id,{bo:t,kind:`container`});for(let t of e.flowElements??[])t.$type===Q?(this.flows.set(t.id,t),this.pairs.add(`${t.sourceRef?.id}>${t.targetRef?.id}`)):t.$instanceOf(`bpmn:FlowNode`)&&(this.nodes.set(t.id,{bo:t,kind:`node`}),t.$instanceOf(`bpmn:SubProcess`)&&this.walk(t))}lanesOf(e){return(e.lanes??[]).flatMap(e=>[e,...e.childLaneSet?this.lanesOf(e.childLaneSet):[]])}has(e){return this.nodes.has(e)||this.flows.has(e)}node(t){let n=this.nodes.get(t);if(!n)throw new T(e(`app.cli.edit.noSuchElement`,{id:t}));return n}freshId(e,t){let n=e===Q?`Flow`:ie(e);for(let e=0;;e+=1){let r=`${n}_${re(e===0?t:`${t}#${e}`)}`;if(!this.taken.has(r))return r}}boundsOf(e){let t=this.shapes.get(e)?.bounds;return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}pointsOf(e){let t=this.edges.get(e)?.waypoint;return t?t.map(e=>({x:e.x,y:e.y})):void 0}snapshot(e){let t=this.flows.get(e),n=t??this.nodes.get(e)?.bo,r=n?.$parent;return{id:e,type:n?.$type??``,...n?.name?{name:n.name}:{},...this.boundsOf(e)?{bounds:this.boundsOf(e)}:{},...t?{waypoints:this.pointsOf(e),source:t.sourceRef?.id,target:t.targetRef?.id}:{},...r?.id&&r.$type!==`bpmn:Definitions`?{parent:r.id}:{},...n?.attachedToRef?.id?{attachedTo:n.attachedToRef.id}:{}}}scopeOf(e){return e.attachedToRef?e.attachedToRef.$parent:e.$parent}shape(e,t){let n=this.moddle.create(`dc:Bounds`,t),r={id:this.uniqueDi(e.id),bpmnElement:e,bounds:n};e.$type===`bpmn:ExclusiveGateway`&&(r.isMarkerVisible=!0),e.$type===`bpmn:SubProcess`&&(r.isExpanded=!0);let i=this.moddle.create(`bpmndi:BPMNShape`,r);this.plane.get(`planeElement`).push(i),i.$parent=this.plane,this.shapes.set(e.id,i)}uniqueDi(e){let t=m(`${e}_di`,e=>this.taken.has(e));return this.taken.add(t),t}edge(e,t){let n=this.moddle.create(`bpmndi:BPMNEdge`,{id:this.uniqueDi(e.id),bpmnElement:e,waypoint:t.map(e=>this.moddle.create(`dc:Point`,e))});this.plane.get(`planeElement`).push(n),n.$parent=this.plane,this.edges.set(e.id,n)}reroute(e){let t=this.flows.get(e),n=this.edges.get(e),r=this.boundsOf(t?.sourceRef?.id),i=this.boundsOf(t?.targetRef?.id);n&&r&&i&&n.set(`waypoint`,H(r,i).map(e=>this.moddle.create(`dc:Point`,e)))}unplane(e){for(let t of[this.shapes,this.edges]){let n=t.get(e);if(!n)continue;let r=this.plane.get(`planeElement`),i=r.indexOf(n);i>=0&&r.splice(i,1),t.delete(e)}}occupiedAround(e,t){let n=[];for(let[r,i]of this.nodes){if(i.kind!==`node`||t.has(r))continue;let a=this.boundsOf(r);if(!a||i.bo.$instanceOf(`bpmn:SubProcess`)&&z(a,e))continue;n.push(a);let o=this.labelOf(r,a,i.bo);o&&n.push(o)}return n}labelOf(e,t,n){let r=this.shapes.get(e)?.label?.bounds;return r?{x:r.x,y:r.y,width:r.width,height:r.height}:R(n.$type,n.name,t)}withinOf(e){if(e.$instanceOf(`bpmn:SubProcess`))return this.boundsOf(e.id);for(let t of this.definitions.rootElements??[]){if(t.$type!==`bpmn:Collaboration`)continue;let n=(t.participants??[]).find(t=>t.processRef===e);if(n)return this.boundsOf(n.id)}}describe(){let e=[];for(let[t,n]of this.nodes){if(n.kind===`root`)continue;let r=this.scopeOf(n.bo)?.id;e.push({id:t,type:u(n.bo),...n.bo.name?{name:n.bo.name}:{},...r?{parent:r}:{},properties:Z(n.bo,this.engine)})}for(let[t,n]of this.flows)e.push({id:t,type:u(n),...n.name?{name:n.name}:{},source:n.sourceRef?.id,target:n.targetRef?.id,properties:Z(n,this.engine)});return e.sort((e,t)=>e.id<t.id?-1:+(e.id>t.id))}snapshotAll(){return{nodes:[...this.nodes].filter(([,e])=>e.kind===`node`).map(([e])=>this.snapshot(e)),flows:[...this.flows.keys()].map(e=>this.snapshot(e))}}flowTouching(e){return[...this.flows.values()].filter(t=>t.sourceRef?.id===e||t.targetRef?.id===e).map(e=>e.id)}create(t,n,r){if(this.flows.has(t.after))throw new T(e(`app.cli.edit.isAConnection`,{id:t.after}));let i=this.node(t.after);if(i.kind!==`node`)throw new T(e(`app.cli.edit.addAfterAnElementInside`,{id:t.after,type:u(i.bo)}));if(!this.plane)throw new T(e(`app.patch.noDrawing`));let a=g[t.element].type,o=this.scopeOf(i.bo);if(I(a,t.event),t.id&&this.taken.has(t.id))throw new T(e(`app.cli.edit.idTaken`,{id:t.id}));L({id:i.bo.id,type:i.bo.$type,scope:o},{id:t.id??``,type:a,scope:o},(e,t)=>this.pairs.has(`${e}>${t}`));let s=t.id;if(!s){let e=t.name&&this.conventions.ids?f({$type:a},t.name,this.conventions.ids):null;s=e?m(e,e=>this.taken.has(e)):this.freshId(a,`${n}:${a}:${t.name??``}:${t.after}`)}this.taken.add(s);let c=this.moddle.create(a,{id:s});if(c.$parent=o,t.event){let e=this.moddle.create(_[t.event]);e.$parent=c,c.get(`eventDefinitions`).push(e)}o.get(`flowElements`).push(c),this.nodes.set(s,{bo:c,kind:`node`});for(let e of[...this.nodes.values()].filter(e=>e.kind===`container`&&e.bo.$type===`bpmn:Lane`))(e.bo.flowNodeRef??[]).includes(i.bo)&&e.bo.get(`flowNodeRef`).push(c);let l=this.boundsOf(i.bo.id);if(!l)throw new T(e(`app.patch.noDrawing`));let d=V(l,a,this.occupiedAround(l,/* @__PURE__ */ new Set([s])),this.withinOf(o),this.gap,t.name);this.shape(c,d);let p=h(this.conventions,a);Object.keys(p).length>0&&this.properties.modeling.updateProperties({businessObject:c},p),t.name&&c.set(`name`,t.name),t.properties&&G(this.properties,this.engine,{id:s,type:a,businessObject:c},t.properties);let v=this.link(i.bo,c,`${n}:flow:${i.bo.id}>${s}`);r.added.push(this.snapshot(s)),r.addedFlows.push(this.snapshot(v.id)),r.touched.push(s,v.id),r.summary=e(`app.cli.edit.added`,{type:u(c),id:s,after:i.bo.id})}link(e,t,n){let r=this.freshId(Q,n);this.taken.add(r);let i=this.moddle.create(Q,{id:r,sourceRef:e,targetRef:t}),a=this.scopeOf(e);i.$parent=a,a.get(`flowElements`).push(i),e.get(`outgoing`).push(i),t.get(`incoming`).push(i),this.flows.set(r,i),this.pairs.add(`${e.id}>${t.id}`);let o=this.boundsOf(e.id),s=this.boundsOf(t.id);return o&&s&&this.plane&&this.edge(i,H(o,s)),i}connect(t,n,r){let i=this.node(t.from),a=this.node(t.to);if(i.kind!==`node`)throw new T(e(`app.patch.notAFlowNode`,{id:t.from,type:u(i.bo)}));if(a.kind!==`node`)throw new T(e(`app.patch.notAFlowNode`,{id:t.to,type:u(a.bo)}));L({id:i.bo.id,type:i.bo.$type,scope:this.scopeOf(i.bo)},{id:a.bo.id,type:a.bo.$type,scope:this.scopeOf(a.bo)},(e,t)=>this.pairs.has(`${e}>${t}`));let o=this.link(i.bo,a.bo,`${n}:flow:${t.from}>${t.to}`);t.name&&o.set(`name`,t.name),t.condition&&G(this.properties,this.engine,{id:o.id,type:Q,businessObject:o},{condition:t.condition}),r.addedFlows.push(this.snapshot(o.id)),r.touched.push(o.id),r.summary=e(`app.cli.edit.connect`,{from:t.from,to:t.to,id:o.id})}set(t,n){let r=this.flows.get(t.id)??this.node(t.id).bo;G(this.properties,this.engine,{id:r.id,type:r.$type,businessObject:r},t.properties),n.changed.push({id:r.id,keys:Object.keys(t.properties),bounds:this.boundsOf(r.id)}),n.touched.push(r.id),n.summary=e(`app.cli.edit.set`,{keys:Object.keys(t.properties).join(`, `),id:r.id})}remove(t,n){let r=this.flows.get(t.id);if(r){this.snapshotAndDrop([r.id],n),n.summary=e(`app.cli.edit.removed`,{id:t.id});return}let i=this.node(t.id);if(i.kind===`root`)throw new T(e(`app.cli.edit.isTheRoot`,{id:t.id}));if(i.kind===`container`)throw new T(e(`app.patch.cannotRemoveContainer`,{id:t.id,type:u(i.bo)}));let a=/* @__PURE__ */ new Set([t.id]),o=[i.bo];for(;o.length>0;){let e=o.pop();for(let t of this.nodes.values())t.bo.attachedToRef===e&&!a.has(t.bo.id)&&(a.add(t.bo.id),o.push(t.bo));if(e.$instanceOf(`bpmn:SubProcess`))for(let t of e.flowElements??[])t.$type!==Q&&this.nodes.has(t.id)&&!a.has(t.id)&&(a.add(t.id),o.push(t))}let s=/* @__PURE__ */ new Set;for(let e of a)for(let t of this.flowTouching(e))s.add(t);this.snapshotAndDrop([...s,...a],n),n.summary=e(`app.cli.edit.removed`,{id:t.id})}snapshotAndDrop(e,t){let n=[...new Set(e)];for(let e of n)t.removed.push(this.snapshot(e));for(let e of n){let t=this.flows.get(e);if(t){let n=(e,t)=>{let n=e?.indexOf(t)??-1;n>=0&&e.splice(n,1)};n(t.sourceRef?.outgoing,t),n(t.targetRef?.incoming,t),n(t.$parent?.flowElements,t),t.sourceRef?.default===t&&t.sourceRef.set(`default`,void 0),this.flows.delete(e),this.pairs.delete(`${t.sourceRef?.id}>${t.targetRef?.id}`),this.unplane(e);continue}let n=this.nodes.get(e);if(!n)continue;let r=n.bo.$parent?.flowElements,i=r?.indexOf(n.bo)??-1;i>=0&&r.splice(i,1);for(let e of this.nodes.values()){let t=e.bo.flowNodeRef,r=t?.indexOf(n.bo)??-1;r>=0&&t.splice(r,1)}this.nodes.delete(e),this.unplane(e)}t.touched.push(...n)}move(t,n){if(this.flows.has(t.id))throw new T(e(`app.patch.isAFlow`,{id:t.id}));let r=this.node(t.id);if(r.kind!==`node`)throw new T(e(`app.patch.notAFlowNode`,{id:t.id,type:u(r.bo)}));if(!this.shapes.has(t.id))throw new T(e(`app.patch.noDrawing`));let i=/* @__PURE__ */ new Set([t.id]);for(let e of this.nodes.values())e.bo.attachedToRef===r.bo&&i.add(e.bo.id);if(r.bo.$instanceOf(`bpmn:SubProcess`)){let e=t=>{for(let n of t.flowElements??[])n.$type!==Q&&(i.add(n.id),n.$instanceOf(`bpmn:SubProcess`)&&e(n))};e(r.bo)}for(let e of i){let r=this.shapes.get(e)?.bounds;if(!r)continue;let i=this.boundsOf(e);r.set(`x`,i.x+t.dx),r.set(`y`,i.y+t.dy),n.moved.push({id:e,from:i,to:this.boundsOf(e)}),n.touched.push(e)}for(let e of this.flows.values()){let n=i.has(e.sourceRef?.id),r=i.has(e.targetRef?.id);if(n||r){if(n&&r){let n=this.edges.get(e.id);for(let e of n?.waypoint??[])e.set(`x`,e.x+t.dx),e.set(`y`,e.y+t.dy)}else this.reroute(e.id)}}n.summary=e(`app.cli.edit.moved`,{id:t.id,dx:t.dx,dy:t.dy})}};function se(e,t){return{index:e,operation:t,summary:``,added:[],addedFlows:[],removed:[],changed:[],moved:[],touched:[]}}function ce(t,n){let r=oe(n),i=[];return n.forEach((n,a)=>{let o=se(a,n);i.push(o);let s=r[a].find(e=>i[e].error);if(s!==void 0)o.skipped=!0,o.error=e(`app.patch.dependsOnFailed`,{number:s+1});else try{switch(n.op){case`add`:t.create(n,a,o);break;case`connect`:t.connect(n,a,o);break;case`set`:t.set(n,o);break;case`remove`:t.remove(n,o);break;case`move`:t.move(n,o)}}catch(e){if(!(e instanceof T))throw e;o.error=e.message}}),i}async function le(e,t,i){if(t.operations.length===0)return{ok:!0,xml:e,steps:[]};let a=await n(e,c(i.engine));if(!a)return{ok:!1,steps:[],failedAt:-1};let o=ce(new $(a,i.engine,i.conventions??{},i.gap),t.operations),s=o.find(e=>e.error);return s?{ok:!1,steps:o,failedAt:s.index}:{ok:!0,xml:await r(a),steps:o}}export{g as a,N as c,f as d,u as f,T as i,M as l,Z as n,_ as o,m as p,G as r,w as s,le as t,h as u};
@@ -1,11 +1,11 @@
1
- import{r as e}from"./chunk-translator-BFUJmSkR.js";import{o as t}from"./chunk-failure-BsimkHy_.js";import{t as n}from"./chunk-context-DPJmldqg.js";import{n as r}from"./chunk-project-qT-Fk_Rz.js";import{c as i,n as a,o,r as s,s as c,u as l}from"./chunk-git-BOKyPQj7.js";import{t as u}from"./chunk-plural-Bq_4vgOr.js";import{r as d}from"./chunk-commands-CeRlfHY-.js";import{n as f,t as p}from"./chunk-compose-BV9Jg348.js";import{r as m,t as h}from"./chunk-drawing-shRfnrs9.js";import g from"node:path";import{tmpdir as _}from"node:os";import{existsSync as v,mkdirSync as y,readFileSync as b,rmSync as x,writeFileSync as S}from"node:fs";const C=/(?:^|\s)(?:@penstock(?:\[bot\])?|\/penstock)\s*([^\n]*)/i,w=/^[A-Za-z0-9._\/ -]{1,300}\.bpmn(20\.xml)?$/;function T(e){let t=C.exec(e);if(!t)return null;let[n=``,r]=t[1].trim().split(/\s+/);switch(n.toLowerCase()){case``:case`report`:return{kind:`report`};case`check`:case`problems`:return{kind:`check`};case`diff`:case`against`:return r&&l(r)?{kind:`diff`,against:r}:{kind:`diff`};case`image`:case`picture`:case`screenshot`:return r&&w.test(r)&&!r.includes(`..`)?{kind:`image`,path:r}:{kind:`image`};default:return{kind:`help`}}}function E(){return[e(`app.cli.bot.help.intro`),``,e(`app.cli.bot.help.report`),e(`app.cli.bot.help.check`),e(`app.cli.bot.help.diff`),e(`app.cli.bot.help.image`)].join(`
2
- `)}const D=`<!-- penstock -->`,O=/* @__PURE__ */ new Set([`OWNER`,`MEMBER`,`COLLABORATOR`]);function k(e){let t=Number(e.PENSTOCK_HTTP_TIMEOUT_MS);return Number.isFinite(t)&&t>0?t:3e4}function A(e,t){if(e)try{return new URL(e).origin===new URL(t).origin?e:void 0}catch{return}}async function j(e,t,n){let r=await fetch(t,{...n,signal:AbortSignal.timeout(k(e))});if(!r.ok)throw Error(`${n.method??`GET`} ${new URL(t).pathname}: ${r.status} ${(await r.text()).slice(0,200)}`);return r}function M(t,n,r){for(let e of n){let n=t[e];if(n)return n}throw Error(e(`app.cli.bot.${r}`,{names:n.join(` or `)}))}function N(e){return(e??``).includes(D)}function P(e){return new Blob([b(e)],{type:`image/svg+xml`})}function F(e){return/<([^>]+)>;\s*rel="next"/.exec(e.headers.get(`link`)??``)?.[1]}function I(t){let n=!!(t.GITEA_ACTIONS||t.FORGEJO_ACTIONS||t.GITHUB_SERVER_URL&&!/github\.com|ghe\.com/.test(t.GITHUB_SERVER_URL)&&t.GITHUB_API_URL?.includes(`/api/v1`)),r=t.GITHUB_API_URL??(n?`${t.GITHUB_SERVER_URL}/api/v1`:`https://api.github.com`),i=M(t,[`GITHUB_REPOSITORY`],`noRepository`),a=M(t,[`PENSTOCK_TOKEN`,`GITHUB_TOKEN`,`GITEA_TOKEN`],`noToken`),o={Authorization:n?`token ${a}`:`Bearer ${a}`,Accept:`application/json`},s=JSON.parse(b(M(t,[`GITHUB_EVENT_PATH`],`noEventPath`),`utf8`)),c=n?50:100,l=``,u=async(e,n,a)=>{let s=await j(t,`${r}/repos/${i}${n}`,{method:e,headers:{...o,...a?{"Content-Type":`application/json`}:{}},body:a?JSON.stringify(a):void 0});return s.status===204?void 0:await s.json()},d=e=>({head:e?.head?.repo?.full_name??``,base:e?.base?.repo?.full_name??``}),f=t=>e(`app.cli.bot.fromAnotherFork`,{head:t.head?e(`app.cli.bot.theFork`,{head:t.head}):e(`app.cli.bot.aForkNoLongerExists`),base:t.base});return{name:n?`gitea`:`github`,async ask(){if(t.GITHUB_EVENT_NAME===`issue_comment`){if(s.action!==`created`||!s.issue?.pull_request||s.comment?.user?.type===`Bot`||N(s.comment?.body))return null;let e=s.comment?.author_association;if(typeof e==`string`?!O.has(e):!n)return null;l=String(s.issue.number);let t=await u(`GET`,`/pulls/${l}`),r=d(t),i={number:l,base:t.base.sha,head:`refs/pull/${l}/head`,command:s.comment.body};return r.head===r.base?i:{...i,refuse:f(r)}}let e=s.pull_request;if(!e)return null;l=String(e.number);let r=d(e),i={number:l,base:e.base.sha,head:`refs/pull/${l}/head`,command:t.PENSTOCK_COMMAND};return r.head===r.base?i:{...i,refuse:f(r)}},async comments(e){let a=[],s=1,u=`${r}/repos/${i}/issues/${l}/comments?per_page=100${n?`&limit=${c}`:``}&page=${s}`;for(;u&&s<=200;){let d=await j(t,u,{headers:o}),f=await d.json();for(let t of f){let n={id:String(t.id),body:t.body??``};if(a.push(n),e(n))return a}let p=A(F(d),r);p?(s+=1,u=p):(s+=1,u=f.length<c?void 0:`${r}/repos/${i}/issues/${l}/comments?per_page=100${n?`&limit=${c}`:``}&page=${s}`)}return a},async post(e){await u(`POST`,`/issues/${l}/comments`,{body:e})},async edit(e,t){await u(`PATCH`,`/issues/comments/${e}`,{body:t})},async attach(e){if(!n)return null;let a=new FormData;return a.append(`attachment`,P(e),g.basename(e)),(await(await j(t,`${r}/repos/${i}/issues/${l}/assets?name=${encodeURIComponent(g.basename(e))}`,{method:`POST`,headers:o,body:a})).json()).browser_download_url||null},picturesLink(){if(t.GITHUB_RUN_ID)return`${t.GITHUB_SERVER_URL??`https://github.com`}/${i}/actions/runs/${t.GITHUB_RUN_ID}`}}}function L(e){let t=M(e,[`CI_API_V4_URL`],`noGitLabApi`),n={"PRIVATE-TOKEN":M(e,[`PENSTOCK_TOKEN`,`GITLAB_TOKEN`],`noGitLabToken`)},r=e.TRIGGER_PAYLOAD?JSON.parse(b(e.TRIGGER_PAYLOAD,`utf8`)):null,i=encodeURIComponent(String(r?.project?.id??M(e,[`CI_PROJECT_ID`],`noGitLabProject`))),a=``,o=async(r,a,o)=>await(await j(e,`${t}/projects/${i}${a}`,{method:r,headers:{...n,...o?{"Content-Type":`application/json`}:{}},body:o?JSON.stringify(o):void 0})).json();return{name:`gitlab`,async ask(){if(r){if(r.object_kind!==`note`||r.object_attributes?.noteable_type!==`MergeRequest`||N(r.object_attributes.note)||r.user?.bot)return null;let e=r.merge_request;return a=String(e.iid),{number:a,base:`origin/${e.target_branch}`,head:`refs/merge-requests/${a}/head`,command:r.object_attributes.note}}return e.CI_MERGE_REQUEST_IID?(a=e.CI_MERGE_REQUEST_IID,{number:a,base:e.CI_MERGE_REQUEST_DIFF_BASE_SHA??`origin/${e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME}`,command:e.PENSTOCK_COMMAND}):null},async comments(r){let o=[],s=1;for(;s<=200;){let c=await j(e,`${t}/projects/${i}/merge_requests/${a}/notes?per_page=100&page=${s}`,{headers:n}),l=await c.json();for(let e of l){let t={id:String(e.id),body:e.body??``};if(o.push(t),r(t))return o}if(!c.headers.get(`x-next-page`)&&l.length<100)return o;s+=1}return o},async post(e){await o(`POST`,`/merge_requests/${a}/notes`,{body:e})},async edit(e,t){await o(`PUT`,`/merge_requests/${a}/notes/${e}`,{body:t})},async attach(r){let a=new FormData;return a.append(`file`,P(r),g.basename(r)),(await(await j(e,`${t}/projects/${i}/uploads`,{method:`POST`,headers:n,body:a})).json()).url||null},picturesLink(){return e.CI_JOB_URL?`${e.CI_JOB_URL}/artifacts/browse`:void 0}}}function R(e){let t=e.BITBUCKET_API_URL??`https://api.bitbucket.org/2.0`,n=M(e,[`BITBUCKET_REPO_FULL_NAME`],`noBitbucketRepo`),r=M(e,[`BITBUCKET_PR_ID`],`noBitbucketPr`),i={Authorization:`Bearer ${M(e,[`PENSTOCK_TOKEN`,`BITBUCKET_TOKEN`],`noBitbucketToken`)}`,"Content-Type":`application/json`},a=`${t}/repositories/${n}/pullrequests/${r}/comments`;return{name:`bitbucket`,async ask(){return{number:r,base:`origin/${M(e,[`BITBUCKET_PR_DESTINATION_BRANCH`],`noBitbucketBranch`)}`,command:e.PENSTOCK_COMMAND}},async comments(n){let r=[],o=`${a}?pagelen=100`,s=0;for(;o&&s++<200;){let a=await(await j(e,o,{headers:i})).json();for(let e of a.values){let t={id:String(e.id),body:e.content?.raw??``};if(r.push(t),n(t))return r}o=A(a.next,t)}return r},async post(t){await j(e,a,{method:`POST`,headers:i,body:JSON.stringify({content:{raw:t}})})},async edit(t,n){await j(e,`${a}/${t}`,{method:`PUT`,headers:i,body:JSON.stringify({content:{raw:n}})})},async attach(){return null},picturesLink(){let t=e.BITBUCKET_WORKSPACE;return e.BITBUCKET_BUILD_NUMBER&&t?`https://bitbucket.org/${n}/pipelines/results/${e.BITBUCKET_BUILD_NUMBER}`:void 0}}}function z(e){let t=M(e,[`SYSTEM_COLLECTIONURI`],`noAzureCollection`).replace(/\/$/,``),n=encodeURIComponent(M(e,[`SYSTEM_TEAMPROJECT`],`noAzureProject`)),r=M(e,[`BUILD_REPOSITORY_ID`],`noAzureRepository`),i=M(e,[`SYSTEM_PULLREQUEST_PULLREQUESTID`],`noAzurePullRequest`),a={Authorization:`Bearer ${M(e,[`PENSTOCK_TOKEN`,`SYSTEM_ACCESSTOKEN`],`noAzureToken`)}`},o=`${t}/${n}/_apis/git/repositories/${r}/pullRequests/${i}`,s=async(t,n,r)=>await(await j(e,n,{method:t,headers:{...a,"Content-Type":`application/json`},body:r?JSON.stringify(r):void 0})).json();return{name:`azure`,async ask(){let t=M(e,[`SYSTEM_PULLREQUEST_TARGETBRANCH`],`noAzureBranch`).replace(/^refs\/heads\//,``);return{number:i,base:`origin/${t}`,command:e.PENSTOCK_COMMAND}},async comments(e){let t=await s(`GET`,`${o}/threads?api-version=7.1`),n=[];for(let r of t.value){if(!r.comments[0])continue;let t={id:`${r.id}/${r.comments[0].id}`,body:r.comments[0].content??``};if(n.push(t),e(t))return n}return n},async post(e){await s(`POST`,`${o}/threads?api-version=7.1`,{comments:[{parentCommentId:0,content:e,commentType:1}],status:1})},async edit(e,t){let[n,r]=e.split(`/`);await s(`PATCH`,`${o}/threads/${n}/comments/${r}?api-version=7.1`,{content:t})},async attach(t){return(await(await j(e,`${o}/attachments/${encodeURIComponent(g.basename(t))}?api-version=7.1-preview.1`,{method:`POST`,headers:{...a,"Content-Type":`application/octet-stream`},body:b(t)})).json()).url||null},picturesLink(){return e.BUILD_BUILDID?`${t}/${n}/_build/results?buildId=${e.BUILD_BUILDID}&view=artifacts`:void 0}}}function B(e){return e.GITHUB_ACTIONS||e.GITEA_ACTIONS||e.FORGEJO_ACTIONS?I(e):e.GITLAB_CI?L(e):e.BITBUCKET_BUILD_NUMBER?R(e):e.TF_BUILD?z(e):null}const V=`{{penstock-pictures}}`;function H(t,n){let i=[],a=[];return{pictures:i,notes:a,async add(o,s){let c;try{let t=await h(b(o.after,`utf8`),s);c=t.svg,t.skipped.length>0&&a.push(`**${o.relative}**: ${e(`app.cli.bot.elementsNotDrawn`,{elements:u(t.skipped.length,`app.cli.bot.count.element`),ids:t.skipped.map(e=>`\`${e}\``).join(`, `)})}`)}catch(t){return a.push(e(`app.cli.bot.noPictureBecause`,{file:o.relative,reason:t instanceof Error?t.message:String(t)})),null}i.push({title:o.relative,svg:c});let l=g.join(n,`${i.length}-${r(o.relative)}.svg`);return S(l,c),t.attach(l)}}}function U(e,t){return t.length===0?e:`${e.trimEnd()}\n\n${t.map(e=>`> ${e}`).join(`
1
+ import{r as e}from"./chunk-translator-BAjzyPKE.js";import{o as t}from"./chunk-failure-BK7fu4Yo.js";import{t as n}from"./chunk-context-B-5CZFAT.js";import{n as r}from"./chunk-project-BS-4dy5o.js";import{c as i,n as a,o,r as s,s as c,u as l}from"./chunk-git-BOKyPQj7.js";import{r as u}from"./chunk-commands-CMEkVxle.js";import{t as d}from"./chunk-plural-Di3FH8HP.js";import{n as f,t as p}from"./chunk-compose-DCAQQndd.js";import{r as m,t as h}from"./chunk-drawing-C2qewK8L.js";import g from"node:path";import{tmpdir as _}from"node:os";import{existsSync as v,mkdirSync as y,readFileSync as b,rmSync as x,writeFileSync as S}from"node:fs";const C=/(?:^|\s)(?:@penstock(?:\[bot\])?|\/penstock)\s*([^\n]*)/i,w=/^[A-Za-z0-9._\/ -]{1,300}\.bpmn(20\.xml)?$/;function T(e){let t=C.exec(e);if(!t)return null;let[n=``,r]=t[1].trim().split(/\s+/);switch(n.toLowerCase()){case``:case`report`:return{kind:`report`};case`check`:case`problems`:return{kind:`check`};case`diff`:case`against`:return r&&l(r)?{kind:`diff`,against:r}:{kind:`diff`};case`image`:case`picture`:case`screenshot`:return r&&w.test(r)&&!r.includes(`..`)?{kind:`image`,path:r}:{kind:`image`};default:return{kind:`help`}}}function E(){return[e(`app.cli.bot.help.intro`),``,e(`app.cli.bot.help.report`),e(`app.cli.bot.help.check`),e(`app.cli.bot.help.diff`),e(`app.cli.bot.help.image`)].join(`
2
+ `)}const D=`<!-- penstock -->`,O=/* @__PURE__ */ new Set([`OWNER`,`MEMBER`,`COLLABORATOR`]);function k(e){let t=Number(e.PENSTOCK_HTTP_TIMEOUT_MS);return Number.isFinite(t)&&t>0?t:3e4}function A(e,t){if(e)try{return new URL(e).origin===new URL(t).origin?e:void 0}catch{return}}async function j(e,t,n){let r=await fetch(t,{...n,signal:AbortSignal.timeout(k(e))});if(!r.ok)throw Error(`${n.method??`GET`} ${new URL(t).pathname}: ${r.status} ${(await r.text()).slice(0,200)}`);return r}function M(t,n,r){for(let e of n){let n=t[e];if(n)return n}throw Error(e(`app.cli.bot.${r}`,{names:n.join(` or `)}))}function N(e){return(e??``).includes(D)}function P(e){return new Blob([b(e)],{type:`image/svg+xml`})}function F(e){return/<([^>]+)>;\s*rel="next"/.exec(e.headers.get(`link`)??``)?.[1]}function I(t){let n=!!(t.GITEA_ACTIONS||t.FORGEJO_ACTIONS||t.GITHUB_SERVER_URL&&!/github\.com|ghe\.com/.test(t.GITHUB_SERVER_URL)&&t.GITHUB_API_URL?.includes(`/api/v1`)),r=t.GITHUB_API_URL??(n?`${t.GITHUB_SERVER_URL}/api/v1`:`https://api.github.com`),i=M(t,[`GITHUB_REPOSITORY`],`noRepository`),a=M(t,[`PENSTOCK_TOKEN`,`GITHUB_TOKEN`,`GITEA_TOKEN`],`noToken`),o={Authorization:n?`token ${a}`:`Bearer ${a}`,Accept:`application/json`},s=JSON.parse(b(M(t,[`GITHUB_EVENT_PATH`],`noEventPath`),`utf8`)),c=n?50:100,l=``,u=async(e,n,a)=>{let s=await j(t,`${r}/repos/${i}${n}`,{method:e,headers:{...o,...a?{"Content-Type":`application/json`}:{}},body:a?JSON.stringify(a):void 0});return s.status===204?void 0:await s.json()},d=e=>({head:e?.head?.repo?.full_name??``,base:e?.base?.repo?.full_name??``}),f=t=>e(`app.cli.bot.fromAnotherFork`,{head:t.head?e(`app.cli.bot.theFork`,{head:t.head}):e(`app.cli.bot.aForkNoLongerExists`),base:t.base});return{name:n?`gitea`:`github`,async ask(){if(t.GITHUB_EVENT_NAME===`issue_comment`){if(s.action!==`created`||!s.issue?.pull_request||s.comment?.user?.type===`Bot`||N(s.comment?.body))return null;let e=s.comment?.author_association;if(typeof e==`string`?!O.has(e):!n)return null;l=String(s.issue.number);let t=await u(`GET`,`/pulls/${l}`),r=d(t),i={number:l,base:t.base.sha,head:`refs/pull/${l}/head`,command:s.comment.body};return r.head===r.base?i:{...i,refuse:f(r)}}let e=s.pull_request;if(!e)return null;l=String(e.number);let r=d(e),i={number:l,base:e.base.sha,head:`refs/pull/${l}/head`,command:t.PENSTOCK_COMMAND};return r.head===r.base?i:{...i,refuse:f(r)}},async comments(e){let a=[],s=1,u=`${r}/repos/${i}/issues/${l}/comments?per_page=100${n?`&limit=${c}`:``}&page=${s}`;for(;u&&s<=200;){let d=await j(t,u,{headers:o}),f=await d.json();for(let t of f){let n={id:String(t.id),body:t.body??``};if(a.push(n),e(n))return a}let p=A(F(d),r);p?(s+=1,u=p):(s+=1,u=f.length<c?void 0:`${r}/repos/${i}/issues/${l}/comments?per_page=100${n?`&limit=${c}`:``}&page=${s}`)}return a},async post(e){await u(`POST`,`/issues/${l}/comments`,{body:e})},async edit(e,t){await u(`PATCH`,`/issues/comments/${e}`,{body:t})},async attach(e){if(!n)return null;let a=new FormData;return a.append(`attachment`,P(e),g.basename(e)),(await(await j(t,`${r}/repos/${i}/issues/${l}/assets?name=${encodeURIComponent(g.basename(e))}`,{method:`POST`,headers:o,body:a})).json()).browser_download_url||null},picturesLink(){if(t.GITHUB_RUN_ID)return`${t.GITHUB_SERVER_URL??`https://github.com`}/${i}/actions/runs/${t.GITHUB_RUN_ID}`}}}function L(e){let t=M(e,[`CI_API_V4_URL`],`noGitLabApi`),n={"PRIVATE-TOKEN":M(e,[`PENSTOCK_TOKEN`,`GITLAB_TOKEN`],`noGitLabToken`)},r=e.TRIGGER_PAYLOAD?JSON.parse(b(e.TRIGGER_PAYLOAD,`utf8`)):null,i=encodeURIComponent(String(r?.project?.id??M(e,[`CI_PROJECT_ID`],`noGitLabProject`))),a=``,o=async(r,a,o)=>await(await j(e,`${t}/projects/${i}${a}`,{method:r,headers:{...n,...o?{"Content-Type":`application/json`}:{}},body:o?JSON.stringify(o):void 0})).json();return{name:`gitlab`,async ask(){if(r){if(r.object_kind!==`note`||r.object_attributes?.noteable_type!==`MergeRequest`||N(r.object_attributes.note)||r.user?.bot)return null;let e=r.merge_request;return a=String(e.iid),{number:a,base:`origin/${e.target_branch}`,head:`refs/merge-requests/${a}/head`,command:r.object_attributes.note}}return e.CI_MERGE_REQUEST_IID?(a=e.CI_MERGE_REQUEST_IID,{number:a,base:e.CI_MERGE_REQUEST_DIFF_BASE_SHA??`origin/${e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME}`,command:e.PENSTOCK_COMMAND}):null},async comments(r){let o=[],s=1;for(;s<=200;){let c=await j(e,`${t}/projects/${i}/merge_requests/${a}/notes?per_page=100&page=${s}`,{headers:n}),l=await c.json();for(let e of l){let t={id:String(e.id),body:e.body??``};if(o.push(t),r(t))return o}if(!c.headers.get(`x-next-page`)&&l.length<100)return o;s+=1}return o},async post(e){await o(`POST`,`/merge_requests/${a}/notes`,{body:e})},async edit(e,t){await o(`PUT`,`/merge_requests/${a}/notes/${e}`,{body:t})},async attach(r){let a=new FormData;return a.append(`file`,P(r),g.basename(r)),(await(await j(e,`${t}/projects/${i}/uploads`,{method:`POST`,headers:n,body:a})).json()).url||null},picturesLink(){return e.CI_JOB_URL?`${e.CI_JOB_URL}/artifacts/browse`:void 0}}}function R(e){let t=e.BITBUCKET_API_URL??`https://api.bitbucket.org/2.0`,n=M(e,[`BITBUCKET_REPO_FULL_NAME`],`noBitbucketRepo`),r=M(e,[`BITBUCKET_PR_ID`],`noBitbucketPr`),i={Authorization:`Bearer ${M(e,[`PENSTOCK_TOKEN`,`BITBUCKET_TOKEN`],`noBitbucketToken`)}`,"Content-Type":`application/json`},a=`${t}/repositories/${n}/pullrequests/${r}/comments`;return{name:`bitbucket`,async ask(){return{number:r,base:`origin/${M(e,[`BITBUCKET_PR_DESTINATION_BRANCH`],`noBitbucketBranch`)}`,command:e.PENSTOCK_COMMAND}},async comments(n){let r=[],o=`${a}?pagelen=100`,s=0;for(;o&&s++<200;){let a=await(await j(e,o,{headers:i})).json();for(let e of a.values){let t={id:String(e.id),body:e.content?.raw??``};if(r.push(t),n(t))return r}o=A(a.next,t)}return r},async post(t){await j(e,a,{method:`POST`,headers:i,body:JSON.stringify({content:{raw:t}})})},async edit(t,n){await j(e,`${a}/${t}`,{method:`PUT`,headers:i,body:JSON.stringify({content:{raw:n}})})},async attach(){return null},picturesLink(){let t=e.BITBUCKET_WORKSPACE;return e.BITBUCKET_BUILD_NUMBER&&t?`https://bitbucket.org/${n}/pipelines/results/${e.BITBUCKET_BUILD_NUMBER}`:void 0}}}function z(e){let t=M(e,[`SYSTEM_COLLECTIONURI`],`noAzureCollection`).replace(/\/$/,``),n=encodeURIComponent(M(e,[`SYSTEM_TEAMPROJECT`],`noAzureProject`)),r=M(e,[`BUILD_REPOSITORY_ID`],`noAzureRepository`),i=M(e,[`SYSTEM_PULLREQUEST_PULLREQUESTID`],`noAzurePullRequest`),a={Authorization:`Bearer ${M(e,[`PENSTOCK_TOKEN`,`SYSTEM_ACCESSTOKEN`],`noAzureToken`)}`},o=`${t}/${n}/_apis/git/repositories/${r}/pullRequests/${i}`,s=async(t,n,r)=>await(await j(e,n,{method:t,headers:{...a,"Content-Type":`application/json`},body:r?JSON.stringify(r):void 0})).json();return{name:`azure`,async ask(){let t=M(e,[`SYSTEM_PULLREQUEST_TARGETBRANCH`],`noAzureBranch`).replace(/^refs\/heads\//,``);return{number:i,base:`origin/${t}`,command:e.PENSTOCK_COMMAND}},async comments(e){let t=await s(`GET`,`${o}/threads?api-version=7.1`),n=[];for(let r of t.value){if(!r.comments[0])continue;let t={id:`${r.id}/${r.comments[0].id}`,body:r.comments[0].content??``};if(n.push(t),e(t))return n}return n},async post(e){await s(`POST`,`${o}/threads?api-version=7.1`,{comments:[{parentCommentId:0,content:e,commentType:1}],status:1})},async edit(e,t){let[n,r]=e.split(`/`);await s(`PATCH`,`${o}/threads/${n}/comments/${r}?api-version=7.1`,{content:t})},async attach(t){return(await(await j(e,`${o}/attachments/${encodeURIComponent(g.basename(t))}?api-version=7.1-preview.1`,{method:`POST`,headers:{...a,"Content-Type":`application/octet-stream`},body:b(t)})).json()).url||null},picturesLink(){return e.BUILD_BUILDID?`${t}/${n}/_build/results?buildId=${e.BUILD_BUILDID}&view=artifacts`:void 0}}}function B(e){return e.GITHUB_ACTIONS||e.GITEA_ACTIONS||e.FORGEJO_ACTIONS?I(e):e.GITLAB_CI?L(e):e.BITBUCKET_BUILD_NUMBER?R(e):e.TF_BUILD?z(e):null}const V=`{{penstock-pictures}}`;function H(t,n){let i=[],a=[];return{pictures:i,notes:a,async add(o,s){let c;try{let t=await h(b(o.after,`utf8`),s);c=t.svg,t.skipped.length>0&&a.push(`**${o.relative}**: ${e(`app.cli.bot.elementsNotDrawn`,{elements:d(t.skipped.length,`app.cli.bot.count.element`),ids:t.skipped.map(e=>`\`${e}\``).join(`, `)})}`)}catch(t){return a.push(e(`app.cli.bot.noPictureBecause`,{file:o.relative,reason:t instanceof Error?t.message:String(t)})),null}i.push({title:o.relative,svg:c});let l=g.join(n,`${i.length}-${r(o.relative)}.svg`);return S(l,c),t.attach(l)}}}function U(e,t){return t.length===0?e:`${e.trimEnd()}\n\n${t.map(e=>`> ${e}`).join(`
3
3
  >
4
4
  `)}\n`}const W=/\[([^\]]*)\]\(\{\{penstock-pictures\}\}\)/g;function G(t,n){return n?t.replace(W,`[$1](${n})`):t.includes(`](${V})`)?`${t.split(`
5
5
  `).filter(e=>!e.includes(`](${V})`)).join(`
6
6
  `).trimEnd()}\n\n${e(`app.cli.bot.picturesInArtifacts`)}`:t}function K(t){return`${t.split(`
7
7
  `).filter(e=>!e.includes(`](${V})`)).join(`
8
- `).trimEnd()}\n\n${e(`app.cli.report.noPictures`)}\n`}async function q(e,t,n,r){let{changed:i,removed:a}=s(e,t),o=H(n,r),c=await f({changed:i.slice(0,40),removed:a,picture:o.add,picturesLink:V});return{body:U(o.pictures.length>0?c.markdown:K(c.markdown),o.notes),pictures:o.pictures}}async function J(t,n,r,a,o){switch(n.kind){case`help`:return{body:E(),upsert:!1,pictures:[]};case`report`:return{...await q(t,r,a,o),upsert:!0};case`diff`:{if(!n.against)return{body:e(`app.cli.bot.sayWhatToCompareWith`),upsert:!1,pictures:[]};let r=i(t,n.against);if(!r)return{body:e(`app.cli.bot.couldNotFindRef`,{ref:n.against}),upsert:!1,pictures:[]};let s=await q(t,r,a,o);return{body:s.body.replace(p,``).replace(e(`app.cli.report.heading`),e(`app.cli.bot.diagramsChangedSince`,{ref:n.against})),upsert:!1,pictures:s.pictures}}case`check`:{let{changed:n}=s(t,r);if(n.length===0)return{body:e(`app.cli.bot.noDiagramChangedHere`),upsert:!1,pictures:[]};let i=(await d(n.map(e=>e.after),{format:`json`,baseline:!0,updateBaseline:!1})).reported;return i.length===0?{body:e(`app.cli.bot.cleanAgainstTheBaseline`),upsert:!1,pictures:[]}:{body:i.map(e=>`- **${g.relative(t,e.file)}** \`${e.rule}\` ${e.message}`).join(`
8
+ `).trimEnd()}\n\n${e(`app.cli.report.noPictures`)}\n`}async function q(e,t,n,r){let{changed:i,removed:a}=s(e,t),o=H(n,r),c=await f({changed:i.slice(0,40),removed:a,picture:o.add,picturesLink:V});return{body:U(o.pictures.length>0?c.markdown:K(c.markdown),o.notes),pictures:o.pictures}}async function J(t,n,r,a,o){switch(n.kind){case`help`:return{body:E(),upsert:!1,pictures:[]};case`report`:return{...await q(t,r,a,o),upsert:!0};case`diff`:{if(!n.against)return{body:e(`app.cli.bot.sayWhatToCompareWith`),upsert:!1,pictures:[]};let r=i(t,n.against);if(!r)return{body:e(`app.cli.bot.couldNotFindRef`,{ref:n.against}),upsert:!1,pictures:[]};let s=await q(t,r,a,o);return{body:s.body.replace(p,``).replace(e(`app.cli.report.heading`),e(`app.cli.bot.diagramsChangedSince`,{ref:n.against})),upsert:!1,pictures:s.pictures}}case`check`:{let{changed:n}=s(t,r);if(n.length===0)return{body:e(`app.cli.bot.noDiagramChangedHere`),upsert:!1,pictures:[]};let i=(await u(n.map(e=>e.after),{format:`json`,baseline:!0,updateBaseline:!1})).reported;return i.length===0?{body:e(`app.cli.bot.cleanAgainstTheBaseline`),upsert:!1,pictures:[]}:{body:i.map(e=>`- **${g.relative(t,e.file)}** \`${e.rule}\` ${e.message}`).join(`
9
9
  `),upsert:!1,pictures:[]}}case`image`:{let i=n.path?[n.path]:s(t,r).changed.map(e=>e.relative);if(i.length===0)return{body:e(`app.cli.bot.noDiagramToDraw`),upsert:!1,pictures:[]};let c=H(a,o),l=[],u=[];for(let n of i.slice(0,40)){let r=g.join(t,n);if(!v(r)){l.push(e(`app.cli.bot.notInThisChange`,{file:n}));continue}let i=await c.add({relative:n,after:r},{});i?l.push(`**${n}**\n\n![${n}](${i})`):u.push(n)}return u.length>0&&l.push(e(`app.cli.bot.drawnButNotShown`,{files:u.map(e=>`**${e}**`).join(`, `),open:e(`app.cli.bot.openThem`),link:V})),{body:U(l.join(`
10
10
 
11
11
  `),c.notes),upsert:!1,pictures:c.pictures}}}}function Y(e){return g.join(e.PENSTOCK_BOT_DIR??e.RUNNER_TEMP??_(),`penstock-bot`)}const X=e=>e.body.includes(`<!-- penstock -->`)||e.body.includes(`<!-- penstock-report -->`);async function Z(e,t,n){let r=`${D}\n${G(t.body,n)}`;if(t.upsert){let t=(await e.comments(X)).find(X);if(t){await e.edit(t.id,r);return}}await e.post(r)}async function Q(e,n,r=process.env){try{return await $(e,n,r)}catch(e){return{ok:!1,lines:[t(e)]}}}async function $(t,r,s){let{root:l}=n(t);if(!c(l))return{ok:!1,lines:[e(`app.cli.bot.notAGitCheckout`)]};let u;try{u=B(s)}catch(e){return{ok:!1,lines:[e instanceof Error?e.message:String(e)]}}if(!u)return{ok:!1,lines:[e(`app.cli.bot.unknownCi`)]};let d=Y(s);r!==`post`&&x(d,{recursive:!0,force:!0});let f=await u.ask();if(!f)return{ok:!0,lines:[e(`app.cli.bot.nothingToAnswer`)]};if(r===`post`){let t=g.join(d,`answer.json`);return v(t)?(await Z(u,JSON.parse(b(t,`utf8`)),s.PENSTOCK_PICTURES_URL||u.picturesLink()),{ok:!0,lines:[e(`app.cli.bot.answeredOn`,{platform:u.name})]}):{ok:!0,lines:[e(`app.cli.bot.nothingDrawn`)]}}if(f.refuse){let t={body:f.refuse,upsert:!1,pictures:[]};return r===`draw`?(y(d,{recursive:!0}),S(g.join(d,`answer.json`),JSON.stringify(t)),{ok:!0,lines:[e(`app.cli.bot.refusedSaved`)]}):(await Z(u,t,void 0),{ok:!0,lines:[e(`app.cli.bot.answeredOn`,{platform:u.name})]})}let p=f.command===void 0?{kind:`report`}:T(f.command);if(!p)return{ok:!0,lines:[e(`app.cli.bot.notForPenstock`)]};if(f.head&&!o(l,f.head)&&!a(l,f.head))return{ok:!1,lines:[e(`app.cli.bot.couldNotCheckOut`,{ref:f.head})]};let h=i(l,f.base);if(!h)return{ok:!1,lines:[e(`app.cli.bot.baseNotFound`,{base:f.base})]};y(d,{recursive:!0});let _;try{_=await J(l,p,h,u,d)}catch(t){_={body:e(`app.cli.bot.couldNotDoThat`,{reason:t instanceof Error?t.message:String(t)}),upsert:!1,pictures:[]}}let C=[];if(_.pictures.length>0){let t=g.join(d,`penstock-diagrams.svg`);S(t,m(_.pictures)),C.push(e(`app.cli.bot.drew`,{file:t}))}return r===`draw`?(S(g.join(d,`answer.json`),JSON.stringify(_)),{ok:!0,lines:[...C,e(`app.cli.bot.answerSaved`)]}):(await Z(u,_,s.PENSTOCK_PICTURES_URL||u.picturesLink()),{ok:!0,lines:[...C,e(`app.cli.bot.answeredOn`,{platform:u.name})]})}export{Q as botCommand};
@@ -0,0 +1 @@
1
+ import{Ct as e,St as t,b as n,r,sn as i,v as a,vt as o,x as s,xt as c,y as l}from"./chunk-src-CxTpK8wk.js";import{i as u,t as d}from"./chunk-codeIndex-olvCG85q.js";import f from"node:path";const p=/[\\/]/,m=/^[A-Za-z_][\w$]*(\.[A-Za-z_][\w$]*)*$/;function h(e,t){let n=e.split(p).map(e=>encodeURIComponent(e));return`${process.platform===`win32`?`file:///`:`file://`}${n.join(`/`)}#L${Math.max(1,t)}`}function g(e){let t=/#L(\d+)$/.exec(e)?.[1];return t?Number(t):null}function _(e){let[t]=e.split(`#`);return decodeURIComponent(t.replace(/^file:\/\//,``))}function v(e,t){return t&&m.test(t)?t:`${f.basename(e.file)}:${e.line}`}const y=/* @__PURE__ */ new Set([`JOB_TYPE`,`TOPIC`,`CLASS`,`BEAN`,`ERROR`]),b={CLASS:`CLASS`,BEAN:`CLASS`,JOB_TYPE:`METHOD`,TOPIC:`METHOD`};function x(e,n){let r=/* @__PURE__ */ new Set;return[...c(e,n),...t(e,n)].filter(e=>{let t=`${e.file}#${e.offset}`;return!r.has(t)&&(r.add(t),!0)})}function S(e,t){let n=/* @__PURE__ */ new Map;for(let r of t){let t=c(e,r);t.length>0&&n.set(i(r),t)}return n}function C(e,t,n){return x(e,t).flatMap(e=>{let r=n(e);return r?[{handle:r,label:v(e,t.kind===`CLASS`?t.value:void 0),icon:b[t.kind]??`FILE`,implements:t.kind===`VARIABLE`?e.writes===!0:y.has(t.kind),test:o(e.file)}]:[]})}function w(e,t){let i=new Map(e.map(e=>[e.path,s(e)])),a=/* @__PURE__ */ new Map;for(let e of t){let t=n(i.get(e.file)??[],e.file,e.offset);t&&a.set(`${t.path}#${t.offset}`,t)}return{workers:r(e),classes:[...a.values()],camunda7Imports:e.flatMap(e=>{let t=l(e);return t.length>0?[{path:e.path,names:t}]:[]})}}async function T(e,t,n=u()){return w(await n.factsOf(e),t)}async function E(t,n=u()){let r=await n.factsOf(t),i=w(r,[]);return{protocol:1,workers:i.workers,classes:i.classes,camunda7Imports:i.camunda7Imports,types:e(r,i.workers.flatMap(e=>(e.variables??[]).map(e=>e.type)))}}async function D(e,t){let n=await d(t.map(e=>({file:e.path,text:e.text})));return{index:n,facts:await T(t,[...S(n,await a(e)).values()].flat())}}export{h as a,C as i,E as n,g as o,D as r,_ as s,T as t};