pi-webapp 0.1.31-alpha.3 → 0.1.31-alpha.4

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 (128) hide show
  1. package/dist/extension.js +2 -2
  2. package/package.json +2 -2
  3. package/web/dist/.vite/manifest.json +508 -508
  4. package/web/dist/assets/{abnfDiagram-VCTEODGH-X3kQ_bki.js → abnfDiagram-VCTEODGH-DOPlOkUJ.js} +1 -1
  5. package/web/dist/assets/{app-CVHf-uJ3.js → app-gCk-2TDF.js} +96 -96
  6. package/web/dist/assets/app.css +1 -1
  7. package/web/dist/assets/app.js +5 -5
  8. package/web/dist/assets/{ar-SA-G6X2FPQ2-CFIHl-DE.js → ar-SA-G6X2FPQ2-DZfey2lT.js} +1 -1
  9. package/web/dist/assets/{arc-CqxikbVL.js → arc-DG_vwUrU.js} +1 -1
  10. package/web/dist/assets/{architectureDiagram-5GKGNRK7-BRKR_H5s.js → architectureDiagram-5GKGNRK7-ECpwUvbT.js} +1 -1
  11. package/web/dist/assets/{az-AZ-76LH7QW2-Dwj_5ziW.js → az-AZ-76LH7QW2-DWGJksfR.js} +1 -1
  12. package/web/dist/assets/{bg-BG-XCXSNQG7-DdfXFJB4.js → bg-BG-XCXSNQG7-ZxUgqtcs.js} +1 -1
  13. package/web/dist/assets/{blockDiagram-I7D4REHJ-DXA8yQq7.js → blockDiagram-I7D4REHJ-s2II5Siy.js} +1 -1
  14. package/web/dist/assets/{bn-BD-2XOGV67Q-D6IfURuj.js → bn-BD-2XOGV67Q-Db0cVQ4Y.js} +1 -1
  15. package/web/dist/assets/{c4Diagram-7LVT6UL2-B2g2j3eN.js → c4Diagram-7LVT6UL2-B3dXdnJP.js} +1 -1
  16. package/web/dist/assets/{ca-ES-6MX7JW3Y-DiNC7bUh.js → ca-ES-6MX7JW3Y-DnTHsp9g.js} +1 -1
  17. package/web/dist/assets/{channel-CG4qi8v4.js → channel-BNmt9r9T.js} +1 -1
  18. package/web/dist/assets/{chunk-2Q5K7J3B-CYbFRw8K.js → chunk-2Q5K7J3B-4JenjRP2.js} +1 -1
  19. package/web/dist/assets/{chunk-5VM5RSS4-DJxmmGJ3.js → chunk-5VM5RSS4-DcZaSc8t.js} +1 -1
  20. package/web/dist/assets/{chunk-F27PBJKO-D-vf-ZQ4.js → chunk-F27PBJKO-DT--4dNr.js} +1 -1
  21. package/web/dist/assets/{chunk-IMKFNOWR-CSkgpgje.js → chunk-IMKFNOWR-DkcD9Q04.js} +1 -1
  22. package/web/dist/assets/{chunk-JWPE2WC7-z6XMczdp.js → chunk-JWPE2WC7-DcfbcRY9.js} +1 -1
  23. package/web/dist/assets/{chunk-POPQ4Y6H-DS4j2lzG.js → chunk-POPQ4Y6H-BGw17ABw.js} +1 -1
  24. package/web/dist/assets/{chunk-SVP7TREG-CH-KfPCb.js → chunk-SVP7TREG-CdlJhbkL.js} +1 -1
  25. package/web/dist/assets/{chunk-TICWLB2K-CKHn5xE1.js → chunk-TICWLB2K-B30eF_rg.js} +1 -1
  26. package/web/dist/assets/{chunk-XXDRQBXY-JAl79qn9.js → chunk-XXDRQBXY-D8lcfHi6.js} +1 -1
  27. package/web/dist/assets/{classDiagram-ZZMXUADV-BtChHpt5.js → classDiagram-ZZMXUADV-CYExlNpU.js} +1 -1
  28. package/web/dist/assets/{classDiagram-v2-VYDZK3BY-C3hGlJDv.js → classDiagram-v2-VYDZK3BY-BOCqfMKB.js} +1 -1
  29. package/web/dist/assets/{cose-bilkent-JH36ORCC-Ce05FpdV.js → cose-bilkent-JH36ORCC-DeCM8oGs.js} +1 -1
  30. package/web/dist/assets/{cs-CZ-2BRQDIVT-BkpSEg3r.js → cs-CZ-2BRQDIVT-DuMpkIPQ.js} +1 -1
  31. package/web/dist/assets/{cynefinDiagram-5FMLGOSQ-C747O64S.js → cynefinDiagram-5FMLGOSQ-CHHc8NfT.js} +1 -1
  32. package/web/dist/assets/{da-DK-5WZEPLOC-CFm1S_Eq.js → da-DK-5WZEPLOC-D3x0whDi.js} +1 -1
  33. package/web/dist/assets/{dagre-GXQ25YYZ-CnZBiYBQ.js → dagre-GXQ25YYZ-BlnSzJm3.js} +1 -1
  34. package/web/dist/assets/{de-DE-XR44H4JA-B1nJndT-.js → de-DE-XR44H4JA-PvFlf9-o.js} +1 -1
  35. package/web/dist/assets/{diagram-S7CK7UJ4-BdEQEyzV.js → diagram-S7CK7UJ4-C8cpqu4g.js} +1 -1
  36. package/web/dist/assets/{diagram-UQ7AKVKN-CL8cEmVb.js → diagram-UQ7AKVKN-CiE5Y0hF.js} +1 -1
  37. package/web/dist/assets/{diagram-VSXAHHWV-B1-kx23j.js → diagram-VSXAHHWV-wFDYB5SE.js} +1 -1
  38. package/web/dist/assets/{diagram-VX7I27RA-CHiB7-IH.js → diagram-VX7I27RA-BJB4bQJ8.js} +1 -1
  39. package/web/dist/assets/{diagram-Z3DM3KII-DFlJjqyR.js → diagram-Z3DM3KII-DDfhenF6.js} +1 -1
  40. package/web/dist/assets/{ebnfDiagram-PWID7BFC-COwoYH0V.js → ebnfDiagram-PWID7BFC-CKfU0hGL.js} +1 -1
  41. package/web/dist/assets/{el-GR-BZB4AONW-BLXALkcZ.js → el-GR-BZB4AONW-CSxYW7dT.js} +1 -1
  42. package/web/dist/assets/{erDiagram-RLTQ6QDP-VM0w2mHD.js → erDiagram-RLTQ6QDP-DPjb8P7m.js} +1 -1
  43. package/web/dist/assets/{es-ES-U4NZUMDT-DJY0B5NJ.js → es-ES-U4NZUMDT-Bt1KalfH.js} +1 -1
  44. package/web/dist/assets/{eu-ES-A7QVB2H4-Bg-VtwjZ.js → eu-ES-A7QVB2H4-l87AYtlV.js} +1 -1
  45. package/web/dist/assets/{fa-IR-HGAKTJCU-BVCFouug.js → fa-IR-HGAKTJCU-DIaro9Hx.js} +1 -1
  46. package/web/dist/assets/{fi-FI-Z5N7JZ37-DZPxzUbi.js → fi-FI-Z5N7JZ37-COLyTVSp.js} +1 -1
  47. package/web/dist/assets/{flowDiagram-HODETNUW-C7gfDcfT.js → flowDiagram-HODETNUW-CBEJA9iU.js} +1 -1
  48. package/web/dist/assets/{fr-FR-RHASNOE6-Cf0IhtOm.js → fr-FR-RHASNOE6-Dqi638pn.js} +1 -1
  49. package/web/dist/assets/{ganttDiagram-EL5Y4UJY-BSkzgHca.js → ganttDiagram-EL5Y4UJY-vAHRozpM.js} +1 -1
  50. package/web/dist/assets/{gitGraphDiagram-WWUBYQGX-B8-Rf6Dz.js → gitGraphDiagram-WWUBYQGX-DCXKE3o8.js} +1 -1
  51. package/web/dist/assets/{gl-ES-HMX3MZ6V-DcVkzWI6.js → gl-ES-HMX3MZ6V-Dfcw_231.js} +1 -1
  52. package/web/dist/assets/{graphql-CEZNEShP.js → graphql-B_h7z8QF.js} +1 -1
  53. package/web/dist/assets/{he-IL-6SHJWFNN-DVTEl8zJ.js → he-IL-6SHJWFNN-BSAgg49S.js} +1 -1
  54. package/web/dist/assets/{hi-IN-IWLTKZ5I-BDJszbel.js → hi-IN-IWLTKZ5I-BqI-UNou.js} +1 -1
  55. package/web/dist/assets/{http-C4T5ELP6.js → http-D8BvZbjX.js} +1 -1
  56. package/web/dist/assets/{hu-HU-A5ZG7DT2-BMO0bpuc.js → hu-HU-A5ZG7DT2-B16ap7C1.js} +1 -1
  57. package/web/dist/assets/{id-ID-SAP4L64H-DlFX7T4W.js → id-ID-SAP4L64H-BUqRAxnn.js} +1 -1
  58. package/web/dist/assets/{index-5PUoAkpB.js → index-jgQcOxOn.js} +6 -6
  59. package/web/dist/assets/{infoDiagram-27XIBGKW-abA4KIoL.js → infoDiagram-27XIBGKW-vfG1s0OL.js} +1 -1
  60. package/web/dist/assets/{ishikawaDiagram-5VMMS53U-CKyskAKu.js → ishikawaDiagram-5VMMS53U-Bci9k7OW.js} +1 -1
  61. package/web/dist/assets/{it-IT-JPQ66NNP-CCtGQwVD.js → it-IT-JPQ66NNP-BWRN1Ku9.js} +1 -1
  62. package/web/dist/assets/{ja-JP-DBVTYXUO-BX0u8Pgz.js → ja-JP-DBVTYXUO-No6piD4d.js} +1 -1
  63. package/web/dist/assets/{journeyDiagram-3NMN7TZE-C_fna9qu.js → journeyDiagram-3NMN7TZE-DPaDQjfX.js} +1 -1
  64. package/web/dist/assets/{kaa-6HZHGXH3-CHgHbmEY.js → kaa-6HZHGXH3-DdHIcOCS.js} +1 -1
  65. package/web/dist/assets/{kab-KAB-ZGHBKWFO-BtmPCdYR.js → kab-KAB-ZGHBKWFO-2wPJRIz0.js} +1 -1
  66. package/web/dist/assets/{kanban-definition-UXKFOSKX--i3veGJK.js → kanban-definition-UXKFOSKX-COZcNcrM.js} +1 -1
  67. package/web/dist/assets/{kk-KZ-P5N5QNE5-DItQaz8n.js → kk-KZ-P5N5QNE5-BnVddHiG.js} +1 -1
  68. package/web/dist/assets/{km-KH-HSX4SM5Z-Fo1wWvPs.js → km-KH-HSX4SM5Z-CaQh_1Zz.js} +1 -1
  69. package/web/dist/assets/{ko-KR-MTYHY66A-D3pWzmJF.js → ko-KR-MTYHY66A-BiAIKUW_.js} +1 -1
  70. package/web/dist/assets/{ku-TR-6OUDTVRD-CzsdnccO.js → ku-TR-6OUDTVRD-Cmqyx_qg.js} +1 -1
  71. package/web/dist/assets/{layout-Dn3HMPmJ.js → layout-D1ZAr34W.js} +1 -1
  72. package/web/dist/assets/{linear-CNZ-99gu.js → linear-CMBY9Ynj.js} +1 -1
  73. package/web/dist/assets/{lt-LT-XHIRWOB4-sHHbLqlz.js → lt-LT-XHIRWOB4-FPPi26PI.js} +1 -1
  74. package/web/dist/assets/{lv-LV-5QDEKY6T-8Xl0Z9Np.js → lv-LV-5QDEKY6T-CdfhNxb4.js} +1 -1
  75. package/web/dist/assets/{mindmap-definition-YA3MSWOX-9dFDd7uj.js → mindmap-definition-YA3MSWOX-DO_oVGmk.js} +1 -1
  76. package/web/dist/assets/{mr-IN-CRQNXWMA-CCHVNKYJ.js → mr-IN-CRQNXWMA-D5Mv5ubd.js} +1 -1
  77. package/web/dist/assets/{my-MM-5M5IBNSE-NII3XKKv.js → my-MM-5M5IBNSE-CG_XcsDc.js} +1 -1
  78. package/web/dist/assets/{nb-NO-T6EIAALU-DMGQtXQs.js → nb-NO-T6EIAALU-ButcGDIE.js} +1 -1
  79. package/web/dist/assets/{nl-NL-IS3SIHDZ-BYSNzynU.js → nl-NL-IS3SIHDZ-B4RCIW6U.js} +1 -1
  80. package/web/dist/assets/{nn-NO-6E72VCQL-jf9XpNK7.js → nn-NO-6E72VCQL-Xesywhmp.js} +1 -1
  81. package/web/dist/assets/{oc-FR-POXYY2M6-BDAy9R-C.js → oc-FR-POXYY2M6-DScPx0Ux.js} +1 -1
  82. package/web/dist/assets/{pa-IN-N4M65BXN-_ggN0KB8.js → pa-IN-N4M65BXN-VndNSoj5.js} +1 -1
  83. package/web/dist/assets/{pegDiagram-XKGWAZYB-BfVRd5eu.js → pegDiagram-XKGWAZYB-DDMhIEdn.js} +1 -1
  84. package/web/dist/assets/{percentages-BXMCSKIN-OWfqlJSl.js → percentages-BXMCSKIN-VuFdtdZF.js} +7 -7
  85. package/web/dist/assets/{php-Dkn52bt_.js → php-JejPRwzT.js} +1 -1
  86. package/web/dist/assets/{pica-BkUkO1d6.js → pica-GNj3eWcB.js} +1 -1
  87. package/web/dist/assets/{pieDiagram-E7YTZNPT-B2g1xagP.js → pieDiagram-E7YTZNPT-CV4Axk4E.js} +1 -1
  88. package/web/dist/assets/{pl-PL-T2D74RX3-C2s5OGEM.js → pl-PL-T2D74RX3-B2jYVPHk.js} +1 -1
  89. package/web/dist/assets/{plugin-acF2vGGo.js → plugin-B4TCKNbA.js} +1 -1
  90. package/web/dist/assets/{plugin-Djp2as1a.js → plugin-BAyOcS28.js} +3 -3
  91. package/web/dist/assets/{plugin-C4xs8k1N.js → plugin-DtO0gZBn.js} +1 -1
  92. package/web/dist/assets/{plugin-DFBr14yN.js → plugin-Dtwg42bN.js} +1 -1
  93. package/web/dist/assets/{pt-BR-5N22H2LF-Wbn7l4lG.js → pt-BR-5N22H2LF-cpUpSu3B.js} +1 -1
  94. package/web/dist/assets/{pt-PT-UZXXM6DQ-C9Q_dXik.js → pt-PT-UZXXM6DQ-Bm5o1aNS.js} +1 -1
  95. package/web/dist/assets/{quadrantDiagram-AXDQQJYC-JFbMaOqG.js → quadrantDiagram-AXDQQJYC-BrOice72.js} +1 -1
  96. package/web/dist/assets/{railroadDiagram-O6MQD6OU-CmujcIiU.js → railroadDiagram-O6MQD6OU-CkIA7mzY.js} +1 -1
  97. package/web/dist/assets/{requirementDiagram-BXWQKSXE-CBRwgswZ.js → requirementDiagram-BXWQKSXE-BLZfWa3W.js} +1 -1
  98. package/web/dist/assets/{ro-RO-JPDTUUEW-3pD5_Bqe.js → ro-RO-JPDTUUEW-D5ewbr8v.js} +1 -1
  99. package/web/dist/assets/{rst-DMMKpDJP.js → rst-Bz1_glFI.js} +1 -1
  100. package/web/dist/assets/{ru-RU-B4JR7IUQ-CXf8Sx_U.js → ru-RU-B4JR7IUQ-BM4UrPha.js} +1 -1
  101. package/web/dist/assets/{ruby-DwUFBzmn.js → ruby-oizq67Sq.js} +1 -1
  102. package/web/dist/assets/{sankeyDiagram-P5KCCOFB-M21RYZW-.js → sankeyDiagram-P5KCCOFB-yD9hxLJX.js} +1 -1
  103. package/web/dist/assets/{sequenceDiagram-WJ2MYXX4-CQvIqE3-.js → sequenceDiagram-WJ2MYXX4-CVqyJvFC.js} +1 -1
  104. package/web/dist/assets/{si-LK-N5RQ5JYF-BlwMmfuW.js → si-LK-N5RQ5JYF-BnIjQwpQ.js} +1 -1
  105. package/web/dist/assets/{sizeCapture-INFHLROL-BG6ArjCn.js → sizeCapture-INFHLROL-CkvfPyS2.js} +1 -1
  106. package/web/dist/assets/{sk-SK-C5VTKIMK-DA8VxrBw.js → sk-SK-C5VTKIMK-C0h1qdby.js} +1 -1
  107. package/web/dist/assets/{sl-SI-NN7IZMDC-CAn4cPTY.js → sl-SI-NN7IZMDC-DNV45ffS.js} +1 -1
  108. package/web/dist/assets/{stateDiagram-D77RDMKH-2UZf_2Q7.js → stateDiagram-D77RDMKH-Nh0i53vT.js} +1 -1
  109. package/web/dist/assets/{stateDiagram-v2-MP3YSRHH-BGkYVUZh.js → stateDiagram-v2-MP3YSRHH-BM-K9bmc.js} +1 -1
  110. package/web/dist/assets/{subset-shared.chunk-BCdfZgoE.js → subset-shared.chunk-TuA1fSFQ.js} +1 -1
  111. package/web/dist/assets/{subset-worker.chunk-CXxAg8sb.js → subset-worker.chunk-BTM-pM_r.js} +1 -1
  112. package/web/dist/assets/{sv-SE-XGPEYMSR-UWe4ZwUP.js → sv-SE-XGPEYMSR-uosawlJJ.js} +1 -1
  113. package/web/dist/assets/{svelte-BIzLFmMm.js → svelte-BEhn2A1K.js} +1 -1
  114. package/web/dist/assets/{swimlanes-42K2YHIH-CciUqLS3.js → swimlanes-42K2YHIH-CrScVzJe.js} +1 -1
  115. package/web/dist/assets/{swimlanesDiagram-VR7AAH4N-DrmPOeKy.js → swimlanesDiagram-VR7AAH4N-BSX45RRS.js} +1 -1
  116. package/web/dist/assets/{ta-IN-2NMHFXQM-ZPs3WDxT.js → ta-IN-2NMHFXQM-Dt9s5QjW.js} +1 -1
  117. package/web/dist/assets/{th-TH-HPSO5L25-DSFCdsI5.js → th-TH-HPSO5L25-BxufhAju.js} +1 -1
  118. package/web/dist/assets/{timeline-definition-24CTP7MA-ifOJ-ier.js → timeline-definition-24CTP7MA-CJbJt2dR.js} +1 -1
  119. package/web/dist/assets/{tr-TR-DEFEU3FU-CELDAn-f.js → tr-TR-DEFEU3FU-BIQE9Xm7.js} +1 -1
  120. package/web/dist/assets/{uk-UA-QMV73CPH-DDS5-qzi.js → uk-UA-QMV73CPH-DhyX8oOD.js} +1 -1
  121. package/web/dist/assets/{vennDiagram-4TSXK5OY-adg55vFx.js → vennDiagram-4TSXK5OY-Dvn1Sbov.js} +1 -1
  122. package/web/dist/assets/{vi-VN-M7AON7JQ-ClX4h4Xx.js → vi-VN-M7AON7JQ-BCPc5pcG.js} +1 -1
  123. package/web/dist/assets/{vue-Dnkrjsnr.js → vue-C1O1jwon.js} +1 -1
  124. package/web/dist/assets/{wardleyDiagram-VM6X3IG4-xP2uuzcP.js → wardleyDiagram-VM6X3IG4-D6lZMm5T.js} +1 -1
  125. package/web/dist/assets/{xychartDiagram-S5SC5T6Z-DclokNRH.js → xychartDiagram-S5SC5T6Z-h2UKcCAm.js} +1 -1
  126. package/web/dist/assets/{zh-CN-LNUGB5OW-CesNeG-n.js → zh-CN-LNUGB5OW-n8E34oE-.js} +1 -1
  127. package/web/dist/assets/{zh-HK-E62DVLB3-C5w1scEl.js → zh-HK-E62DVLB3-BaW9jv7O.js} +1 -1
  128. package/web/dist/assets/{zh-TW-RAJ6MFWO-DIteDACD.js → zh-TW-RAJ6MFWO-Ba9nSPFU.js} +1 -1
package/dist/extension.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="5f5055fc-1b8e-41ca-b18d-8533ace17ea6",r._sentryDebugIdIdentifier="sentry-dbid-5f5055fc-1b8e-41ca-b18d-8533ace17ea6")}catch{}})();import{delimiter as pl,dirname as ul,join as Dt,resolve as xr}from"node:path";import{realpathSync as ns,watch as fl}from"node:fs";import{fileURLToPath as gl}from"node:url";import{DefaultPackageManager as cs,getAgentDir as Ne,ModelRuntime as ml,SessionManager as ls,SettingsManager as hl,VERSION as vr}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as wl}from"@earendil-works/pi-ai";import{randomBytes as xn,randomUUID as or,timingSafeEqual as La}from"node:crypto";import{readFile as Ga,readdir as Ua}from"node:fs/promises";import{createServer as za}from"node:http";import{join as ar}from"node:path";import{getAgentDir as Va}from"@earendil-works/pi-coding-agent";import{Type as S}from"@earendil-works/pi-ai";var it="@pi-webapp/diagrams",A=class extends Error{status;reason;constructor(e,t=400,i){super(e),this.name="DiagramError",this.status=t,this.reason=i}};function R(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function E(r){throw new A(r)}function j(r){return typeof r=="string"&&/^[\w-]{1,80}$/.test(r)?r:E("\u56FE\u5F62 ID \u65E0\u6548")}function re(r){return typeof r=="string"&&r.length>0&&r.length<=500?r:E("\u6587\u6848\u987B\u4E3A 1\u2013500 \u5B57\u7B26")}function Pr(r){let e={};for(let t of["x","y","width","height"])if(r[t]!==void 0){let i=r[t];(typeof i!="number"||!Number.isFinite(i)||Math.abs(i)>1e5||(t==="width"||t==="height")&&(i<20||i>1e4))&&E("\u8282\u70B9\u5750\u6807\u6216\u5C3A\u5BF8\u65E0\u6548"),e[t]=i}return e}function Le(r){let e={};for(let t of["strokeColor","backgroundColor"])r[t]!==void 0&&((typeof r[t]!="string"||!/^(#[\da-f]{6}|#[\da-f]{3}|transparent)$/i.test(r[t]))&&E("\u7ED8\u56FE\u989C\u8272\u987B\u4E3A\u5341\u516D\u8FDB\u5236\u6216 transparent"),e[t]=r[t]);return r.strokeStyle!==void 0&&(["solid","dashed","dotted"].includes(String(r.strokeStyle))||E("\u7EBF\u578B\u65E0\u6548"),e.strokeStyle=r.strokeStyle),r.fontSize!==void 0&&((typeof r.fontSize!="number"||!Number.isFinite(r.fontSize)||r.fontSize<12||r.fontSize>96)&&E("\u5B57\u53F7\u987B\u4E3A 12\u201396"),e.fontSize=r.fontSize),e}function Ir(r){return(!Array.isArray(r)||r.length>30)&&E("\u6BCF\u6B21\u6700\u591A 30 \u4E2A\u8282\u70B9"),r.map(e=>{R(e)||E("\u8282\u70B9\u65E0\u6548");let t={id:j(e.id),label:re(e.label),...Pr(e),...Le(e)};return e.kind!==void 0&&(["process","decision","terminal","text","group"].includes(String(e.kind))||E("\u8282\u70B9\u7C7B\u578B\u65E0\u6548"),t.kind=e.kind),e.groupId!==void 0&&(t.groupId=j(e.groupId)),t})}function Cr(r){return(!Array.isArray(r)||r.length>60)&&E("\u6BCF\u6B21\u6700\u591A 60 \u6761\u8FDE\u7EBF"),r.map(e=>{R(e)||E("\u8FDE\u7EBF\u65E0\u6548");let t={id:j(e.id),from:j(e.from),to:j(e.to),...Le(e),...e.label===void 0?{}:{label:re(e.label)}};return e.waypoints!==void 0&&((!Array.isArray(e.waypoints)||e.waypoints.length>12||e.waypoints.some(i=>!Array.isArray(i)||i.length!==2||i.some(n=>typeof n!="number"||!Number.isFinite(n)||Math.abs(n)>1e5)))&&E("\u8FDE\u7EBF\u9014\u7ECF\u70B9\u65E0\u6548"),t.waypoints=e.waypoints),t})}function Ae(r){new Set(r).size!==r.length&&E("\u56FE\u5F62 ID \u91CD\u590D")}function nt(r){R(r)||E("\u56FE\u7ED3\u6784\u65E0\u6548");let e={nodes:Ir(r.nodes),edges:Cr(r.edges??[])};e.nodes.length||E("\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u8282\u70B9"),r.layout!==void 0&&(r.layout!=="top-down"&&r.layout!=="left-right"&&E("\u5E03\u5C40\u65E0\u6548"),e.layout=r.layout),Ae([...e.nodes,...e.edges].map(n=>n.id));let t=new Set(e.nodes.filter(n=>n.kind!=="text").map(n=>n.id)),i=new Set(e.nodes.filter(n=>n.kind==="group").map(n=>n.id));for(let n of e.nodes)n.groupId&&(!i.has(n.groupId)||n.groupId===n.id||n.kind==="group")&&E("\u5206\u7EC4\u5F15\u7528\u65E0\u6548");for(let n of e.edges)(!t.has(n.from)||!t.has(n.to))&&E("\u8FDE\u7EBF\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684\u8282\u70B9");return e}function st(r,e){R(r)||E("\u4FEE\u6539\u64CD\u4F5C\u65E0\u6548");let t={addNodes:Ir(r.addNodes??[]),addEdges:Cr(r.addEdges??[]),updateNodes:[],removeIds:[]};(!Array.isArray(r.updateNodes??[])||!Array.isArray(r.removeIds??[]))&&E("\u4FEE\u6539\u64CD\u4F5C\u65E0\u6548"),((r.updateNodes??[]).length>30||(r.removeIds??[]).length>60)&&E("\u4FEE\u6539\u8FC7\u591A"),t.updateNodes=(r.updateNodes??[]).map(l=>(R(l)||E("\u8282\u70B9\u4FEE\u6539\u65E0\u6548"),{id:j(l.id),label:re(l.label)})),t.removeIds=(r.removeIds??[]).map(j);let i=e.elements.filter(l=>!l.isDeleted),n=new Set(i.filter(l=>["rectangle","diamond","ellipse"].includes(l.type)).map(l=>l.id)),s=new Set(i.map(l=>l.id)),o=new Set(e.elements.map(l=>l.id));for(let l of t.removeIds)s.has(l)||E(`\u5F85\u5220\u9664\u5143\u7D20\u4E0D\u5B58\u5728\uFF1A${l}`);for(let l of t.updateNodes)(!n.has(l.id)||t.removeIds.includes(l.id))&&E(`\u5F85\u4FEE\u6539\u8282\u70B9\u4E0D\u5B58\u5728\uFF1A${l.id}`);for(let l of t.addNodes)o.has(l.id)&&E(`\u5143\u7D20 ID \u5DF2\u5B58\u5728\uFF1A${l.id}`),l.kind!=="text"&&n.add(l.id);for(let l of t.addEdges)(o.has(l.id)||!n.has(l.from)||!n.has(l.to)||t.removeIds.includes(l.from)||t.removeIds.includes(l.to))&&E("\u65B0\u589E\u8FDE\u7EBF\u65E0\u6548");Ae([...t.addNodes,...t.addEdges].map(l=>l.id)),Ae(t.updateNodes.map(l=>l.id)),(!Array.isArray(r.updateElements??[])||(r.updateElements??[]).length>60)&&E("\u5143\u7D20\u4FEE\u6539\u8FC7\u591A"),t.updateElements=(r.updateElements??[]).map(l=>{R(l)||E("\u5143\u7D20\u4FEE\u6539\u65E0\u6548");let p=j(l.id),u=i.find(d=>d.id===p);(!u||t.removeIds.includes(p)||t.updateNodes.some(d=>d.id===p))&&E("\u5F85\u4FEE\u6539\u5143\u7D20\u4E0D\u5B58\u5728\u6216\u64CD\u4F5C\u91CD\u590D");let h={id:p,...Pr(l),...Le(l),...l.label===void 0?{}:{label:re(l.label)}};return Object.keys(h).length===1&&E("\u5143\u7D20\u4FEE\u6539\u4E3A\u7A7A"),["rectangle","ellipse","diamond","text"].includes(u.type)||E("\u6B64\u7C7B\u578B\u4E0D\u652F\u6301\u76F4\u63A5\u4FEE\u6539\uFF0C\u8BF7\u4FEE\u6539\u5176\u7AEF\u70B9\u6216\u91CD\u5EFA\u8FDE\u7EBF"),u.containerId&&E("\u8BF7\u4FEE\u6539\u6587\u672C\u6240\u5C5E\u7684\u56FE\u5F62\uFF0C\u4FDD\u6301\u7ED1\u5B9A\u4E00\u81F4"),h}),Ae(t.updateElements.map(l=>l.id));let c=new Set([...i.filter(l=>l.customData?.diagramKind==="group").map(l=>l.id),...t.addNodes.filter(l=>l.kind==="group").map(l=>l.id)]);for(let l of t.addNodes)l.groupId&&(!c.has(l.groupId)||t.removeIds.includes(l.groupId)||l.kind==="group")&&E("\u5206\u7EC4\u5F15\u7528\u65E0\u6548");return!t.updateElements.length&&!t.addNodes.length&&!t.addEdges.length&&!t.updateNodes.length&&!t.removeIds.length&&E("\u4FEE\u6539\u4E3A\u7A7A"),t}function ot(r){if(typeof r=="string"){new TextEncoder().encode(r).length>524288&&E("\u56FE\u7A3F\u8D85\u8FC7 512 KiB");try{r=JSON.parse(r)}catch{E("elements \u987B\u4E3A\u6709\u6548 JSON \u6570\u7EC4\u5B57\u7B26\u4E32")}}(!Array.isArray(r)||!r.length||r.length>150)&&E("\u6BCF\u6B21\u9700\u8981 1\u2013150 \u4E2A\u7ED8\u56FE\u5143\u7D20"),new TextEncoder().encode(JSON.stringify(r)).length>524288&&E("\u56FE\u7A3F\u8D85\u8FC7 512 KiB");let e=new Set(["type","id","x","y","width","height","text","fontSize","fontFamily","strokeColor","backgroundColor","strokeWidth","strokeStyle","fillStyle","roughness","opacity","angle","roundness","points","start","end","startArrowhead","endArrowhead","label","groupIds","textAlign","verticalAlign"]),t=r.map(n=>{(!R(n)||Object.keys(n).some(o=>!e.has(o)))&&E("\u7ED8\u56FE\u5143\u7D20\u5305\u542B\u4E0D\u652F\u6301\u5B57\u6BB5"),["rectangle","ellipse","diamond","text","line","arrow"].includes(String(n.type))||E("\u7ED8\u56FE\u7C7B\u578B\u4E0D\u652F\u6301");let s={...n,id:j(n.id)};for(let o of["x","y","width","height","fontSize","strokeWidth","roughness","opacity","angle"]){let c=n[o];c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||Math.abs(c)>1e5)&&E("\u7ED8\u56FE\u6570\u503C\u65E0\u6548")}(typeof n.x!="number"||typeof n.y!="number")&&E("\u7ED8\u56FE\u5750\u6807\u7F3A\u5931"),["rectangle","ellipse","diamond"].includes(String(n.type))&&["width","height"].some(o=>typeof n[o]!="number"||n[o]<20||n[o]>1e4)&&E("\u7ED8\u56FE\u5C3A\u5BF8\u65E0\u6548"),n.fontSize!==void 0&&(n.fontSize<12||n.fontSize>96)&&E("\u5B57\u53F7\u987B\u4E3A 12\u201396"),n.fontFamily!==void 0&&n.fontFamily!==5&&E("\u7ED8\u56FE\u9ED8\u8BA4\u4F7F\u7528\u672C\u5730 Excalifont"),Le(n),n.type==="text"?re(n.text):n.text!==void 0&&E("\u5F62\u72B6\u6587\u5B57\u8BF7\u653E\u5165 label");for(let[o,c]of[["roughness",3],["opacity",100],["strokeWidth",16]])n[o]!==void 0&&(n[o]<0||n[o]>c)&&E("\u7ED8\u56FE\u6837\u5F0F\u6570\u503C\u65E0\u6548");for(let o of["width","height"])n[o]!==void 0&&(n[o]<0||n[o]>1e4)&&E("\u7ED8\u56FE\u5C3A\u5BF8\u65E0\u6548");n.label!==void 0&&((!R(n.label)||Object.keys(n.label).some(o=>!["text","fontSize","fontFamily","textAlign","verticalAlign"].includes(o)))&&E("\u7ED8\u56FE\u6807\u7B7E\u65E0\u6548"),re(n.label.text),Le(n.label),n.label.fontFamily!==void 0&&n.label.fontFamily!==5&&E("\u7ED8\u56FE\u6807\u7B7E\u5B57\u4F53\u65E0\u6548"));for(let o of[n,n.label].filter(R))o.textAlign!==void 0&&!["left","center","right"].includes(String(o.textAlign))&&E("\u6587\u5B57\u5BF9\u9F50\u65E0\u6548"),o.verticalAlign!==void 0&&!["top","middle","bottom"].includes(String(o.verticalAlign))&&E("\u6587\u5B57\u5BF9\u9F50\u65E0\u6548");n.fillStyle!==void 0&&!["solid","hachure","cross-hatch","zigzag"].includes(String(n.fillStyle))&&E("\u586B\u5145\u6837\u5F0F\u65E0\u6548"),n.roundness!==void 0&&(!R(n.roundness)||Object.keys(n.roundness).some(o=>o!=="type")||![1,2,3].includes(n.roundness.type))&&E("\u5706\u89D2\u65E0\u6548");for(let o of["startArrowhead","endArrowhead"])n[o]!==void 0&&n[o]!==null&&!["arrow","bar","dot","triangle"].includes(String(n[o]))&&E("\u7BAD\u5934\u6837\u5F0F\u65E0\u6548");for(let o of["start","end"])if(n[o]!==void 0){let c=n[o];(!R(c)||Object.keys(c).some(l=>l!=="id"))&&E("\u7AEF\u70B9\u7ED1\u5B9A\u65E0\u6548"),j(c.id)}return n.groupIds!==void 0&&(!Array.isArray(n.groupIds)||n.groupIds.length>10||n.groupIds.some(o=>typeof o!="string"||o.length>100||!/^[\p{L}\p{N}_-]{1,100}$/u.test(o)))&&E("\u5143\u7D20\u5206\u7EC4\u65E0\u6548\uFF1AgroupIds \u987B\u4E3A\u6700\u591A 10 \u4E2A\u975E\u7A7A\u6587\u5B57/\u6570\u5B57/\u4E0B\u5212\u7EBF/\u8FDE\u5B57\u7B26 ID\uFF0C\u6BCF\u4E2A\u4E0D\u8D85\u8FC7 100 \u5B57\u7B26"),["arrow","line"].includes(String(n.type))&&(!Array.isArray(n.points)||n.points.length<2||n.points.length>100||n.points.some(o=>!Array.isArray(o)||o.length!==2||o.some(c=>typeof c!="number"||!Number.isFinite(c)||Math.abs(c)>1e5)))&&E("\u8DEF\u5F84\u5750\u6807\u65E0\u6548"),structuredClone(s)});Ae(t.map(n=>n.id));let i=new Set(t.filter(n=>["rectangle","ellipse","diamond"].includes(String(n.type))).map(n=>n.id));for(let n of t)for(let s of["start","end"])R(n[s])&&!i.has(n[s].id)&&E("\u8FDE\u7EBF\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684\u5F62\u72B6");return t}function _r(){return{type:"excalidraw",version:2,source:"pi-webapp",elements:[],appState:{viewBackgroundColor:"#ffffff"},files:{}}}function ce(r){(!R(r)||r.type!=="excalidraw"||r.version!==2||!Array.isArray(r.elements)||r.elements.length>400)&&E("\u65E0\u6548\u6216\u8FC7\u5927\u7684 Excalidraw \u573A\u666F"),new TextEncoder().encode(JSON.stringify(r)).length>524288&&E("\u56FE\u7A3F\u8D85\u8FC7 512 KiB"),r.files!==void 0&&(!R(r.files)||Object.keys(r.files).length)&&E("\u9996\u671F\u4E0D\u652F\u6301\u5D4C\u5165\u56FE\u7247\u6216\u9644\u4EF6");let e=r.elements,t=[];for(let s of e){(!R(s)||typeof s.id!="string"||!s.id||s.id.length>100||!["rectangle","ellipse","diamond","text","line","arrow","freedraw","frame"].includes(s.type))&&E("\u573A\u666F\u5305\u542B\u4E0D\u652F\u6301\u7684\u5143\u7D20"),t.push(s.id);for(let o of["x","y","width","height","angle","fontSize","strokeWidth"])s[o]!==void 0&&(typeof s[o]!="number"||!Number.isFinite(s[o])||Math.abs(s[o])>1e5)&&E("\u56FE\u5F62\u6570\u503C\u65E0\u6548");for(let o of["x","y","width","height"])typeof s[o]!="number"&&E("\u56FE\u5F62\u5C3A\u5BF8\u7F3A\u5931");(s.link||s.fileId||s.type==="embeddable"||s.type==="iframe")&&E("\u9996\u671F\u4E0D\u652F\u6301\u5916\u94FE\u6216\u5D4C\u5165\u8D44\u6E90"),s.text!==void 0&&(typeof s.text!="string"||s.text.length>2e3)&&E("\u56FE\u5F62\u6587\u6848\u8FC7\u957F"),(s.width<0||s.height<0||typeof s.fontSize=="number"&&(s.fontSize<1||s.fontSize>200))&&E("\u56FE\u5F62\u5C3A\u5BF8\u6216\u5B57\u53F7\u65E0\u6548"),s.groupIds!==void 0&&(!Array.isArray(s.groupIds)||s.groupIds.some(o=>typeof o!="string"||o.length>100))&&E("\u5143\u7D20\u5206\u7EC4\u65E0\u6548"),s.boundElements!=null&&(!Array.isArray(s.boundElements)||s.boundElements.some(o=>!R(o)||typeof o.id!="string"||!["arrow","text"].includes(String(o.type))))&&E("\u5143\u7D20\u7ED1\u5B9A\u65E0\u6548");for(let o of["startBinding","endBinding"])if(s[o]!=null){let c=s[o];(!R(c)||typeof c.elementId!="string"||["focus","gap"].some(l=>typeof c[l]!="number"||!Number.isFinite(c[l])))&&E("\u8FDE\u7EBF\u7ED1\u5B9A\u65E0\u6548")}s.containerId!=null&&typeof s.containerId!="string"&&E("\u6587\u672C\u7ED1\u5B9A\u65E0\u6548"),s.frameId!=null&&(typeof s.frameId!="string"||!e.some(o=>o.id===s.frameId&&o.type==="frame"))&&E("\u753B\u6846\u5F15\u7528\u65E0\u6548"),s.type==="frame"&&s.name!=null&&(typeof s.name!="string"||s.name.length>2e3)&&E("\u753B\u6846\u540D\u79F0\u65E0\u6548"),s.fontFamily!==void 0&&(typeof s.fontFamily!="number"||!Number.isInteger(s.fontFamily)||s.fontFamily<1||s.fontFamily>1e3)&&E("\u5B57\u4F53\u65E0\u6548");for(let o of["strokeColor","backgroundColor","fillStyle","strokeStyle"])s[o]!==void 0&&(typeof s[o]!="string"||s[o].length>100)&&E("\u56FE\u5F62\u6837\u5F0F\u65E0\u6548");s.points!==void 0&&(!Array.isArray(s.points)||s.points.length>2e3||s.points.some(o=>!Array.isArray(o)||o.length!==2||o.some(c=>typeof c!="number"||!Number.isFinite(c)||Math.abs(c)>1e5)))&&E("\u8DEF\u5F84\u5750\u6807\u65E0\u6548")}Ae(t);let i=R(r.appState)?r.appState:{},n=typeof i.viewBackgroundColor=="string"&&/^#[\da-f]{3,8}$/i.test(i.viewBackgroundColor)?i.viewBackgroundColor:"#ffffff";return{type:"excalidraw",version:2,source:"pi-webapp",elements:structuredClone(e),appState:{viewBackgroundColor:n},files:{}}}var ie=S.String({pattern:"^[\\w-]{1,80}$"}),Te=S.String({minLength:1,maxLength:500}),Nr=S.String({pattern:"^(#[a-fA-F0-9]{6}|#[a-fA-F0-9]{3}|transparent)$"}),Ft={strokeColor:S.Optional(Nr),backgroundColor:S.Optional(Nr),strokeStyle:S.Optional(S.Union([S.Literal("solid"),S.Literal("dashed"),S.Literal("dotted")])),fontSize:S.Optional(S.Number({minimum:12,maximum:96}))},Ar={x:S.Optional(S.Number({minimum:-1e5,maximum:1e5})),y:S.Optional(S.Number({minimum:-1e5,maximum:1e5})),width:S.Optional(S.Number({minimum:20,maximum:1e4})),height:S.Optional(S.Number({minimum:20,maximum:1e4}))},Tr=S.Object({id:ie,label:Te,kind:S.Optional(S.Union(["process","decision","terminal","text","group"].map(r=>S.Literal(r)))),...Ar,...Ft,groupId:S.Optional(ie)}),Rr=S.Object({id:ie,from:ie,to:ie,label:S.Optional(Te),...Ft,waypoints:S.Optional(S.Array(S.Tuple([S.Number({minimum:-1e5,maximum:1e5}),S.Number({minimum:-1e5,maximum:1e5})]),{maxItems:12}))}),ms=S.Object({nodes:S.Array(Tr,{minItems:1,maxItems:30}),edges:S.Array(Rr,{maxItems:60}),layout:S.Optional(S.Union([S.Literal("top-down"),S.Literal("left-right")]))}),hs=S.Object({addNodes:S.Optional(S.Array(Tr,{maxItems:30})),addEdges:S.Optional(S.Array(Rr,{maxItems:60})),updateNodes:S.Optional(S.Array(S.Object({id:ie,label:Te}),{maxItems:30})),updateElements:S.Optional(S.Array(S.Object({id:ie,label:S.Optional(Te),...Ar,...Ft}),{maxItems:60})),removeIds:S.Optional(S.Array(ie,{maxItems:60}))});function Dr(r){return[{name:"excalidraw_read_me",action:"reference",description:"Read the local Excalidraw element format and drawing examples before using excalidraw_create_view. Draw from the main conversation; never ask users to open a diagram app, fill a form, or accept a newly created diagram. No external service or account.",parameters:S.Object({})},{name:"excalidraw_create_view",action:"view",description:"Draw an editable Excalidraw view directly in the conversation. First read excalidraw_read_me. Put scene JSON only in tool arguments, never repeat it as assistant text/code blocks: the tool card already provides a collapsed parameter inspector. elements is a JSON array string of compact native shapes, text, lines and arrows with explicit positions, sizes, styles and bound labels. New views become editable automatically. To edit the active drawing, first call diagram_read (omit id for active view); prefer diagram_patch for targeted changes preserving manual edits. For a full replacement provide id and exact baseRevision; existing drawings require review in chat. Does not upload, write workspace files or export PNG.",parameters:S.Object({title:S.Optional(Te),elements:S.String({maxLength:512*1024}),id:S.Optional(ie),baseRevision:S.Optional(S.Integer({minimum:0}))})},{name:"diagram_reference",action:"reference",description:"Read the local Excalidraw composition format, layout guidance and a layered architecture example. Use before drawing a rich diagram. Does not access files or an external service.",parameters:S.Object({})},{name:"diagram_create",action:"create",description:"Create an editable Excalidraw diagram displayed directly in chat. Put graph JSON only in tool arguments, not in assistant text/code blocks; the card has a parameter inspector. Use for natural-language drawing requests; users need not name tools. For architecture/knowledge diagrams read diagram_reference first: nodes support text/group kinds, explicit coordinates, width/height, colors and fontSize; edges support dashed strokes and absolute waypoints. Compose layers and annotations, not just identical boxes. Unique stable ASCII IDs; Chinese labels supported. New drawings are automatically materialized in the conversation and can be edited directly; do not ask users to accept a new drawing. Prefer excalidraw_create_view for free-form compositions. This does not save a file or render PNG.",parameters:S.Object({title:Te,graph:ms})},{name:"diagram_read",action:"read",description:"Read the latest synchronized diagram revision and compact native elements by ID. Always read before patching. Bound text uses containerId; shape IDs identify nodes. User manual edits are authoritative. Omit id to read the current active drawing in this session. Only this session's drawings are read. Read after user edits before generating a patch.",parameters:S.Object({id:S.Optional(ie),elementIds:S.Optional(S.Array(ie,{maxItems:100}))})},{name:"diagram_patch",action:"patch",description:"Propose local edits to an existing diagram after diagram_read. Supply its exact baseRevision. addNodes/addEdges, updateNodes (shape ID + label), updateElements (shape or unbound text ID + optional label, x/y, width/height, colors, fontSize, strokeStyle), removeIds (native IDs). Geometry updates reroute incident bound arrows; unrelated native elements retain their positions and text. Do not rearrange everything unless requested. Never claim the proposal was accepted or saved.",parameters:S.Object({id:ie,baseRevision:S.Integer({minimum:0}),patch:hs})}].map(({name:e,action:t,description:i,parameters:n})=>({name:e,label:e,description:i,parameters:n,async execute(s,o,c,l,p){c?.throwIfAborted();let u=await r(it,p.cwd,p.sessionManager.getSessionId(),t,o);return{content:[{type:"text",text:JSON.stringify(u)}],details:u}}}))}var Mr={id:it,kind:"builtin",version:"1.0.0",name:{zh:"\u624B\u7ED8\u56FE",en:"Diagrams"},description:{zh:"Agent \u751F\u6210\u6D41\u7A0B\u4E0E\u67B6\u6784\u56FE\uFF0C\u4F7F\u7528 Excalidraw \u7F16\u8F91\u3001\u672C\u5730\u4FDD\u5B58\u548C\u5BFC\u51FA\u3002",en:"Generate flowcharts with the agent, edit in Excalidraw, save locally and export."}};import{constants as zt}from"node:fs";import{lstat as Cs,mkdir as _s,open as Jt,readdir as Ns,rename as As,unlink as Vt}from"node:fs/promises";import{createHash as Ts,randomUUID as Rs}from"node:crypto";import{join as ve}from"node:path";import{setTimeout as Ds}from"node:timers/promises";import{getAgentDir as Ms}from"@earendil-works/pi-coding-agent";import{randomUUID as ct}from"node:crypto";import{basename as Is}from"node:path";import{constants as Bt}from"node:fs";import{link as ws,lstat as Or,mkdir as ys,open as $t,realpath as Wr,rename as bs,unlink as jt}from"node:fs/promises";import{dirname as ks,isAbsolute as Br,join as jr,relative as Lt,resolve as vs,sep as $r,win32 as Es}from"node:path";import{createHash as xs,randomUUID as Ss}from"node:crypto";var at=r=>xs("sha256").update(r).digest("hex");function Fr(r,e){let t=Lt(r,e);return t!==".."&&!t.startsWith(`..${$r}`)&&!Br(t)}async function Gt(r,e,t=!1){if(typeof e!="string"||e.length>4096||!e.endsWith(".excalidraw")||e.includes("\\")||e.includes("\0")||Br(e)||Es.isAbsolute(e))throw new A("\u8BF7\u4F7F\u7528\u5DE5\u4F5C\u533A\u5185\u7684 .excalidraw \u76F8\u5BF9\u8DEF\u5F84");let i=await Wr(r),n=vs(i,e);if(!Fr(i,n)||n===i)throw new A("\u56FE\u7A3F\u8DEF\u5F84\u8D8A\u754C",403);let s=Lt(i,n).split($r),o=i;for(let l=0;l<s.length;l++){o=jr(o,s[l]);let p;try{p=await Or(o)}catch(u){if(u.code!=="ENOENT")throw u;if(l<s.length-1){if(!t||Lt(i,o)!=="diagrams")throw new A("\u4FDD\u5B58\u76EE\u5F55\u4E0D\u5B58\u5728",404);try{await ys(o,{mode:448})}catch(h){if(h.code!=="EEXIST")throw h}p=await Or(o)}}if(p?.isSymbolicLink())throw new A("\u56FE\u7A3F\u8DEF\u5F84\u4E0D\u80FD\u5305\u542B\u7B26\u53F7\u94FE\u63A5",403);if(p&&(l<s.length-1?!p.isDirectory():!p.isFile()))throw new A("\u56FE\u7A3F\u8DEF\u5F84\u4E0D\u662F\u666E\u901A\u6587\u4EF6")}let c=await Wr(ks(n));if(!Fr(i,c))throw new A("\u56FE\u7A3F\u8DEF\u5F84\u8D8A\u754C",403);return{target:n,parent:c}}async function Ut(r){let e;try{e=await $t(r,Bt.O_RDONLY|Bt.O_NONBLOCK|(Bt.O_NOFOLLOW??0))}catch(t){if(t.code==="ENOENT")return null;throw t}try{let t=await e.stat();if(!t.isFile()||t.size>524288)throw new A("\u4E0D\u662F\u666E\u901A\u6587\u4EF6\u6216\u56FE\u7A3F\u8D85\u8FC7 512 KiB");let i=Buffer.alloc(524289),n=0;for(;n<i.length;){let{bytesRead:s}=await e.read(i,n,i.length-n,n);if(!s)break;n+=s}if(n>524288)throw new A("\u56FE\u7A3F\u8D85\u8FC7 512 KiB");return i.subarray(0,n)}finally{await e.close()}}function Lr(r){if(r instanceof A)throw r;let e=r.code;throw["EACCES","EPERM","ELOOP"].includes(e??"")?new A("\u56FE\u7A3F\u4E0D\u53EF\u8BBF\u95EE\u6216\u5305\u542B\u7B26\u53F7\u94FE\u63A5",403):["ENOENT","ENOTDIR"].includes(e??"")?new A("\u56FE\u7A3F\u76EE\u5F55\u4E0D\u5B58\u5728",404):e==="EEXIST"?new A("\u56FE\u7A3F\u6B63\u5728\u4FDD\u5B58\uFF1B\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF08\u4E0D\u8981\u5220\u9664\u6D3B\u8DC3\u7684\u9501\u6587\u4EF6\uFF09",409):r}async function Gr(r,e){try{let{target:t}=await Gt(r,e),i=await Ut(t);if(!i)throw new A("\u56FE\u7A3F\u4E0D\u5B58\u5728",404);let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new A("\u56FE\u7A3F\u4E0D\u662F\u6709\u6548\u7684 UTF-8 JSON")}return{scene:ce(n),hash:at(i)}}catch(t){return Lr(t)}}async function Ur(r,e,t,i,n=()=>{}){let s=JSON.stringify(ce(t)),o,c,l;try{let{target:p,parent:u}=await Gt(r,e,!0);c=`${p}.lock`,o=await $t(c,"wx",384),await o.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));let h=await Ut(p);if((h?at(h):null)!==i)throw new A("\u6587\u4EF6\u5DF2\u5B58\u5728\u6216\u88AB\u5916\u90E8\u4FEE\u6539\uFF1B\u8BF7\u91CD\u65B0\u6253\u5F00\u6216\u53E6\u5B58\uFF0C\u672A\u8986\u76D6\u539F\u6587\u4EF6",409);l=jr(u,`.diagram-${Ss()}.tmp`);let d=await $t(l,"wx",384);try{await d.writeFile(s),await d.sync()}finally{await d.close()}if((await Gt(r,e)).parent!==u)throw new A("\u4FDD\u5B58\u76EE\u5F55\u53D1\u751F\u53D8\u5316",409);let m=await Ut(p);if((m?at(m):null)!==i)throw new A("\u4FDD\u5B58\u671F\u95F4\u6587\u4EF6\u53D1\u751F\u53D8\u5316\uFF1B\u672A\u8986\u76D6",409);if(n(),i===null){try{await ws(l,p)}catch(y){throw y.code==="EEXIST"?new A("\u76EE\u6807\u6587\u4EF6\u5DF2\u5B58\u5728\uFF1B\u8BF7\u53E6\u5B58",409):y}await jt(l),l=void 0}else await bs(l,p),l=void 0;return at(s)}catch(p){return Lr(p)}finally{l&&await jt(l).catch(()=>{}),o&&(await o.close(),await jt(c).catch(()=>{}))}}var Ps={nodes:[{id:"title",kind:"text",label:"Pi \u67B6\u6784\u603B\u89C8",x:330,y:0,width:600,height:60,fontSize:36},{id:"entry",kind:"group",label:"\u2460 \u5165\u53E3 / \u6A21\u5F0F\u5206\u53D1",x:0,y:100,width:1280,height:180,backgroundColor:"#eff6ff",strokeColor:"#93c5fd"},{id:"core",kind:"group",label:"\u2461 \u5E94\u7528\u6838\u5FC3",x:0,y:310,width:1280,height:210,backgroundColor:"#f5f3ff",strokeColor:"#c4b5fd"},{id:"runtime",kind:"group",label:"\u2462 \u8FD0\u884C\u65F6\u5E93",x:0,y:550,width:1280,height:200,backgroundColor:"#f0fdf4",strokeColor:"#86efac"},{id:"infra",kind:"group",label:"\u2463 \u57FA\u7840\u8BBE\u65BD",x:0,y:1e3,width:1280,height:150,backgroundColor:"#fff7ed",strokeColor:"#fdba74"},{id:"cli",label:"pi CLI \xB7 main.ts",x:110,y:160,width:360,height:80,groupId:"entry",strokeColor:"#3b82f6",backgroundColor:"#bfdbfe"},{id:"modes",label:"interactive \xB7 print \xB7 rpc",x:730,y:160,width:440,height:80,groupId:"entry",strokeColor:"#3b82f6",backgroundColor:"#bfdbfe"},{id:"session",label:"AgentSession \u6838\u5FC3",x:100,y:375,width:450,height:90,groupId:"core",strokeColor:"#8b5cf6",backgroundColor:"#ddd6fe",fontSize:26},{id:"manager",label:"SessionManager \xB7 JSONL",x:790,y:375,width:380,height:90,groupId:"core",strokeColor:"#22c55e",backgroundColor:"#bbf7d0"},{id:"tools",kind:"text",label:"\u5185\u7F6E\u5DE5\u5177\uFF1Abash \xB7 fs \xB7 edit \xB7 grep",x:110,y:475,width:500,height:30,groupId:"core",fontSize:16,strokeColor:"#64748b"},{id:"agent",label:"agent-core",x:40,y:610,width:200,height:80,groupId:"runtime",backgroundColor:"#ddd6fe",strokeColor:"#8b5cf6"},{id:"ai",label:"pi-ai",x:300,y:610,width:190,height:80,groupId:"runtime",backgroundColor:"#bfdbfe",strokeColor:"#3b82f6"},{id:"tui",label:"pi-tui",x:550,y:610,width:190,height:80,groupId:"runtime",backgroundColor:"#fef3c7",strokeColor:"#f59e0b"},{id:"code",label:"codemode",x:800,y:610,width:190,height:80,groupId:"runtime",backgroundColor:"#fed7aa",strokeColor:"#f97316"},{id:"mcp",label:"pi-mcp",x:1050,y:610,width:190,height:80,groupId:"runtime",backgroundColor:"#bbf7d0",strokeColor:"#22c55e"},{id:"fs",label:"\u6587\u4EF6\u7CFB\u7EDF \xB7 \u8FDB\u7A0B",x:30,y:820,width:230,height:80,strokeStyle:"dashed",backgroundColor:"#f8fafc",strokeColor:"#94a3b8"},{id:"providers",label:"Provider APIs",x:300,y:820,width:240,height:80,strokeStyle:"dashed",backgroundColor:"#f8fafc",strokeColor:"#94a3b8"},{id:"servers",label:"MCP servers",x:1030,y:820,width:230,height:80,strokeStyle:"dashed",backgroundColor:"#f8fafc",strokeColor:"#94a3b8"},{id:"infra-text",kind:"text",label:"chord \xB7 durable \xB7 protocol / server / client \xB7 env \xB7 telemetry",x:80,y:1070,width:1140,height:40,groupId:"infra",strokeColor:"#b45309"},{id:"experiment",label:"\u5B9E\u9A8C\uFF08\u975E\u9ED8\u8BA4\u88C5\u914D\uFF09\uFF1Aexperimental server / client",x:520,y:1230,width:740,height:80,strokeStyle:"dashed",strokeColor:"#f59e0b",backgroundColor:"#fef3c7"}],edges:[{id:"dispatch",from:"cli",to:"modes",waypoints:[[620,200]]},{id:"shared",from:"modes",to:"session"},{id:"persist",from:"session",to:"manager",label:"\u4E8B\u4EF6 \u2192 \u6301\u4E45\u5316",strokeColor:"#22c55e"},{id:"loop",from:"session",to:"agent"},{id:"stream",from:"agent",to:"ai"},{id:"filesystem",from:"agent",to:"fs",strokeColor:"#8b5cf6"},{id:"provider",from:"ai",to:"providers",strokeColor:"#3b82f6"},{id:"mcp-api",from:"mcp",to:"servers",strokeColor:"#22c55e"},{id:"dependency",from:"tui",to:"infra",strokeStyle:"dashed",strokeColor:"#94a3b8",label:"npm workspace \u4F9D\u8D56"},{id:"experimental",from:"infra",to:"experiment",strokeStyle:"dashed",strokeColor:"#f59e0b"}]},zr={elementsGuide:'Preferred drawing workflow: user speaks in the main chat \u2192 excalidraw_read_me \u2192 excalidraw_create_view({title, elements: JSON.stringify([...])}) \u2192 diagram is displayed in this tool result \u2192 Edit opens only the native Excalidraw editor. No second prompt form, no initial acceptance step. This is a local native adapter, not a remote MCP service. elements: 1\u2013150 objects; types rectangle/ellipse/diamond/text/line/arrow. Each needs stable ASCII id and x/y. Shapes need width/height (20\u201310000); text needs text and preferably fontSize (16\u201336). Use label:{text,fontSize:20} for centered bound labels; optional textAlign and verticalAlign. Use separate text for headings. Safe colors #RRGGBB or transparent, fillStyle solid/hachure/cross-hatch/zigzag, strokeStyle solid/dashed/dotted, roundness:{type:3}, roughness:1, opacity:0\u2013100, groupIds:[string] (up to 10 IDs; each 1\u2013100 Unicode letters/digits, underscores or hyphens; e.g. ["core-layer_2", "\u6838\u5FC3\u5C42"]). Arrows/lines need points:[[0,0],[dx,dy],\u2026] relative to x/y; bind with start:{id:shapeId}, end:{id:shapeId}; endArrowhead:arrow/bar/dot/triangle/null. No URLs, images, embeds, scripts or pseudo-elements. Put background zones first, then shapes, labels and purposeful arrows. Explicitly position generous 20\u201340px gaps; use pastel #a5d8ff/#d0bfff/#b2f2bb/#ffd8a8 and dark readable text. Chinese fonts are local. Tool arguments may render progressively; final rendering is authoritative. To change the current drawing: diagram_read({}) gets latest selected drawing and revision including hand edits, then diagram_patch for targeted changes; user confirms existing edits in chat. Full replacement via excalidraw_create_view with id/baseRevision also requires chat confirmation. Never rebuild unrelated manual content. Save/export are native menu actions; do not claim files or PNG exist before that.',elementsExample:{title:"\u767B\u5F55\u6D41\u7A0B",elements:JSON.stringify([{type:"rectangle",id:"input",x:40,y:80,width:220,height:100,backgroundColor:"#a5d8ff",label:{text:"\u8F93\u5165\u9A8C\u8BC1\u7801",fontSize:20}},{type:"diamond",id:"check",x:400,y:60,width:220,height:140,backgroundColor:"#fff3bf",label:{text:"\u9A8C\u8BC1\u901A\u8FC7\uFF1F",fontSize:20}},{type:"arrow",id:"verify",x:260,y:130,points:[[0,0],[140,0]],start:{id:"input"},end:{id:"check"},endArrowhead:"arrow"}])},guide:"Legacy graph shortcut: Draw locally; no Excalidraw account or external service is needed. Use diagram_create with title and graph. For simple flows omit coordinates and use top-down/left-right. For rich architecture use explicit x/y/width/height for ALL nodes, generous spacing and few purposeful arrows. nodes: process (rectangle), decision (diamond), terminal (ellipse), text (standalone title/annotation), group (background container, label top-left). Put background containers first; groupId on children associates native selection groups, not hierarchical layout. A group must exist and cannot nest. Supported styles: strokeColor/backgroundColor (#RGB/#RRGGBB/transparent), strokeStyle (solid/dashed/dotted), fontSize 12\u201396. Edges: id/from/to/optional label, strokeColor/strokeStyle/fontSize; optional waypoints are ABSOLUTE intermediate [x,y] coordinates, endpoints stay bound. No arrows to standalone text. Up to 30 nodes, 60 edges, 12 waypoints per edge. Leave room under a group's heading and around notes. Use separate text nodes for subtitles; do not connect every library in a false sequential chain. Chinese is supported by bundled fonts. A new drawing appears directly in chat and becomes editable automatically. Changes to existing drawings require review in chat; saving is separate. For edits call diagram_read first; use updateElements for geometry/styles or standalone text, updateNodes for bound labels, addNodes/addEdges/removeIds for structure. Do not target a bound text ID; target its container. Moving a shape reroutes its incident bound arrows; untouched paths and elements remain. Do not claim a candidate was accepted or a file saved.",example:{title:"Pi \u5206\u5C42\u67B6\u6784\uFF08\u6784\u56FE\u793A\u4F8B\uFF0C\u4E0D\u662F\u6E90\u7801\u5BA1\u8BA1\uFF09",graph:Ps}};var Ue=class{scopes=new Map;saving=new Set;focused=new Map;checkpoint(e,t){return structuredClone({drafts:[...this.scope(e,t).values()],focused:this.focused.get(this.scopeKey(e,t))??null})}restoreCheckpoint(e,t,i){this.scopes.set(this.scopeKey(e,t),new Map(i.drafts.map(n=>[n.id,n]))),i.focused&&this.focused.set(this.scopeKey(e,t),i.focused)}scopeKey(e,t){return JSON.stringify([e,t])}scope(e,t){let i=JSON.stringify([e,t]),n=this.scopes.get(i);return n||(n=new Map,this.scopes.set(i,n)),n}draft(e,t,i){let n=this.scope(e,t).get(j(i));if(!n)throw new A("\u56FE\u7A3F\u4E0D\u5C5E\u4E8E\u5F53\u524D\u4F1A\u8BDD\u6216\u670D\u52A1\u5DF2\u91CD\u542F\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u5DF2\u4FDD\u5B58\u6587\u4EF6",404,"diagram_unavailable");return n}expected(e,t){if(t!==e.revision||this.saving.has(e.id))throw new A("\u56FE\u7A3F\u4FEE\u8BA2\u5DF2\u53D8\u5316\u6216\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\uFF1B\u672C\u5730\u8349\u7A3F\u4ECD\u53EF\u4E0B\u8F7D",409)}list(e,t){return[...this.scope(e,t).values()].map(i=>({id:i.id,title:i.title,revision:i.revision,path:i.path,savedRevision:i.savedRevision,pending:!!i.candidate}))}add(e,t,i){let n=this.scope(e,t);if(n.size>=100)throw new A("\u5F53\u524D\u4F1A\u8BDD\u56FE\u7A3F\u5DF2\u8FBE 100 \u4EFD\u4E0A\u9650");let s={id:ct(),title:i,revision:0,scene:_r(),path:null,diskHash:null,savedRevision:null,candidate:null};return n.set(s.id,s),this.focused.set(this.scopeKey(e,t),s.id),s}tool(e,t,i,n){if(!R(n))throw new A("\u7ED8\u56FE\u5DE5\u5177\u8F93\u5165\u65E0\u6548");if(i==="reference")return structuredClone(zr);if(i==="create"){let c=nt(n.graph),l=re(n.title),p=this.add(e,t,l);return p.candidate={id:ct(),baseRevision:p.revision,graph:c},{id:p.id,title:l,revision:p.revision,status:"pending_canvas_acceptance",message:"\u7ED3\u6784\u5DF2\u5EFA\u7ACB\uFF0C\u56FE\u7A3F\u5C06\u5728\u5BF9\u8BDD\u4E2D\u81EA\u52A8\u5448\u73B0\u5E76\u53EF\u76F4\u63A5\u7F16\u8F91\uFF0C\u65E0\u9700\u7528\u6237\u63A5\u53D7\u9996\u6B21\u521B\u5EFA\u3002\u5C1A\u672A\u4FDD\u5B58\u6587\u4EF6\u6216\u751F\u6210 PNG\u3002"}}if(i==="view"){let c=ot(n.elements),l=n.title===void 0?"Excalidraw":re(n.title),p=n.id===void 0?this.add(e,t,l):this.draft(e,t,n.id);if(n.id!==void 0&&(this.expected(p,n.baseRevision),p.candidate))throw new A("\u8BF7\u5148\u5728\u5BF9\u8BDD\u4E2D\u5904\u7406\u5DF2\u6709\u4FEE\u6539",409);return p.candidate={id:ct(),baseRevision:p.revision,elements:c},{id:p.id,title:p.title,revision:p.revision,status:n.id===void 0?"pending_canvas":"pending_review",message:n.id===void 0?"\u56FE\u7A3F\u5C06\u5728\u5BF9\u8BDD\u4E2D\u81EA\u52A8\u5448\u73B0\u5E76\u53EF\u76F4\u63A5\u7F16\u8F91\uFF0C\u65E0\u9700\u7528\u6237\u63A5\u53D7\u9996\u6B21\u521B\u5EFA\u3002\u5C1A\u672A\u5199\u5165\u5DE5\u4F5C\u533A\u6216\u5BFC\u51FA\u56FE\u7247\u3002":"\u4FEE\u6539\u5DF2\u5728\u5BF9\u8BDD\u4E2D\u9884\u89C8\uFF0C\u4FDD\u7559\u539F\u56FE\uFF0C\u7B49\u5F85\u7528\u6237\u786E\u8BA4\u3002"}}let s=this.draft(e,t,n.id??(i==="read"?this.focused.get(this.scopeKey(e,t)):void 0));if(i==="read"){let c=n.elementIds===void 0?null:Array.isArray(n.elementIds)&&n.elementIds.length<=100?new Set(n.elementIds.map(j)):(()=>{throw new A("\u5143\u7D20\u8BFB\u53D6\u8303\u56F4\u65E0\u6548")})(),l=s.scene.elements.filter(u=>!u.isDeleted),p=c?l.filter(u=>c.has(u.id)||u.containerId&&c.has(u.containerId)):l.slice(0,100);return{totalElements:l.length,truncated:!c&&l.length>p.length,id:s.id,title:s.title,revision:s.revision,saved:s.revision===s.savedRevision,pending:!!s.candidate,elements:p.map(u=>({id:u.id,type:u.type,x:u.x,y:u.y,width:u.width,height:u.height,...u.text===void 0?{}:{text:u.text},...u.containerId?{containerId:u.containerId}:{},...u.startBinding?{startBinding:u.startBinding}:{},...u.endBinding?{endBinding:u.endBinding}:{},...Object.fromEntries(["strokeColor","backgroundColor","strokeStyle","fontSize","groupIds","customData"].filter(h=>u[h]!==void 0).map(h=>[h,u[h]]))}))}}if(i!=="patch")throw new A("\u672A\u77E5\u7ED8\u56FE\u5DE5\u5177");if(this.expected(s,n.baseRevision),s.candidate)throw new A("\u8BF7\u5148\u5728\u5BF9\u8BDD\u4E2D\u5E94\u7528\u5DF2\u6709\u4FEE\u6539\u6216\u4FDD\u7559\u539F\u56FE",409);let o=st(n.patch,s.scene);return s.candidate={id:ct(),baseRevision:s.revision,patch:o},{id:s.id,title:s.title,revision:s.revision,status:"pending_canvas_acceptance",message:"\u4FEE\u6539\u5DF2\u5728\u5BF9\u8BDD\u5DE5\u5177\u7ED3\u679C\u4E2D\u9884\u89C8\uFF0C\u539F\u56FE\u672A\u88AB\u66FF\u6362\uFF1B\u8BF7\u7528\u6237\u5728\u5BF9\u8BDD\u4E2D\u5E94\u7528\u4FEE\u6539\u6216\u4FDD\u7559\u539F\u56FE\u3002\u53F3\u4FA7\u4ECD\u53EF\u624B\u52A8\u7F16\u8F91\u539F\u56FE\u3002"}}async action(e,t,i,n,s){if(s(),i==="list")return this.list(e,t);if(i==="new")return structuredClone(this.add(e,t,"\u672A\u547D\u540D\u56FE\u7A3F"));if(i==="open"){let c=await Gr(e,n.path);s();let l=[...this.scope(e,t).values()].find(u=>u.path===n.path);if(l&&l.revision!==l.savedRevision)throw new A("\u6B64\u6587\u4EF6\u5DF2\u6709\u672A\u4FDD\u5B58\u8349\u7A3F\uFF0C\u8BF7\u5148\u4FDD\u5B58\u6216\u53E6\u5B58",409);let p=this.add(e,t,Is(n.path,".excalidraw"));return p.scene=c.scene,p.path=n.path,p.diskHash=c.hash,p.savedRevision=0,structuredClone(p)}if(i==="import"){let c=ce(n.scene),l=this.add(e,t,typeof n.title=="string"?re(n.title):"\u5BFC\u5165\u56FE\u7A3F");return l.scene=c,structuredClone(l)}let o=this.draft(e,t,n.id);if(i==="get")return structuredClone(o);if(i==="focus")return this.focused.set(this.scopeKey(e,t),o.id),{id:o.id};if(this.expected(o,n.revision),i==="sync")return o.scene=ce(n.scene),o.revision++,structuredClone(o);if(i==="initialize"||i==="accept"||i==="reject"){let c=o.candidate;if(!c||c.id!==n.candidateId)throw new A("\u5019\u9009\u5DF2\u53D8\u5316",409);if(i==="initialize"&&(o.revision!==0||o.scene.elements.length||c.patch))throw new A("\u53EA\u80FD\u81EA\u52A8\u5448\u73B0\u5C1A\u672A\u7F16\u8F91\u7684\u65B0\u56FE\u7A3F",409);if(i==="accept"||i==="initialize"){if(c.baseRevision!==o.revision)throw new A("\u5019\u9009\u57FA\u4E8E\u65E7\u56FE\u7A3F\uFF0C\u4E0D\u80FD\u8986\u76D6\u6700\u65B0\u624B\u6539\uFF1B\u8BF7\u62D2\u7EDD\u540E\u91CD\u65B0\u751F\u6210",409);o.scene=ce(n.scene),o.revision++}return o.candidate=null,structuredClone(o)}if(i==="save"){if(o.candidate)throw new A("\u8BF7\u5148\u63A5\u53D7\u6216\u62D2\u7EDD\u4FEE\u6539\u5019\u9009");let c=o.revision,l=n.path===o.path?o.diskHash:null;this.saving.add(o.id);try{let p=await Ur(e,n.path,o.scene,l,()=>{if(s(),o.revision!==c)throw new A("\u4FDD\u5B58\u671F\u95F4\u56FE\u7A3F\u5DF2\u4FEE\u6539",409)});return o.path=n.path,o.diskHash=p,o.savedRevision=c,structuredClone(o)}finally{this.saving.delete(o.id)}}throw new A("\u672A\u77E5\u56FE\u7A3F\u64CD\u4F5C")}};var Os=r=>r.code==="ENOENT",Ws=r=>Ts("sha256").update(r).digest("hex"),qr=3*524288;async function Vr(r,e=qr){let t;try{t=await Jt(r,zt.O_RDONLY|zt.O_NONBLOCK|(zt.O_NOFOLLOW??0))}catch(i){if(Os(i))return null;throw i}try{let i=await t.stat();if(!i.isFile()||i.size>e)throw new Error("Invalid diagram checkpoint size or type");let n=Buffer.alloc(e+1),s=0;for(;s<n.length;){let{bytesRead:o}=await t.read(n,s,n.length-s,s);if(!o)break;s+=o}if(s>e)throw new Error("Oversized diagram checkpoint");return new TextDecoder("utf-8",{fatal:!0}).decode(n.subarray(0,s))}finally{await t.close()}}async function Jr(r){await _s(r,{recursive:!0,mode:448});let e=await Cs(r);if(!e.isDirectory()||e.isSymbolicLink())throw new Error("Diagram storage must be a real directory")}async function Hr(r,e){let t=`${r}.${Rs()}.tmp`,i=await Jt(t,"wx",384);try{try{await i.writeFile(e),await i.sync()}finally{await i.close()}await As(t,r)}finally{await Vt(t).catch(()=>{})}}function Fs(r){if(!R(r))throw new Error("Invalid checkpoint");let e=j(r.id),t=re(r.title),i=ce(r.scene);if(!Number.isSafeInteger(r.revision)||r.revision<0||!(r.savedRevision===null||Number.isSafeInteger(r.savedRevision)&&r.savedRevision>=0&&r.savedRevision<=r.revision)||!(r.path===null||typeof r.path=="string"&&r.path.length<=4096)||!(r.diskHash===null||typeof r.diskHash=="string"&&/^[a-f0-9]{64}$/.test(r.diskHash)))throw new Error("Invalid checkpoint metadata");let n={id:e,title:t,scene:i,revision:r.revision,savedRevision:r.savedRevision,path:r.path,diskHash:r.diskHash,candidate:null};if(r.candidate!==null){let s=r.candidate;if(!R(s)||!Number.isSafeInteger(s.baseRevision)||s.baseRevision<0||s.baseRevision>n.revision||[s.elements,s.graph,s.patch].filter(o=>o!==void 0).length!==1)throw new Error("Invalid checkpoint candidate");n.candidate={id:j(s.id),baseRevision:s.baseRevision,...s.elements===void 0?{}:{elements:ot(s.elements)},...s.graph===void 0?{}:{graph:nt(s.graph)},...s.patch===void 0?{}:{patch:s.baseRevision===n.revision?st(s.patch,i):R(s.patch)?structuredClone(s.patch):(()=>{throw new Error("Invalid checkpoint patch")})()}}}return n}var lt=class{root;constructor(e=ve(Ms(),"pi-web","diagrams")){this.root=e}async lock(e){let t=ve(e,"scope.lock");for(let i=0;i<100;i++)try{let n=await Jt(t,"wx",384);try{await n.writeFile(JSON.stringify({pid:process.pid}))}catch(s){throw await n.close(),await Vt(t),s}return async()=>{await n.close(),await Vt(t)}}catch(n){if(n.code!=="EEXIST")throw n;await Ds(20)}throw new A("\u56FE\u7A3F\u5B58\u50A8\u6B63\u5FD9\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF1B\u672A\u8986\u76D6\u56FE\u7A3F",409)}async run(e,t,i){let n,s=!1;try{await Jr(this.root);let o=ve(this.root,Ws(JSON.stringify([e,t])));await Jr(o),n=await this.lock(o);let c=(await Ns(o)).filter(y=>/^[\w-]{1,80}\.json$/.test(y)&&y!=="focus.json");if(c.length>100)throw new Error("Too many diagram checkpoints");let l=[],p=new Map;for(let y of c){let N=await Vr(ve(o,y));if(!N)throw new Error("Missing diagram checkpoint");let P=JSON.parse(N);if(!R(P)||P.version!==1||P.cwd!==e||P.sessionId!==t)throw new Error("Checkpoint scope mismatch");let W=Fs(P.draft);if(y!==`${W.id}.json`)throw new Error("Checkpoint ID mismatch");l.push(W),p.set(W.id,JSON.stringify(W))}let u=await Vr(ve(o,"focus.json"),1024),h=u?JSON.parse(u):null,d=new Ue;d.restoreCheckpoint(e,t,{drafts:l,focused:typeof h=="string"&&l.some(y=>y.id===h)?h:null}),s=!0;let g=await i(d),m=d.checkpoint(e,t);s=!1;for(let y of m.drafts)if(JSON.stringify(y)!==p.get(y.id)){let P=JSON.stringify({version:1,cwd:e,sessionId:t,draft:y});if(Buffer.byteLength(P)>qr)throw new Error("Oversized diagram checkpoint");await Hr(ve(o,`${j(y.id)}.json`),P)}return m.focused!==h&&await Hr(ve(o,"focus.json"),JSON.stringify(m.focused)),g}catch(o){throw o instanceof A&&(s||o.status===409)?o:new A("\u56FE\u7A3F\u672C\u5730\u5B58\u50A8\u8BFB\u53D6\u6216\u5199\u5165\u5931\u8D25\uFF1B\u539F\u6570\u636E\u672A\u88AB\u81EA\u52A8\u6E05\u7A7A\uFF0C\u8BF7\u4FDD\u7559\u8349\u7A3F\u540E\u91CD\u8BD5",500,"diagram_storage_error")}finally{await n?.()}}tool(e,t,i,n){return i==="reference"?Promise.resolve(new Ue().tool(e,t,i,n)):this.run(e,t,s=>s.tool(e,t,i,n))}action(e,t,i,n,s){return this.run(e,t,async o=>{s();let c=await o.action(e,t,i,n,s);return s(),c})}};var Bs=["list","new","get","open","import","sync","focus","initialize","accept","reject","save"];function Kr(){let r=new lt;return{metadata:Mr,routes:Bs.map(e=>`/api/diagrams/${e}`),agentAction:(e,t,i,n)=>r.tool(e,t,i,n),async handle({path:e,body:t,snapshot:i,json:n}){let s=i(),o=()=>{let c=i();if(t.sessionId!==s.sessionId||c.sessionId!==s.sessionId||c.cwd!==s.cwd)throw new A("\u4F1A\u8BDD\u5DF2\u5207\u6362",409)};try{let c=await r.action(s.cwd,s.sessionId,e.split("/").at(-1),t,o);n(200,c)}catch(c){if(c instanceof A)n(c.status,{error:c.message,errorCode:"validation_error",...c.reason?{reason:c.reason}:{}});else throw c}}}}import{isAbsolute as wo,relative as yo}from"node:path";var Re={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var Xr={id:Re.git,kind:"builtin",version:"1.0.0",name:{zh:"Git",en:"Git"},description:{zh:"\u5BA1\u9605\u5DE5\u4F5C\u533A\u6539\u52A8\u4E0E\u63D0\u4EA4\u5386\u53F2\uFF0C\u6682\u5B58\u6587\u4EF6\u3001\u63D0\u4EA4\u5E76\u7BA1\u7406\u672C\u5730\u5206\u652F\u3002",en:"Review workspace changes and history, stage files, commit and manage local branches."}};import{execFile as js}from"node:child_process";import{realpath as $s}from"node:fs/promises";import{isAbsolute as Yr,relative as Ls,sep as Gs,win32 as Us}from"node:path";var _=class extends Error{status;reason;constructor(e,t=400,i="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=i}};function D(r,e,t=2*1024*1024,i={}){let n=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_")));return new Promise((s,o)=>{let c,l=js("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:r,env:{...n,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:i.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(p,u,h)=>{if(!p){if(c){o(new _("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,i.write?"outcome_unknown":"git_failed"));return}s(u);return}if(i.write){let g=p.killed||p.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(h)?"index_locked":/already exists/i.test(h)?"branch_exists":/already checked out|used by worktree/i.test(h)?"branch_in_use":/would be overwritten|local changes/i.test(h)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(h)?"identity_missing":"git_failed";o(new _("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",g==="outcome_unknown"?503:409,g));return}let d=p.code;d==="ENOENT"?o(new _("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):d==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new _("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(h)?o(new _("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new _(p.killed?"Git \u8BFB\u53D6\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5":"Git \u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u548C\u76EE\u5F55\u6743\u9650",503))});l.stdin?.on("error",p=>{c=p}),i.input!==void 0&&l.stdin?.end(i.input)})}async function le(r){let e=await $s(r),t;try{t=(await D(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(n){if(n instanceof _&&n.status===404)return{kind:"not-repository"};if(n instanceof _&&n.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw n}let i=Ls(t,e).split(Gs).join("/");if(i===".."||i.startsWith("../")||Yr(i))throw new _("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:i?`${i}/`:""}}function Ee(r){if(typeof r!="string"||!r||r.length>4096||r.includes("\0")||r.includes("\\")||Yr(r)||Us.isAbsolute(r)||r.split("/").some(e=>!e||e==="."||e===".."))throw new _("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as no}from"node:crypto";import{lstat as Xt,realpath as di}from"node:fs/promises";import{dirname as li,isAbsolute as so,relative as oo,resolve as Ve}from"node:path";import{lstat as to}from"node:fs/promises";import{resolve as ro}from"node:path";import{constants as Ht}from"node:fs";import{open as zs,opendir as Vs,realpath as Qr,stat as ti}from"node:fs/promises";import{isAbsolute as ri,relative as Js,resolve as Hs,sep as qs,win32 as Ks}from"node:path";var Xs=1e3,Ys=512*1024,Qs=8*1024*1024,Zr=1e4,Zs=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),$=class extends Error{status;constructor(e,t=400){super(e),this.name="WorkspaceFileError",this.status=t}};function ei(r,e){let t=Js(r,e);return t!==".."&&!t.startsWith(`..${qs}`)&&!ri(t)}async function qt(r,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||ri(e)||Ks.isAbsolute(e))throw new $("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await Qr(r),i=Hs(t,e);if(!ei(t,i))throw new $("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let n=await Qr(i);if(!ei(t,n))throw new $("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return n}async function ii(r){try{return await r()}catch(e){if(e instanceof $)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new $("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new $("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function ni(r,e){return ii(async()=>{let t=await qt(r,e),i=[],n=!1;for await(let s of await Vs(t)){if(i.length===Xs){n=!0;break}let o=e?`${e}/${s.name}`:s.name,c=s.isDirectory()?"directory":s.isFile()?"file":"other";if(s.isSymbolicLink())try{let l=await ti(await qt(r,o));c=l.isDirectory()?"directory":l.isFile()?"file":"other"}catch{}i.push({name:s.name,path:o,kind:c})}return i.sort((s,o)=>+(o.kind==="directory")-+(s.kind==="directory")||Zs.compare(s.name,o.name)||s.name.localeCompare(o.name)),{path:e,entries:i,truncated:n}})}function eo(r){if(r.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(r[0]===255&&r[1]===216&&r[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(r.subarray(0,6).toString("ascii")))return"image/gif";if(r.subarray(0,4).toString("ascii")==="RIFF"&&r.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function ze(r,e){return ii(async()=>{let t=await qt(r,e);if(!(await ti(t)).isFile())throw new $("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await zs(t,Ht.O_RDONLY|Ht.O_NONBLOCK|(Ht.O_NOFOLLOW??0));try{let n=await i.stat();if(!n.isFile())throw new $("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let s={path:e,size:n.size},o=Buffer.alloc(16);await i.read(o,0,o.length,0);let c=eo(o),l=c?Qs:Ys;if(n.size>l)return{...s,kind:"too-large",limit:l,unit:"bytes"};let p=Buffer.alloc(Math.min(n.size+1,l+1)),u=0;for(;u<p.length;){let{bytesRead:g}=await i.read(p,u,p.length-u,u);if(!g)break;u+=g}if(u>n.size)throw new $("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let h=p.subarray(0,u);if(c)return{...s,kind:"image",mimeType:c,data:h.toString("base64")};if(h.some(g=>g===0||g<32&&![9,10,12,13,27].includes(g)))return{...s,kind:"unsupported"};let d=1;for(let g=0;g<h.length-1;g++)if(h[g]===10&&++d>Zr)return{...s,kind:"too-large",limit:Zr,unit:"lines"};try{return{...s,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(h)}}catch{return{...s,kind:"unsupported"}}}finally{await i.close()}})}var io=1e3,si=512*1024,oi=1e4;function ai(r,e){return e.startsWith(r)&&e.slice(r.length)||void 0}async function De(r){let e=await le(r);if(e.kind!=="repository")return e;let{root:t,scope:i}=e,n=await D(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),s={kind:"repository",root:t,scope:i,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=n.split("\0");for(let c=0;c<o.length;c++){let l=o[c];if(l.startsWith("# branch.oid ")){let P=l.slice(13);s.head=P==="(initial)"?null:P;continue}if(l.startsWith("# branch.head ")){let P=l.slice(14);s.branch=P==="(detached)"?null:P;continue}if(l.startsWith("# branch.upstream ")){s.upstream=l.slice(18);continue}if(l.startsWith("# branch.ab ")){let P=l.match(/\+(\d+) -(\d+)/);P&&(s.ahead=Number(P[1]),s.behind=Number(P[2]));continue}let p=l[0];if(!["1","2","u","?"].includes(p??""))continue;let u=p==="?"?1:p==="1"?8:p==="2"?9:10,h=0;for(let P=0;P<u;P++)h=l.indexOf(" ",h)+1;let d=ai(i,l.slice(h)),g=p==="2"?o[++c]:void 0;if(!d)continue;if(s.entries.length===io){s.truncated=!0;continue}let m=l.slice(0,h).split(" "),y={path:d,index:p==="?"?"?":m[1][0],worktree:p==="?"?"?":m[1][1],conflict:p==="u",untracked:p==="?",submodule:p!=="?"&&m[2]!=="N..."},N=g===void 0?void 0:ai(i,g);N&&(y.originalPath=N),s.entries.push(y)}return s}async function ci(r,e,t){if(Ee(e),!["staged","unstaged","untracked"].includes(t))throw new _("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let i=await De(r);if(i.kind!=="repository")throw new _("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let n={path:e,area:t},s=i.entries.find(c=>c.path===e);if(!s)return{...n,kind:"empty"};if(s.conflict)return{...n,kind:"conflict"};if(s.submodule)return{...n,kind:"submodule"};if(t==="untracked"){if(!s.untracked)return{...n,kind:"empty"};if(!(await to(ro(r,e))).isFile())return{...n,kind:"unsupported"};let c=await ze(r,e);if(c.kind==="too-large")return{...n,kind:"too-large"};if(c.kind!=="text")return{...n,kind:"binary"};if(!c.text)return{...n,kind:"empty"};let l=c.text.split(`
1
+ (function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="6984214c-6ad1-4a02-a495-424e8f41e38b",r._sentryDebugIdIdentifier="sentry-dbid-6984214c-6ad1-4a02-a495-424e8f41e38b")}catch{}})();import{delimiter as pl,dirname as ul,join as Dt,resolve as xr}from"node:path";import{realpathSync as ns,watch as fl}from"node:fs";import{fileURLToPath as gl}from"node:url";import{DefaultPackageManager as cs,getAgentDir as Ne,ModelRuntime as ml,SessionManager as ls,SettingsManager as hl,VERSION as vr}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as wl}from"@earendil-works/pi-ai";import{randomBytes as xn,randomUUID as or,timingSafeEqual as La}from"node:crypto";import{readFile as Ga,readdir as Ua}from"node:fs/promises";import{createServer as za}from"node:http";import{join as ar}from"node:path";import{getAgentDir as Va}from"@earendil-works/pi-coding-agent";import{Type as S}from"@earendil-works/pi-ai";var it="@pi-webapp/diagrams",A=class extends Error{status;reason;constructor(e,t=400,i){super(e),this.name="DiagramError",this.status=t,this.reason=i}};function R(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function E(r){throw new A(r)}function j(r){return typeof r=="string"&&/^[\w-]{1,80}$/.test(r)?r:E("\u56FE\u5F62 ID \u65E0\u6548")}function re(r){return typeof r=="string"&&r.length>0&&r.length<=500?r:E("\u6587\u6848\u987B\u4E3A 1\u2013500 \u5B57\u7B26")}function Pr(r){let e={};for(let t of["x","y","width","height"])if(r[t]!==void 0){let i=r[t];(typeof i!="number"||!Number.isFinite(i)||Math.abs(i)>1e5||(t==="width"||t==="height")&&(i<20||i>1e4))&&E("\u8282\u70B9\u5750\u6807\u6216\u5C3A\u5BF8\u65E0\u6548"),e[t]=i}return e}function Le(r){let e={};for(let t of["strokeColor","backgroundColor"])r[t]!==void 0&&((typeof r[t]!="string"||!/^(#[\da-f]{6}|#[\da-f]{3}|transparent)$/i.test(r[t]))&&E("\u7ED8\u56FE\u989C\u8272\u987B\u4E3A\u5341\u516D\u8FDB\u5236\u6216 transparent"),e[t]=r[t]);return r.strokeStyle!==void 0&&(["solid","dashed","dotted"].includes(String(r.strokeStyle))||E("\u7EBF\u578B\u65E0\u6548"),e.strokeStyle=r.strokeStyle),r.fontSize!==void 0&&((typeof r.fontSize!="number"||!Number.isFinite(r.fontSize)||r.fontSize<12||r.fontSize>96)&&E("\u5B57\u53F7\u987B\u4E3A 12\u201396"),e.fontSize=r.fontSize),e}function Ir(r){return(!Array.isArray(r)||r.length>30)&&E("\u6BCF\u6B21\u6700\u591A 30 \u4E2A\u8282\u70B9"),r.map(e=>{R(e)||E("\u8282\u70B9\u65E0\u6548");let t={id:j(e.id),label:re(e.label),...Pr(e),...Le(e)};return e.kind!==void 0&&(["process","decision","terminal","text","group"].includes(String(e.kind))||E("\u8282\u70B9\u7C7B\u578B\u65E0\u6548"),t.kind=e.kind),e.groupId!==void 0&&(t.groupId=j(e.groupId)),t})}function Cr(r){return(!Array.isArray(r)||r.length>60)&&E("\u6BCF\u6B21\u6700\u591A 60 \u6761\u8FDE\u7EBF"),r.map(e=>{R(e)||E("\u8FDE\u7EBF\u65E0\u6548");let t={id:j(e.id),from:j(e.from),to:j(e.to),...Le(e),...e.label===void 0?{}:{label:re(e.label)}};return e.waypoints!==void 0&&((!Array.isArray(e.waypoints)||e.waypoints.length>12||e.waypoints.some(i=>!Array.isArray(i)||i.length!==2||i.some(n=>typeof n!="number"||!Number.isFinite(n)||Math.abs(n)>1e5)))&&E("\u8FDE\u7EBF\u9014\u7ECF\u70B9\u65E0\u6548"),t.waypoints=e.waypoints),t})}function Ae(r){new Set(r).size!==r.length&&E("\u56FE\u5F62 ID \u91CD\u590D")}function nt(r){R(r)||E("\u56FE\u7ED3\u6784\u65E0\u6548");let e={nodes:Ir(r.nodes),edges:Cr(r.edges??[])};e.nodes.length||E("\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u8282\u70B9"),r.layout!==void 0&&(r.layout!=="top-down"&&r.layout!=="left-right"&&E("\u5E03\u5C40\u65E0\u6548"),e.layout=r.layout),Ae([...e.nodes,...e.edges].map(n=>n.id));let t=new Set(e.nodes.filter(n=>n.kind!=="text").map(n=>n.id)),i=new Set(e.nodes.filter(n=>n.kind==="group").map(n=>n.id));for(let n of e.nodes)n.groupId&&(!i.has(n.groupId)||n.groupId===n.id||n.kind==="group")&&E("\u5206\u7EC4\u5F15\u7528\u65E0\u6548");for(let n of e.edges)(!t.has(n.from)||!t.has(n.to))&&E("\u8FDE\u7EBF\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684\u8282\u70B9");return e}function st(r,e){R(r)||E("\u4FEE\u6539\u64CD\u4F5C\u65E0\u6548");let t={addNodes:Ir(r.addNodes??[]),addEdges:Cr(r.addEdges??[]),updateNodes:[],removeIds:[]};(!Array.isArray(r.updateNodes??[])||!Array.isArray(r.removeIds??[]))&&E("\u4FEE\u6539\u64CD\u4F5C\u65E0\u6548"),((r.updateNodes??[]).length>30||(r.removeIds??[]).length>60)&&E("\u4FEE\u6539\u8FC7\u591A"),t.updateNodes=(r.updateNodes??[]).map(l=>(R(l)||E("\u8282\u70B9\u4FEE\u6539\u65E0\u6548"),{id:j(l.id),label:re(l.label)})),t.removeIds=(r.removeIds??[]).map(j);let i=e.elements.filter(l=>!l.isDeleted),n=new Set(i.filter(l=>["rectangle","diamond","ellipse"].includes(l.type)).map(l=>l.id)),s=new Set(i.map(l=>l.id)),o=new Set(e.elements.map(l=>l.id));for(let l of t.removeIds)s.has(l)||E(`\u5F85\u5220\u9664\u5143\u7D20\u4E0D\u5B58\u5728\uFF1A${l}`);for(let l of t.updateNodes)(!n.has(l.id)||t.removeIds.includes(l.id))&&E(`\u5F85\u4FEE\u6539\u8282\u70B9\u4E0D\u5B58\u5728\uFF1A${l.id}`);for(let l of t.addNodes)o.has(l.id)&&E(`\u5143\u7D20 ID \u5DF2\u5B58\u5728\uFF1A${l.id}`),l.kind!=="text"&&n.add(l.id);for(let l of t.addEdges)(o.has(l.id)||!n.has(l.from)||!n.has(l.to)||t.removeIds.includes(l.from)||t.removeIds.includes(l.to))&&E("\u65B0\u589E\u8FDE\u7EBF\u65E0\u6548");Ae([...t.addNodes,...t.addEdges].map(l=>l.id)),Ae(t.updateNodes.map(l=>l.id)),(!Array.isArray(r.updateElements??[])||(r.updateElements??[]).length>60)&&E("\u5143\u7D20\u4FEE\u6539\u8FC7\u591A"),t.updateElements=(r.updateElements??[]).map(l=>{R(l)||E("\u5143\u7D20\u4FEE\u6539\u65E0\u6548");let p=j(l.id),u=i.find(d=>d.id===p);(!u||t.removeIds.includes(p)||t.updateNodes.some(d=>d.id===p))&&E("\u5F85\u4FEE\u6539\u5143\u7D20\u4E0D\u5B58\u5728\u6216\u64CD\u4F5C\u91CD\u590D");let h={id:p,...Pr(l),...Le(l),...l.label===void 0?{}:{label:re(l.label)}};return Object.keys(h).length===1&&E("\u5143\u7D20\u4FEE\u6539\u4E3A\u7A7A"),["rectangle","ellipse","diamond","text"].includes(u.type)||E("\u6B64\u7C7B\u578B\u4E0D\u652F\u6301\u76F4\u63A5\u4FEE\u6539\uFF0C\u8BF7\u4FEE\u6539\u5176\u7AEF\u70B9\u6216\u91CD\u5EFA\u8FDE\u7EBF"),u.containerId&&E("\u8BF7\u4FEE\u6539\u6587\u672C\u6240\u5C5E\u7684\u56FE\u5F62\uFF0C\u4FDD\u6301\u7ED1\u5B9A\u4E00\u81F4"),h}),Ae(t.updateElements.map(l=>l.id));let c=new Set([...i.filter(l=>l.customData?.diagramKind==="group").map(l=>l.id),...t.addNodes.filter(l=>l.kind==="group").map(l=>l.id)]);for(let l of t.addNodes)l.groupId&&(!c.has(l.groupId)||t.removeIds.includes(l.groupId)||l.kind==="group")&&E("\u5206\u7EC4\u5F15\u7528\u65E0\u6548");return!t.updateElements.length&&!t.addNodes.length&&!t.addEdges.length&&!t.updateNodes.length&&!t.removeIds.length&&E("\u4FEE\u6539\u4E3A\u7A7A"),t}function ot(r){if(typeof r=="string"){new TextEncoder().encode(r).length>524288&&E("\u56FE\u7A3F\u8D85\u8FC7 512 KiB");try{r=JSON.parse(r)}catch{E("elements \u987B\u4E3A\u6709\u6548 JSON \u6570\u7EC4\u5B57\u7B26\u4E32")}}(!Array.isArray(r)||!r.length||r.length>150)&&E("\u6BCF\u6B21\u9700\u8981 1\u2013150 \u4E2A\u7ED8\u56FE\u5143\u7D20"),new TextEncoder().encode(JSON.stringify(r)).length>524288&&E("\u56FE\u7A3F\u8D85\u8FC7 512 KiB");let e=new Set(["type","id","x","y","width","height","text","fontSize","fontFamily","strokeColor","backgroundColor","strokeWidth","strokeStyle","fillStyle","roughness","opacity","angle","roundness","points","start","end","startArrowhead","endArrowhead","label","groupIds","textAlign","verticalAlign"]),t=r.map(n=>{(!R(n)||Object.keys(n).some(o=>!e.has(o)))&&E("\u7ED8\u56FE\u5143\u7D20\u5305\u542B\u4E0D\u652F\u6301\u5B57\u6BB5"),["rectangle","ellipse","diamond","text","line","arrow"].includes(String(n.type))||E("\u7ED8\u56FE\u7C7B\u578B\u4E0D\u652F\u6301");let s={...n,id:j(n.id)};for(let o of["x","y","width","height","fontSize","strokeWidth","roughness","opacity","angle"]){let c=n[o];c!==void 0&&(typeof c!="number"||!Number.isFinite(c)||Math.abs(c)>1e5)&&E("\u7ED8\u56FE\u6570\u503C\u65E0\u6548")}(typeof n.x!="number"||typeof n.y!="number")&&E("\u7ED8\u56FE\u5750\u6807\u7F3A\u5931"),["rectangle","ellipse","diamond"].includes(String(n.type))&&["width","height"].some(o=>typeof n[o]!="number"||n[o]<20||n[o]>1e4)&&E("\u7ED8\u56FE\u5C3A\u5BF8\u65E0\u6548"),n.fontSize!==void 0&&(n.fontSize<12||n.fontSize>96)&&E("\u5B57\u53F7\u987B\u4E3A 12\u201396"),n.fontFamily!==void 0&&n.fontFamily!==5&&E("\u7ED8\u56FE\u9ED8\u8BA4\u4F7F\u7528\u672C\u5730 Excalifont"),Le(n),n.type==="text"?re(n.text):n.text!==void 0&&E("\u5F62\u72B6\u6587\u5B57\u8BF7\u653E\u5165 label");for(let[o,c]of[["roughness",3],["opacity",100],["strokeWidth",16]])n[o]!==void 0&&(n[o]<0||n[o]>c)&&E("\u7ED8\u56FE\u6837\u5F0F\u6570\u503C\u65E0\u6548");for(let o of["width","height"])n[o]!==void 0&&(n[o]<0||n[o]>1e4)&&E("\u7ED8\u56FE\u5C3A\u5BF8\u65E0\u6548");n.label!==void 0&&((!R(n.label)||Object.keys(n.label).some(o=>!["text","fontSize","fontFamily","textAlign","verticalAlign"].includes(o)))&&E("\u7ED8\u56FE\u6807\u7B7E\u65E0\u6548"),re(n.label.text),Le(n.label),n.label.fontFamily!==void 0&&n.label.fontFamily!==5&&E("\u7ED8\u56FE\u6807\u7B7E\u5B57\u4F53\u65E0\u6548"));for(let o of[n,n.label].filter(R))o.textAlign!==void 0&&!["left","center","right"].includes(String(o.textAlign))&&E("\u6587\u5B57\u5BF9\u9F50\u65E0\u6548"),o.verticalAlign!==void 0&&!["top","middle","bottom"].includes(String(o.verticalAlign))&&E("\u6587\u5B57\u5BF9\u9F50\u65E0\u6548");n.fillStyle!==void 0&&!["solid","hachure","cross-hatch","zigzag"].includes(String(n.fillStyle))&&E("\u586B\u5145\u6837\u5F0F\u65E0\u6548"),n.roundness!==void 0&&(!R(n.roundness)||Object.keys(n.roundness).some(o=>o!=="type")||![1,2,3].includes(n.roundness.type))&&E("\u5706\u89D2\u65E0\u6548");for(let o of["startArrowhead","endArrowhead"])n[o]!==void 0&&n[o]!==null&&!["arrow","bar","dot","triangle"].includes(String(n[o]))&&E("\u7BAD\u5934\u6837\u5F0F\u65E0\u6548");for(let o of["start","end"])if(n[o]!==void 0){let c=n[o];(!R(c)||Object.keys(c).some(l=>l!=="id"))&&E("\u7AEF\u70B9\u7ED1\u5B9A\u65E0\u6548"),j(c.id)}return n.groupIds!==void 0&&(!Array.isArray(n.groupIds)||n.groupIds.length>10||n.groupIds.some(o=>typeof o!="string"||o.length>100||!/^[\p{L}\p{N}_-]{1,100}$/u.test(o)))&&E("\u5143\u7D20\u5206\u7EC4\u65E0\u6548\uFF1AgroupIds \u987B\u4E3A\u6700\u591A 10 \u4E2A\u975E\u7A7A\u6587\u5B57/\u6570\u5B57/\u4E0B\u5212\u7EBF/\u8FDE\u5B57\u7B26 ID\uFF0C\u6BCF\u4E2A\u4E0D\u8D85\u8FC7 100 \u5B57\u7B26"),["arrow","line"].includes(String(n.type))&&(!Array.isArray(n.points)||n.points.length<2||n.points.length>100||n.points.some(o=>!Array.isArray(o)||o.length!==2||o.some(c=>typeof c!="number"||!Number.isFinite(c)||Math.abs(c)>1e5)))&&E("\u8DEF\u5F84\u5750\u6807\u65E0\u6548"),structuredClone(s)});Ae(t.map(n=>n.id));let i=new Set(t.filter(n=>["rectangle","ellipse","diamond"].includes(String(n.type))).map(n=>n.id));for(let n of t)for(let s of["start","end"])R(n[s])&&!i.has(n[s].id)&&E("\u8FDE\u7EBF\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684\u5F62\u72B6");return t}function _r(){return{type:"excalidraw",version:2,source:"pi-webapp",elements:[],appState:{viewBackgroundColor:"#ffffff"},files:{}}}function ce(r){(!R(r)||r.type!=="excalidraw"||r.version!==2||!Array.isArray(r.elements)||r.elements.length>400)&&E("\u65E0\u6548\u6216\u8FC7\u5927\u7684 Excalidraw \u573A\u666F"),new TextEncoder().encode(JSON.stringify(r)).length>524288&&E("\u56FE\u7A3F\u8D85\u8FC7 512 KiB"),r.files!==void 0&&(!R(r.files)||Object.keys(r.files).length)&&E("\u9996\u671F\u4E0D\u652F\u6301\u5D4C\u5165\u56FE\u7247\u6216\u9644\u4EF6");let e=r.elements,t=[];for(let s of e){(!R(s)||typeof s.id!="string"||!s.id||s.id.length>100||!["rectangle","ellipse","diamond","text","line","arrow","freedraw","frame"].includes(s.type))&&E("\u573A\u666F\u5305\u542B\u4E0D\u652F\u6301\u7684\u5143\u7D20"),t.push(s.id);for(let o of["x","y","width","height","angle","fontSize","strokeWidth"])s[o]!==void 0&&(typeof s[o]!="number"||!Number.isFinite(s[o])||Math.abs(s[o])>1e5)&&E("\u56FE\u5F62\u6570\u503C\u65E0\u6548");for(let o of["x","y","width","height"])typeof s[o]!="number"&&E("\u56FE\u5F62\u5C3A\u5BF8\u7F3A\u5931");(s.link||s.fileId||s.type==="embeddable"||s.type==="iframe")&&E("\u9996\u671F\u4E0D\u652F\u6301\u5916\u94FE\u6216\u5D4C\u5165\u8D44\u6E90"),s.text!==void 0&&(typeof s.text!="string"||s.text.length>2e3)&&E("\u56FE\u5F62\u6587\u6848\u8FC7\u957F"),(s.width<0||s.height<0||typeof s.fontSize=="number"&&(s.fontSize<1||s.fontSize>200))&&E("\u56FE\u5F62\u5C3A\u5BF8\u6216\u5B57\u53F7\u65E0\u6548"),s.groupIds!==void 0&&(!Array.isArray(s.groupIds)||s.groupIds.some(o=>typeof o!="string"||o.length>100))&&E("\u5143\u7D20\u5206\u7EC4\u65E0\u6548"),s.boundElements!=null&&(!Array.isArray(s.boundElements)||s.boundElements.some(o=>!R(o)||typeof o.id!="string"||!["arrow","text"].includes(String(o.type))))&&E("\u5143\u7D20\u7ED1\u5B9A\u65E0\u6548");for(let o of["startBinding","endBinding"])if(s[o]!=null){let c=s[o];(!R(c)||typeof c.elementId!="string"||["focus","gap"].some(l=>typeof c[l]!="number"||!Number.isFinite(c[l])))&&E("\u8FDE\u7EBF\u7ED1\u5B9A\u65E0\u6548")}s.containerId!=null&&typeof s.containerId!="string"&&E("\u6587\u672C\u7ED1\u5B9A\u65E0\u6548"),s.frameId!=null&&(typeof s.frameId!="string"||!e.some(o=>o.id===s.frameId&&o.type==="frame"))&&E("\u753B\u6846\u5F15\u7528\u65E0\u6548"),s.type==="frame"&&s.name!=null&&(typeof s.name!="string"||s.name.length>2e3)&&E("\u753B\u6846\u540D\u79F0\u65E0\u6548"),s.fontFamily!==void 0&&(typeof s.fontFamily!="number"||!Number.isInteger(s.fontFamily)||s.fontFamily<1||s.fontFamily>1e3)&&E("\u5B57\u4F53\u65E0\u6548");for(let o of["strokeColor","backgroundColor","fillStyle","strokeStyle"])s[o]!==void 0&&(typeof s[o]!="string"||s[o].length>100)&&E("\u56FE\u5F62\u6837\u5F0F\u65E0\u6548");s.points!==void 0&&(!Array.isArray(s.points)||s.points.length>2e3||s.points.some(o=>!Array.isArray(o)||o.length!==2||o.some(c=>typeof c!="number"||!Number.isFinite(c)||Math.abs(c)>1e5)))&&E("\u8DEF\u5F84\u5750\u6807\u65E0\u6548")}Ae(t);let i=R(r.appState)?r.appState:{},n=typeof i.viewBackgroundColor=="string"&&/^#[\da-f]{3,8}$/i.test(i.viewBackgroundColor)?i.viewBackgroundColor:"#ffffff";return{type:"excalidraw",version:2,source:"pi-webapp",elements:structuredClone(e),appState:{viewBackgroundColor:n},files:{}}}var ie=S.String({pattern:"^[\\w-]{1,80}$"}),Te=S.String({minLength:1,maxLength:500}),Nr=S.String({pattern:"^(#[a-fA-F0-9]{6}|#[a-fA-F0-9]{3}|transparent)$"}),Ft={strokeColor:S.Optional(Nr),backgroundColor:S.Optional(Nr),strokeStyle:S.Optional(S.Union([S.Literal("solid"),S.Literal("dashed"),S.Literal("dotted")])),fontSize:S.Optional(S.Number({minimum:12,maximum:96}))},Ar={x:S.Optional(S.Number({minimum:-1e5,maximum:1e5})),y:S.Optional(S.Number({minimum:-1e5,maximum:1e5})),width:S.Optional(S.Number({minimum:20,maximum:1e4})),height:S.Optional(S.Number({minimum:20,maximum:1e4}))},Tr=S.Object({id:ie,label:Te,kind:S.Optional(S.Union(["process","decision","terminal","text","group"].map(r=>S.Literal(r)))),...Ar,...Ft,groupId:S.Optional(ie)}),Rr=S.Object({id:ie,from:ie,to:ie,label:S.Optional(Te),...Ft,waypoints:S.Optional(S.Array(S.Tuple([S.Number({minimum:-1e5,maximum:1e5}),S.Number({minimum:-1e5,maximum:1e5})]),{maxItems:12}))}),ms=S.Object({nodes:S.Array(Tr,{minItems:1,maxItems:30}),edges:S.Array(Rr,{maxItems:60}),layout:S.Optional(S.Union([S.Literal("top-down"),S.Literal("left-right")]))}),hs=S.Object({addNodes:S.Optional(S.Array(Tr,{maxItems:30})),addEdges:S.Optional(S.Array(Rr,{maxItems:60})),updateNodes:S.Optional(S.Array(S.Object({id:ie,label:Te}),{maxItems:30})),updateElements:S.Optional(S.Array(S.Object({id:ie,label:S.Optional(Te),...Ar,...Ft}),{maxItems:60})),removeIds:S.Optional(S.Array(ie,{maxItems:60}))});function Dr(r){return[{name:"excalidraw_read_me",action:"reference",description:"Read the local Excalidraw element format and drawing examples before using excalidraw_create_view. Draw from the main conversation; never ask users to open a diagram app, fill a form, or accept a newly created diagram. No external service or account.",parameters:S.Object({})},{name:"excalidraw_create_view",action:"view",description:"Draw an editable Excalidraw view directly in the conversation. First read excalidraw_read_me. Put scene JSON only in tool arguments, never repeat it as assistant text/code blocks: the tool card already provides a collapsed parameter inspector. elements is a JSON array string of compact native shapes, text, lines and arrows with explicit positions, sizes, styles and bound labels. New views become editable automatically. To edit the active drawing, first call diagram_read (omit id for active view); prefer diagram_patch for targeted changes preserving manual edits. For a full replacement provide id and exact baseRevision; existing drawings require review in chat. Does not upload, write workspace files or export PNG.",parameters:S.Object({title:S.Optional(Te),elements:S.String({maxLength:512*1024}),id:S.Optional(ie),baseRevision:S.Optional(S.Integer({minimum:0}))})},{name:"diagram_reference",action:"reference",description:"Read the local Excalidraw composition format, layout guidance and a layered architecture example. Use before drawing a rich diagram. Does not access files or an external service.",parameters:S.Object({})},{name:"diagram_create",action:"create",description:"Create an editable Excalidraw diagram displayed directly in chat. Put graph JSON only in tool arguments, not in assistant text/code blocks; the card has a parameter inspector. Use for natural-language drawing requests; users need not name tools. For architecture/knowledge diagrams read diagram_reference first: nodes support text/group kinds, explicit coordinates, width/height, colors and fontSize; edges support dashed strokes and absolute waypoints. Compose layers and annotations, not just identical boxes. Unique stable ASCII IDs; Chinese labels supported. New drawings are automatically materialized in the conversation and can be edited directly; do not ask users to accept a new drawing. Prefer excalidraw_create_view for free-form compositions. This does not save a file or render PNG.",parameters:S.Object({title:Te,graph:ms})},{name:"diagram_read",action:"read",description:"Read the latest synchronized diagram revision and compact native elements by ID. Always read before patching. Bound text uses containerId; shape IDs identify nodes. User manual edits are authoritative. Omit id to read the current active drawing in this session. Only this session's drawings are read. Read after user edits before generating a patch.",parameters:S.Object({id:S.Optional(ie),elementIds:S.Optional(S.Array(ie,{maxItems:100}))})},{name:"diagram_patch",action:"patch",description:"Propose local edits to an existing diagram after diagram_read. Supply its exact baseRevision. addNodes/addEdges, updateNodes (shape ID + label), updateElements (shape or unbound text ID + optional label, x/y, width/height, colors, fontSize, strokeStyle), removeIds (native IDs). Geometry updates reroute incident bound arrows; unrelated native elements retain their positions and text. Do not rearrange everything unless requested. Never claim the proposal was accepted or saved.",parameters:S.Object({id:ie,baseRevision:S.Integer({minimum:0}),patch:hs})}].map(({name:e,action:t,description:i,parameters:n})=>({name:e,label:e,description:i,parameters:n,async execute(s,o,c,l,p){c?.throwIfAborted();let u=await r(it,p.cwd,p.sessionManager.getSessionId(),t,o);return{content:[{type:"text",text:JSON.stringify(u)}],details:u}}}))}var Mr={id:it,kind:"builtin",version:"1.0.0",name:{zh:"\u624B\u7ED8\u56FE",en:"Diagrams"},description:{zh:"Agent \u751F\u6210\u6D41\u7A0B\u4E0E\u67B6\u6784\u56FE\uFF0C\u4F7F\u7528 Excalidraw \u7F16\u8F91\u3001\u672C\u5730\u4FDD\u5B58\u548C\u5BFC\u51FA\u3002",en:"Generate flowcharts with the agent, edit in Excalidraw, save locally and export."}};import{constants as zt}from"node:fs";import{lstat as Cs,mkdir as _s,open as Jt,readdir as Ns,rename as As,unlink as Vt}from"node:fs/promises";import{createHash as Ts,randomUUID as Rs}from"node:crypto";import{join as ve}from"node:path";import{setTimeout as Ds}from"node:timers/promises";import{getAgentDir as Ms}from"@earendil-works/pi-coding-agent";import{randomUUID as ct}from"node:crypto";import{basename as Is}from"node:path";import{constants as Bt}from"node:fs";import{link as ws,lstat as Or,mkdir as ys,open as $t,realpath as Wr,rename as bs,unlink as jt}from"node:fs/promises";import{dirname as ks,isAbsolute as Br,join as jr,relative as Lt,resolve as vs,sep as $r,win32 as Es}from"node:path";import{createHash as xs,randomUUID as Ss}from"node:crypto";var at=r=>xs("sha256").update(r).digest("hex");function Fr(r,e){let t=Lt(r,e);return t!==".."&&!t.startsWith(`..${$r}`)&&!Br(t)}async function Gt(r,e,t=!1){if(typeof e!="string"||e.length>4096||!e.endsWith(".excalidraw")||e.includes("\\")||e.includes("\0")||Br(e)||Es.isAbsolute(e))throw new A("\u8BF7\u4F7F\u7528\u5DE5\u4F5C\u533A\u5185\u7684 .excalidraw \u76F8\u5BF9\u8DEF\u5F84");let i=await Wr(r),n=vs(i,e);if(!Fr(i,n)||n===i)throw new A("\u56FE\u7A3F\u8DEF\u5F84\u8D8A\u754C",403);let s=Lt(i,n).split($r),o=i;for(let l=0;l<s.length;l++){o=jr(o,s[l]);let p;try{p=await Or(o)}catch(u){if(u.code!=="ENOENT")throw u;if(l<s.length-1){if(!t||Lt(i,o)!=="diagrams")throw new A("\u4FDD\u5B58\u76EE\u5F55\u4E0D\u5B58\u5728",404);try{await ys(o,{mode:448})}catch(h){if(h.code!=="EEXIST")throw h}p=await Or(o)}}if(p?.isSymbolicLink())throw new A("\u56FE\u7A3F\u8DEF\u5F84\u4E0D\u80FD\u5305\u542B\u7B26\u53F7\u94FE\u63A5",403);if(p&&(l<s.length-1?!p.isDirectory():!p.isFile()))throw new A("\u56FE\u7A3F\u8DEF\u5F84\u4E0D\u662F\u666E\u901A\u6587\u4EF6")}let c=await Wr(ks(n));if(!Fr(i,c))throw new A("\u56FE\u7A3F\u8DEF\u5F84\u8D8A\u754C",403);return{target:n,parent:c}}async function Ut(r){let e;try{e=await $t(r,Bt.O_RDONLY|Bt.O_NONBLOCK|(Bt.O_NOFOLLOW??0))}catch(t){if(t.code==="ENOENT")return null;throw t}try{let t=await e.stat();if(!t.isFile()||t.size>524288)throw new A("\u4E0D\u662F\u666E\u901A\u6587\u4EF6\u6216\u56FE\u7A3F\u8D85\u8FC7 512 KiB");let i=Buffer.alloc(524289),n=0;for(;n<i.length;){let{bytesRead:s}=await e.read(i,n,i.length-n,n);if(!s)break;n+=s}if(n>524288)throw new A("\u56FE\u7A3F\u8D85\u8FC7 512 KiB");return i.subarray(0,n)}finally{await e.close()}}function Lr(r){if(r instanceof A)throw r;let e=r.code;throw["EACCES","EPERM","ELOOP"].includes(e??"")?new A("\u56FE\u7A3F\u4E0D\u53EF\u8BBF\u95EE\u6216\u5305\u542B\u7B26\u53F7\u94FE\u63A5",403):["ENOENT","ENOTDIR"].includes(e??"")?new A("\u56FE\u7A3F\u76EE\u5F55\u4E0D\u5B58\u5728",404):e==="EEXIST"?new A("\u56FE\u7A3F\u6B63\u5728\u4FDD\u5B58\uFF1B\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF08\u4E0D\u8981\u5220\u9664\u6D3B\u8DC3\u7684\u9501\u6587\u4EF6\uFF09",409):r}async function Gr(r,e){try{let{target:t}=await Gt(r,e),i=await Ut(t);if(!i)throw new A("\u56FE\u7A3F\u4E0D\u5B58\u5728",404);let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new A("\u56FE\u7A3F\u4E0D\u662F\u6709\u6548\u7684 UTF-8 JSON")}return{scene:ce(n),hash:at(i)}}catch(t){return Lr(t)}}async function Ur(r,e,t,i,n=()=>{}){let s=JSON.stringify(ce(t)),o,c,l;try{let{target:p,parent:u}=await Gt(r,e,!0);c=`${p}.lock`,o=await $t(c,"wx",384),await o.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));let h=await Ut(p);if((h?at(h):null)!==i)throw new A("\u6587\u4EF6\u5DF2\u5B58\u5728\u6216\u88AB\u5916\u90E8\u4FEE\u6539\uFF1B\u8BF7\u91CD\u65B0\u6253\u5F00\u6216\u53E6\u5B58\uFF0C\u672A\u8986\u76D6\u539F\u6587\u4EF6",409);l=jr(u,`.diagram-${Ss()}.tmp`);let d=await $t(l,"wx",384);try{await d.writeFile(s),await d.sync()}finally{await d.close()}if((await Gt(r,e)).parent!==u)throw new A("\u4FDD\u5B58\u76EE\u5F55\u53D1\u751F\u53D8\u5316",409);let m=await Ut(p);if((m?at(m):null)!==i)throw new A("\u4FDD\u5B58\u671F\u95F4\u6587\u4EF6\u53D1\u751F\u53D8\u5316\uFF1B\u672A\u8986\u76D6",409);if(n(),i===null){try{await ws(l,p)}catch(y){throw y.code==="EEXIST"?new A("\u76EE\u6807\u6587\u4EF6\u5DF2\u5B58\u5728\uFF1B\u8BF7\u53E6\u5B58",409):y}await jt(l),l=void 0}else await bs(l,p),l=void 0;return at(s)}catch(p){return Lr(p)}finally{l&&await jt(l).catch(()=>{}),o&&(await o.close(),await jt(c).catch(()=>{}))}}var Ps={nodes:[{id:"title",kind:"text",label:"Pi \u67B6\u6784\u603B\u89C8",x:330,y:0,width:600,height:60,fontSize:36},{id:"entry",kind:"group",label:"\u2460 \u5165\u53E3 / \u6A21\u5F0F\u5206\u53D1",x:0,y:100,width:1280,height:180,backgroundColor:"#eff6ff",strokeColor:"#93c5fd"},{id:"core",kind:"group",label:"\u2461 \u5E94\u7528\u6838\u5FC3",x:0,y:310,width:1280,height:210,backgroundColor:"#f5f3ff",strokeColor:"#c4b5fd"},{id:"runtime",kind:"group",label:"\u2462 \u8FD0\u884C\u65F6\u5E93",x:0,y:550,width:1280,height:200,backgroundColor:"#f0fdf4",strokeColor:"#86efac"},{id:"infra",kind:"group",label:"\u2463 \u57FA\u7840\u8BBE\u65BD",x:0,y:1e3,width:1280,height:150,backgroundColor:"#fff7ed",strokeColor:"#fdba74"},{id:"cli",label:"pi CLI \xB7 main.ts",x:110,y:160,width:360,height:80,groupId:"entry",strokeColor:"#3b82f6",backgroundColor:"#bfdbfe"},{id:"modes",label:"interactive \xB7 print \xB7 rpc",x:730,y:160,width:440,height:80,groupId:"entry",strokeColor:"#3b82f6",backgroundColor:"#bfdbfe"},{id:"session",label:"AgentSession \u6838\u5FC3",x:100,y:375,width:450,height:90,groupId:"core",strokeColor:"#8b5cf6",backgroundColor:"#ddd6fe",fontSize:26},{id:"manager",label:"SessionManager \xB7 JSONL",x:790,y:375,width:380,height:90,groupId:"core",strokeColor:"#22c55e",backgroundColor:"#bbf7d0"},{id:"tools",kind:"text",label:"\u5185\u7F6E\u5DE5\u5177\uFF1Abash \xB7 fs \xB7 edit \xB7 grep",x:110,y:475,width:500,height:30,groupId:"core",fontSize:16,strokeColor:"#64748b"},{id:"agent",label:"agent-core",x:40,y:610,width:200,height:80,groupId:"runtime",backgroundColor:"#ddd6fe",strokeColor:"#8b5cf6"},{id:"ai",label:"pi-ai",x:300,y:610,width:190,height:80,groupId:"runtime",backgroundColor:"#bfdbfe",strokeColor:"#3b82f6"},{id:"tui",label:"pi-tui",x:550,y:610,width:190,height:80,groupId:"runtime",backgroundColor:"#fef3c7",strokeColor:"#f59e0b"},{id:"code",label:"codemode",x:800,y:610,width:190,height:80,groupId:"runtime",backgroundColor:"#fed7aa",strokeColor:"#f97316"},{id:"mcp",label:"pi-mcp",x:1050,y:610,width:190,height:80,groupId:"runtime",backgroundColor:"#bbf7d0",strokeColor:"#22c55e"},{id:"fs",label:"\u6587\u4EF6\u7CFB\u7EDF \xB7 \u8FDB\u7A0B",x:30,y:820,width:230,height:80,strokeStyle:"dashed",backgroundColor:"#f8fafc",strokeColor:"#94a3b8"},{id:"providers",label:"Provider APIs",x:300,y:820,width:240,height:80,strokeStyle:"dashed",backgroundColor:"#f8fafc",strokeColor:"#94a3b8"},{id:"servers",label:"MCP servers",x:1030,y:820,width:230,height:80,strokeStyle:"dashed",backgroundColor:"#f8fafc",strokeColor:"#94a3b8"},{id:"infra-text",kind:"text",label:"chord \xB7 durable \xB7 protocol / server / client \xB7 env \xB7 telemetry",x:80,y:1070,width:1140,height:40,groupId:"infra",strokeColor:"#b45309"},{id:"experiment",label:"\u5B9E\u9A8C\uFF08\u975E\u9ED8\u8BA4\u88C5\u914D\uFF09\uFF1Aexperimental server / client",x:520,y:1230,width:740,height:80,strokeStyle:"dashed",strokeColor:"#f59e0b",backgroundColor:"#fef3c7"}],edges:[{id:"dispatch",from:"cli",to:"modes",waypoints:[[620,200]]},{id:"shared",from:"modes",to:"session"},{id:"persist",from:"session",to:"manager",label:"\u4E8B\u4EF6 \u2192 \u6301\u4E45\u5316",strokeColor:"#22c55e"},{id:"loop",from:"session",to:"agent"},{id:"stream",from:"agent",to:"ai"},{id:"filesystem",from:"agent",to:"fs",strokeColor:"#8b5cf6"},{id:"provider",from:"ai",to:"providers",strokeColor:"#3b82f6"},{id:"mcp-api",from:"mcp",to:"servers",strokeColor:"#22c55e"},{id:"dependency",from:"tui",to:"infra",strokeStyle:"dashed",strokeColor:"#94a3b8",label:"npm workspace \u4F9D\u8D56"},{id:"experimental",from:"infra",to:"experiment",strokeStyle:"dashed",strokeColor:"#f59e0b"}]},zr={elementsGuide:'Preferred drawing workflow: user speaks in the main chat \u2192 excalidraw_read_me \u2192 excalidraw_create_view({title, elements: JSON.stringify([...])}) \u2192 diagram is displayed in this tool result \u2192 Edit opens only the native Excalidraw editor. No second prompt form, no initial acceptance step. This is a local native adapter, not a remote MCP service. elements: 1\u2013150 objects; types rectangle/ellipse/diamond/text/line/arrow. Each needs stable ASCII id and x/y. Shapes need width/height (20\u201310000); text needs text and preferably fontSize (16\u201336). Use label:{text,fontSize:20} for centered bound labels; optional textAlign and verticalAlign. Use separate text for headings. Safe colors #RRGGBB or transparent, fillStyle solid/hachure/cross-hatch/zigzag, strokeStyle solid/dashed/dotted, roundness:{type:3}, roughness:1, opacity:0\u2013100, groupIds:[string] (up to 10 IDs; each 1\u2013100 Unicode letters/digits, underscores or hyphens; e.g. ["core-layer_2", "\u6838\u5FC3\u5C42"]). Arrows/lines need points:[[0,0],[dx,dy],\u2026] relative to x/y; bind with start:{id:shapeId}, end:{id:shapeId}; endArrowhead:arrow/bar/dot/triangle/null. No URLs, images, embeds, scripts or pseudo-elements. Put background zones first, then shapes, labels and purposeful arrows. Explicitly position generous 20\u201340px gaps; use pastel #a5d8ff/#d0bfff/#b2f2bb/#ffd8a8 and dark readable text. Chinese fonts are local. Tool arguments may render progressively; final rendering is authoritative. To change the current drawing: diagram_read({}) gets latest selected drawing and revision including hand edits, then diagram_patch for targeted changes; user confirms existing edits in chat. Full replacement via excalidraw_create_view with id/baseRevision also requires chat confirmation. Never rebuild unrelated manual content. Save/export are native menu actions; do not claim files or PNG exist before that.',elementsExample:{title:"\u767B\u5F55\u6D41\u7A0B",elements:JSON.stringify([{type:"rectangle",id:"input",x:40,y:80,width:220,height:100,backgroundColor:"#a5d8ff",label:{text:"\u8F93\u5165\u9A8C\u8BC1\u7801",fontSize:20}},{type:"diamond",id:"check",x:400,y:60,width:220,height:140,backgroundColor:"#fff3bf",label:{text:"\u9A8C\u8BC1\u901A\u8FC7\uFF1F",fontSize:20}},{type:"arrow",id:"verify",x:260,y:130,points:[[0,0],[140,0]],start:{id:"input"},end:{id:"check"},endArrowhead:"arrow"}])},guide:"Legacy graph shortcut: Draw locally; no Excalidraw account or external service is needed. Use diagram_create with title and graph. For simple flows omit coordinates and use top-down/left-right. For rich architecture use explicit x/y/width/height for ALL nodes, generous spacing and few purposeful arrows. nodes: process (rectangle), decision (diamond), terminal (ellipse), text (standalone title/annotation), group (background container, label top-left). Put background containers first; groupId on children associates native selection groups, not hierarchical layout. A group must exist and cannot nest. Supported styles: strokeColor/backgroundColor (#RGB/#RRGGBB/transparent), strokeStyle (solid/dashed/dotted), fontSize 12\u201396. Edges: id/from/to/optional label, strokeColor/strokeStyle/fontSize; optional waypoints are ABSOLUTE intermediate [x,y] coordinates, endpoints stay bound. No arrows to standalone text. Up to 30 nodes, 60 edges, 12 waypoints per edge. Leave room under a group's heading and around notes. Use separate text nodes for subtitles; do not connect every library in a false sequential chain. Chinese is supported by bundled fonts. A new drawing appears directly in chat and becomes editable automatically. Changes to existing drawings require review in chat; saving is separate. For edits call diagram_read first; use updateElements for geometry/styles or standalone text, updateNodes for bound labels, addNodes/addEdges/removeIds for structure. Do not target a bound text ID; target its container. Moving a shape reroutes its incident bound arrows; untouched paths and elements remain. Do not claim a candidate was accepted or a file saved.",example:{title:"Pi \u5206\u5C42\u67B6\u6784\uFF08\u6784\u56FE\u793A\u4F8B\uFF0C\u4E0D\u662F\u6E90\u7801\u5BA1\u8BA1\uFF09",graph:Ps}};var Ue=class{scopes=new Map;saving=new Set;focused=new Map;checkpoint(e,t){return structuredClone({drafts:[...this.scope(e,t).values()],focused:this.focused.get(this.scopeKey(e,t))??null})}restoreCheckpoint(e,t,i){this.scopes.set(this.scopeKey(e,t),new Map(i.drafts.map(n=>[n.id,n]))),i.focused&&this.focused.set(this.scopeKey(e,t),i.focused)}scopeKey(e,t){return JSON.stringify([e,t])}scope(e,t){let i=JSON.stringify([e,t]),n=this.scopes.get(i);return n||(n=new Map,this.scopes.set(i,n)),n}draft(e,t,i){let n=this.scope(e,t).get(j(i));if(!n)throw new A("\u56FE\u7A3F\u4E0D\u5C5E\u4E8E\u5F53\u524D\u4F1A\u8BDD\u6216\u670D\u52A1\u5DF2\u91CD\u542F\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u5DF2\u4FDD\u5B58\u6587\u4EF6",404,"diagram_unavailable");return n}expected(e,t){if(t!==e.revision||this.saving.has(e.id))throw new A("\u56FE\u7A3F\u4FEE\u8BA2\u5DF2\u53D8\u5316\u6216\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\uFF1B\u672C\u5730\u8349\u7A3F\u4ECD\u53EF\u4E0B\u8F7D",409)}list(e,t){return[...this.scope(e,t).values()].map(i=>({id:i.id,title:i.title,revision:i.revision,path:i.path,savedRevision:i.savedRevision,pending:!!i.candidate}))}add(e,t,i){let n=this.scope(e,t);if(n.size>=100)throw new A("\u5F53\u524D\u4F1A\u8BDD\u56FE\u7A3F\u5DF2\u8FBE 100 \u4EFD\u4E0A\u9650");let s={id:ct(),title:i,revision:0,scene:_r(),path:null,diskHash:null,savedRevision:null,candidate:null};return n.set(s.id,s),this.focused.set(this.scopeKey(e,t),s.id),s}tool(e,t,i,n){if(!R(n))throw new A("\u7ED8\u56FE\u5DE5\u5177\u8F93\u5165\u65E0\u6548");if(i==="reference")return structuredClone(zr);if(i==="create"){let c=nt(n.graph),l=re(n.title),p=this.add(e,t,l);return p.candidate={id:ct(),baseRevision:p.revision,graph:c},{id:p.id,title:l,revision:p.revision,status:"pending_canvas_acceptance",message:"\u7ED3\u6784\u5DF2\u5EFA\u7ACB\uFF0C\u56FE\u7A3F\u5C06\u5728\u5BF9\u8BDD\u4E2D\u81EA\u52A8\u5448\u73B0\u5E76\u53EF\u76F4\u63A5\u7F16\u8F91\uFF0C\u65E0\u9700\u7528\u6237\u63A5\u53D7\u9996\u6B21\u521B\u5EFA\u3002\u5C1A\u672A\u4FDD\u5B58\u6587\u4EF6\u6216\u751F\u6210 PNG\u3002"}}if(i==="view"){let c=ot(n.elements),l=n.title===void 0?"Excalidraw":re(n.title),p=n.id===void 0?this.add(e,t,l):this.draft(e,t,n.id);if(n.id!==void 0&&(this.expected(p,n.baseRevision),p.candidate))throw new A("\u8BF7\u5148\u5728\u5BF9\u8BDD\u4E2D\u5904\u7406\u5DF2\u6709\u4FEE\u6539",409);return p.candidate={id:ct(),baseRevision:p.revision,elements:c},{id:p.id,title:p.title,revision:p.revision,status:n.id===void 0?"pending_canvas":"pending_review",message:n.id===void 0?"\u56FE\u7A3F\u5C06\u5728\u5BF9\u8BDD\u4E2D\u81EA\u52A8\u5448\u73B0\u5E76\u53EF\u76F4\u63A5\u7F16\u8F91\uFF0C\u65E0\u9700\u7528\u6237\u63A5\u53D7\u9996\u6B21\u521B\u5EFA\u3002\u5C1A\u672A\u5199\u5165\u5DE5\u4F5C\u533A\u6216\u5BFC\u51FA\u56FE\u7247\u3002":"\u4FEE\u6539\u5DF2\u5728\u5BF9\u8BDD\u4E2D\u9884\u89C8\uFF0C\u4FDD\u7559\u539F\u56FE\uFF0C\u7B49\u5F85\u7528\u6237\u786E\u8BA4\u3002"}}let s=this.draft(e,t,n.id??(i==="read"?this.focused.get(this.scopeKey(e,t)):void 0));if(i==="read"){let c=n.elementIds===void 0?null:Array.isArray(n.elementIds)&&n.elementIds.length<=100?new Set(n.elementIds.map(j)):(()=>{throw new A("\u5143\u7D20\u8BFB\u53D6\u8303\u56F4\u65E0\u6548")})(),l=s.scene.elements.filter(u=>!u.isDeleted),p=c?l.filter(u=>c.has(u.id)||u.containerId&&c.has(u.containerId)):l.slice(0,100);return{totalElements:l.length,truncated:!c&&l.length>p.length,id:s.id,title:s.title,revision:s.revision,saved:s.revision===s.savedRevision,pending:!!s.candidate,elements:p.map(u=>({id:u.id,type:u.type,x:u.x,y:u.y,width:u.width,height:u.height,...u.text===void 0?{}:{text:u.text},...u.containerId?{containerId:u.containerId}:{},...u.startBinding?{startBinding:u.startBinding}:{},...u.endBinding?{endBinding:u.endBinding}:{},...Object.fromEntries(["strokeColor","backgroundColor","strokeStyle","fontSize","groupIds","customData"].filter(h=>u[h]!==void 0).map(h=>[h,u[h]]))}))}}if(i!=="patch")throw new A("\u672A\u77E5\u7ED8\u56FE\u5DE5\u5177");if(this.expected(s,n.baseRevision),s.candidate)throw new A("\u8BF7\u5148\u5728\u5BF9\u8BDD\u4E2D\u5E94\u7528\u5DF2\u6709\u4FEE\u6539\u6216\u4FDD\u7559\u539F\u56FE",409);let o=st(n.patch,s.scene);return s.candidate={id:ct(),baseRevision:s.revision,patch:o},{id:s.id,title:s.title,revision:s.revision,status:"pending_canvas_acceptance",message:"\u4FEE\u6539\u5DF2\u5728\u5BF9\u8BDD\u5DE5\u5177\u7ED3\u679C\u4E2D\u9884\u89C8\uFF0C\u539F\u56FE\u672A\u88AB\u66FF\u6362\uFF1B\u8BF7\u7528\u6237\u5728\u5BF9\u8BDD\u4E2D\u5E94\u7528\u4FEE\u6539\u6216\u4FDD\u7559\u539F\u56FE\u3002\u53F3\u4FA7\u4ECD\u53EF\u624B\u52A8\u7F16\u8F91\u539F\u56FE\u3002"}}async action(e,t,i,n,s){if(s(),i==="list")return this.list(e,t);if(i==="new")return structuredClone(this.add(e,t,"\u672A\u547D\u540D\u56FE\u7A3F"));if(i==="open"){let c=await Gr(e,n.path);s();let l=[...this.scope(e,t).values()].find(u=>u.path===n.path);if(l&&l.revision!==l.savedRevision)throw new A("\u6B64\u6587\u4EF6\u5DF2\u6709\u672A\u4FDD\u5B58\u8349\u7A3F\uFF0C\u8BF7\u5148\u4FDD\u5B58\u6216\u53E6\u5B58",409);let p=this.add(e,t,Is(n.path,".excalidraw"));return p.scene=c.scene,p.path=n.path,p.diskHash=c.hash,p.savedRevision=0,structuredClone(p)}if(i==="import"){let c=ce(n.scene),l=this.add(e,t,typeof n.title=="string"?re(n.title):"\u5BFC\u5165\u56FE\u7A3F");return l.scene=c,structuredClone(l)}let o=this.draft(e,t,n.id);if(i==="get")return structuredClone(o);if(i==="focus")return this.focused.set(this.scopeKey(e,t),o.id),{id:o.id};if(this.expected(o,n.revision),i==="sync")return o.scene=ce(n.scene),o.revision++,structuredClone(o);if(i==="initialize"||i==="accept"||i==="reject"){let c=o.candidate;if(!c||c.id!==n.candidateId)throw new A("\u5019\u9009\u5DF2\u53D8\u5316",409);if(i==="initialize"&&(o.revision!==0||o.scene.elements.length||c.patch))throw new A("\u53EA\u80FD\u81EA\u52A8\u5448\u73B0\u5C1A\u672A\u7F16\u8F91\u7684\u65B0\u56FE\u7A3F",409);if(i==="accept"||i==="initialize"){if(c.baseRevision!==o.revision)throw new A("\u5019\u9009\u57FA\u4E8E\u65E7\u56FE\u7A3F\uFF0C\u4E0D\u80FD\u8986\u76D6\u6700\u65B0\u624B\u6539\uFF1B\u8BF7\u62D2\u7EDD\u540E\u91CD\u65B0\u751F\u6210",409);o.scene=ce(n.scene),o.revision++}return o.candidate=null,structuredClone(o)}if(i==="save"){if(o.candidate)throw new A("\u8BF7\u5148\u63A5\u53D7\u6216\u62D2\u7EDD\u4FEE\u6539\u5019\u9009");let c=o.revision,l=n.path===o.path?o.diskHash:null;this.saving.add(o.id);try{let p=await Ur(e,n.path,o.scene,l,()=>{if(s(),o.revision!==c)throw new A("\u4FDD\u5B58\u671F\u95F4\u56FE\u7A3F\u5DF2\u4FEE\u6539",409)});return o.path=n.path,o.diskHash=p,o.savedRevision=c,structuredClone(o)}finally{this.saving.delete(o.id)}}throw new A("\u672A\u77E5\u56FE\u7A3F\u64CD\u4F5C")}};var Os=r=>r.code==="ENOENT",Ws=r=>Ts("sha256").update(r).digest("hex"),qr=3*524288;async function Vr(r,e=qr){let t;try{t=await Jt(r,zt.O_RDONLY|zt.O_NONBLOCK|(zt.O_NOFOLLOW??0))}catch(i){if(Os(i))return null;throw i}try{let i=await t.stat();if(!i.isFile()||i.size>e)throw new Error("Invalid diagram checkpoint size or type");let n=Buffer.alloc(e+1),s=0;for(;s<n.length;){let{bytesRead:o}=await t.read(n,s,n.length-s,s);if(!o)break;s+=o}if(s>e)throw new Error("Oversized diagram checkpoint");return new TextDecoder("utf-8",{fatal:!0}).decode(n.subarray(0,s))}finally{await t.close()}}async function Jr(r){await _s(r,{recursive:!0,mode:448});let e=await Cs(r);if(!e.isDirectory()||e.isSymbolicLink())throw new Error("Diagram storage must be a real directory")}async function Hr(r,e){let t=`${r}.${Rs()}.tmp`,i=await Jt(t,"wx",384);try{try{await i.writeFile(e),await i.sync()}finally{await i.close()}await As(t,r)}finally{await Vt(t).catch(()=>{})}}function Fs(r){if(!R(r))throw new Error("Invalid checkpoint");let e=j(r.id),t=re(r.title),i=ce(r.scene);if(!Number.isSafeInteger(r.revision)||r.revision<0||!(r.savedRevision===null||Number.isSafeInteger(r.savedRevision)&&r.savedRevision>=0&&r.savedRevision<=r.revision)||!(r.path===null||typeof r.path=="string"&&r.path.length<=4096)||!(r.diskHash===null||typeof r.diskHash=="string"&&/^[a-f0-9]{64}$/.test(r.diskHash)))throw new Error("Invalid checkpoint metadata");let n={id:e,title:t,scene:i,revision:r.revision,savedRevision:r.savedRevision,path:r.path,diskHash:r.diskHash,candidate:null};if(r.candidate!==null){let s=r.candidate;if(!R(s)||!Number.isSafeInteger(s.baseRevision)||s.baseRevision<0||s.baseRevision>n.revision||[s.elements,s.graph,s.patch].filter(o=>o!==void 0).length!==1)throw new Error("Invalid checkpoint candidate");n.candidate={id:j(s.id),baseRevision:s.baseRevision,...s.elements===void 0?{}:{elements:ot(s.elements)},...s.graph===void 0?{}:{graph:nt(s.graph)},...s.patch===void 0?{}:{patch:s.baseRevision===n.revision?st(s.patch,i):R(s.patch)?structuredClone(s.patch):(()=>{throw new Error("Invalid checkpoint patch")})()}}}return n}var lt=class{root;constructor(e=ve(Ms(),"pi-web","diagrams")){this.root=e}async lock(e){let t=ve(e,"scope.lock");for(let i=0;i<100;i++)try{let n=await Jt(t,"wx",384);try{await n.writeFile(JSON.stringify({pid:process.pid}))}catch(s){throw await n.close(),await Vt(t),s}return async()=>{await n.close(),await Vt(t)}}catch(n){if(n.code!=="EEXIST")throw n;await Ds(20)}throw new A("\u56FE\u7A3F\u5B58\u50A8\u6B63\u5FD9\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF1B\u672A\u8986\u76D6\u56FE\u7A3F",409)}async run(e,t,i){let n,s=!1;try{await Jr(this.root);let o=ve(this.root,Ws(JSON.stringify([e,t])));await Jr(o),n=await this.lock(o);let c=(await Ns(o)).filter(y=>/^[\w-]{1,80}\.json$/.test(y)&&y!=="focus.json");if(c.length>100)throw new Error("Too many diagram checkpoints");let l=[],p=new Map;for(let y of c){let N=await Vr(ve(o,y));if(!N)throw new Error("Missing diagram checkpoint");let P=JSON.parse(N);if(!R(P)||P.version!==1||P.cwd!==e||P.sessionId!==t)throw new Error("Checkpoint scope mismatch");let W=Fs(P.draft);if(y!==`${W.id}.json`)throw new Error("Checkpoint ID mismatch");l.push(W),p.set(W.id,JSON.stringify(W))}let u=await Vr(ve(o,"focus.json"),1024),h=u?JSON.parse(u):null,d=new Ue;d.restoreCheckpoint(e,t,{drafts:l,focused:typeof h=="string"&&l.some(y=>y.id===h)?h:null}),s=!0;let g=await i(d),m=d.checkpoint(e,t);s=!1;for(let y of m.drafts)if(JSON.stringify(y)!==p.get(y.id)){let P=JSON.stringify({version:1,cwd:e,sessionId:t,draft:y});if(Buffer.byteLength(P)>qr)throw new Error("Oversized diagram checkpoint");await Hr(ve(o,`${j(y.id)}.json`),P)}return m.focused!==h&&await Hr(ve(o,"focus.json"),JSON.stringify(m.focused)),g}catch(o){throw o instanceof A&&(s||o.status===409)?o:new A("\u56FE\u7A3F\u672C\u5730\u5B58\u50A8\u8BFB\u53D6\u6216\u5199\u5165\u5931\u8D25\uFF1B\u539F\u6570\u636E\u672A\u88AB\u81EA\u52A8\u6E05\u7A7A\uFF0C\u8BF7\u4FDD\u7559\u8349\u7A3F\u540E\u91CD\u8BD5",500,"diagram_storage_error")}finally{await n?.()}}tool(e,t,i,n){return i==="reference"?Promise.resolve(new Ue().tool(e,t,i,n)):this.run(e,t,s=>s.tool(e,t,i,n))}action(e,t,i,n,s){return this.run(e,t,async o=>{s();let c=await o.action(e,t,i,n,s);return s(),c})}};var Bs=["list","new","get","open","import","sync","focus","initialize","accept","reject","save"];function Kr(){let r=new lt;return{metadata:Mr,routes:Bs.map(e=>`/api/diagrams/${e}`),agentAction:(e,t,i,n)=>r.tool(e,t,i,n),async handle({path:e,body:t,snapshot:i,json:n}){let s=i(),o=()=>{let c=i();if(t.sessionId!==s.sessionId||c.sessionId!==s.sessionId||c.cwd!==s.cwd)throw new A("\u4F1A\u8BDD\u5DF2\u5207\u6362",409)};try{let c=await r.action(s.cwd,s.sessionId,e.split("/").at(-1),t,o);n(200,c)}catch(c){if(c instanceof A)n(c.status,{error:c.message,errorCode:"validation_error",...c.reason?{reason:c.reason}:{}});else throw c}}}}import{isAbsolute as wo,relative as yo}from"node:path";var Re={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var Xr={id:Re.git,kind:"builtin",version:"1.0.0",name:{zh:"Git",en:"Git"},description:{zh:"\u5BA1\u9605\u5DE5\u4F5C\u533A\u6539\u52A8\u4E0E\u63D0\u4EA4\u5386\u53F2\uFF0C\u6682\u5B58\u6587\u4EF6\u3001\u63D0\u4EA4\u5E76\u7BA1\u7406\u672C\u5730\u5206\u652F\u3002",en:"Review workspace changes and history, stage files, commit and manage local branches."}};import{execFile as js}from"node:child_process";import{realpath as $s}from"node:fs/promises";import{isAbsolute as Yr,relative as Ls,sep as Gs,win32 as Us}from"node:path";var _=class extends Error{status;reason;constructor(e,t=400,i="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=i}};function D(r,e,t=2*1024*1024,i={}){let n=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_")));return new Promise((s,o)=>{let c,l=js("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:r,env:{...n,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:i.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(p,u,h)=>{if(!p){if(c){o(new _("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,i.write?"outcome_unknown":"git_failed"));return}s(u);return}if(i.write){let g=p.killed||p.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(h)?"index_locked":/already exists/i.test(h)?"branch_exists":/already checked out|used by worktree/i.test(h)?"branch_in_use":/would be overwritten|local changes/i.test(h)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(h)?"identity_missing":"git_failed";o(new _("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",g==="outcome_unknown"?503:409,g));return}let d=p.code;d==="ENOENT"?o(new _("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):d==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new _("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(h)?o(new _("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new _(p.killed?"Git \u8BFB\u53D6\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5":"Git \u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u548C\u76EE\u5F55\u6743\u9650",503))});l.stdin?.on("error",p=>{c=p}),i.input!==void 0&&l.stdin?.end(i.input)})}async function le(r){let e=await $s(r),t;try{t=(await D(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(n){if(n instanceof _&&n.status===404)return{kind:"not-repository"};if(n instanceof _&&n.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw n}let i=Ls(t,e).split(Gs).join("/");if(i===".."||i.startsWith("../")||Yr(i))throw new _("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:i?`${i}/`:""}}function Ee(r){if(typeof r!="string"||!r||r.length>4096||r.includes("\0")||r.includes("\\")||Yr(r)||Us.isAbsolute(r)||r.split("/").some(e=>!e||e==="."||e===".."))throw new _("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as no}from"node:crypto";import{lstat as Xt,realpath as di}from"node:fs/promises";import{dirname as li,isAbsolute as so,relative as oo,resolve as Ve}from"node:path";import{lstat as to}from"node:fs/promises";import{resolve as ro}from"node:path";import{constants as Ht}from"node:fs";import{open as zs,opendir as Vs,realpath as Qr,stat as ti}from"node:fs/promises";import{isAbsolute as ri,relative as Js,resolve as Hs,sep as qs,win32 as Ks}from"node:path";var Xs=1e3,Ys=512*1024,Qs=8*1024*1024,Zr=1e4,Zs=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),$=class extends Error{status;constructor(e,t=400){super(e),this.name="WorkspaceFileError",this.status=t}};function ei(r,e){let t=Js(r,e);return t!==".."&&!t.startsWith(`..${qs}`)&&!ri(t)}async function qt(r,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||ri(e)||Ks.isAbsolute(e))throw new $("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await Qr(r),i=Hs(t,e);if(!ei(t,i))throw new $("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let n=await Qr(i);if(!ei(t,n))throw new $("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return n}async function ii(r){try{return await r()}catch(e){if(e instanceof $)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new $("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new $("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function ni(r,e){return ii(async()=>{let t=await qt(r,e),i=[],n=!1;for await(let s of await Vs(t)){if(i.length===Xs){n=!0;break}let o=e?`${e}/${s.name}`:s.name,c=s.isDirectory()?"directory":s.isFile()?"file":"other";if(s.isSymbolicLink())try{let l=await ti(await qt(r,o));c=l.isDirectory()?"directory":l.isFile()?"file":"other"}catch{}i.push({name:s.name,path:o,kind:c})}return i.sort((s,o)=>+(o.kind==="directory")-+(s.kind==="directory")||Zs.compare(s.name,o.name)||s.name.localeCompare(o.name)),{path:e,entries:i,truncated:n}})}function eo(r){if(r.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(r[0]===255&&r[1]===216&&r[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(r.subarray(0,6).toString("ascii")))return"image/gif";if(r.subarray(0,4).toString("ascii")==="RIFF"&&r.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function ze(r,e){return ii(async()=>{let t=await qt(r,e);if(!(await ti(t)).isFile())throw new $("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await zs(t,Ht.O_RDONLY|Ht.O_NONBLOCK|(Ht.O_NOFOLLOW??0));try{let n=await i.stat();if(!n.isFile())throw new $("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let s={path:e,size:n.size},o=Buffer.alloc(16);await i.read(o,0,o.length,0);let c=eo(o),l=c?Qs:Ys;if(n.size>l)return{...s,kind:"too-large",limit:l,unit:"bytes"};let p=Buffer.alloc(Math.min(n.size+1,l+1)),u=0;for(;u<p.length;){let{bytesRead:g}=await i.read(p,u,p.length-u,u);if(!g)break;u+=g}if(u>n.size)throw new $("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let h=p.subarray(0,u);if(c)return{...s,kind:"image",mimeType:c,data:h.toString("base64")};if(h.some(g=>g===0||g<32&&![9,10,12,13,27].includes(g)))return{...s,kind:"unsupported"};let d=1;for(let g=0;g<h.length-1;g++)if(h[g]===10&&++d>Zr)return{...s,kind:"too-large",limit:Zr,unit:"lines"};try{return{...s,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(h)}}catch{return{...s,kind:"unsupported"}}}finally{await i.close()}})}var io=1e3,si=512*1024,oi=1e4;function ai(r,e){return e.startsWith(r)&&e.slice(r.length)||void 0}async function De(r){let e=await le(r);if(e.kind!=="repository")return e;let{root:t,scope:i}=e,n=await D(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),s={kind:"repository",root:t,scope:i,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=n.split("\0");for(let c=0;c<o.length;c++){let l=o[c];if(l.startsWith("# branch.oid ")){let P=l.slice(13);s.head=P==="(initial)"?null:P;continue}if(l.startsWith("# branch.head ")){let P=l.slice(14);s.branch=P==="(detached)"?null:P;continue}if(l.startsWith("# branch.upstream ")){s.upstream=l.slice(18);continue}if(l.startsWith("# branch.ab ")){let P=l.match(/\+(\d+) -(\d+)/);P&&(s.ahead=Number(P[1]),s.behind=Number(P[2]));continue}let p=l[0];if(!["1","2","u","?"].includes(p??""))continue;let u=p==="?"?1:p==="1"?8:p==="2"?9:10,h=0;for(let P=0;P<u;P++)h=l.indexOf(" ",h)+1;let d=ai(i,l.slice(h)),g=p==="2"?o[++c]:void 0;if(!d)continue;if(s.entries.length===io){s.truncated=!0;continue}let m=l.slice(0,h).split(" "),y={path:d,index:p==="?"?"?":m[1][0],worktree:p==="?"?"?":m[1][1],conflict:p==="u",untracked:p==="?",submodule:p!=="?"&&m[2]!=="N..."},N=g===void 0?void 0:ai(i,g);N&&(y.originalPath=N),s.entries.push(y)}return s}async function ci(r,e,t){if(Ee(e),!["staged","unstaged","untracked"].includes(t))throw new _("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let i=await De(r);if(i.kind!=="repository")throw new _("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let n={path:e,area:t},s=i.entries.find(c=>c.path===e);if(!s)return{...n,kind:"empty"};if(s.conflict)return{...n,kind:"conflict"};if(s.submodule)return{...n,kind:"submodule"};if(t==="untracked"){if(!s.untracked)return{...n,kind:"empty"};if(!(await to(ro(r,e))).isFile())return{...n,kind:"unsupported"};let c=await ze(r,e);if(c.kind==="too-large")return{...n,kind:"too-large"};if(c.kind!=="text")return{...n,kind:"binary"};if(!c.text)return{...n,kind:"empty"};let l=c.text.split(`
2
2
  `),p=l.at(-1)==="";p&&l.pop();let u=`--- /dev/null
3
3
  +++ b/${e.replace(/[\r\n]/g," ")}
4
4
  @@ -0,0 +1,${l.length} @@
@@ -25,7 +25,7 @@ ${p.stack.split(`
25
25
  `).slice(1).join(`
26
26
  `)}`);let h=this.reportError(u,{...s,stage:"provider_login"});l.view={id:c,providerId:e,method:t,status:"error",error:"\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u63D0\u4F9B\u65B9\u63D0\u793A\u5E76\u91CD\u8BD5\u3002",errorId:h}}}),{...l.view}}get(e){let t=this.flows.get(e)?.view;return t?{...t}:void 0}getActive(){let e=[...this.flows.values()].find(({view:t})=>t.status==="running"||t.status==="waiting")?.view;return e?{...e}:void 0}respond(e,t){let i=this.flows.get(e);if(!i?.answer||i.view.status!=="waiting"||i.view.prompt?.type==="select"&&!i.view.prompt.options.some(s=>s.id===t))return!1;let n=i.answer;return i.answer=void 0,i.reject=void 0,i.view={...i.view,status:"running",prompt:void 0},n(t),!0}cancel(e){let t=this.flows.get(e);return!t||t.view.status==="done"||t.view.status==="error"?!1:(t.view={...t.view,status:"cancelled",prompt:void 0},t.controller.abort(),t.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),t.answer=void 0,t.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as da}from"node:crypto";import{readFile as pa,rename as ua,rm as fa,stat as ga,writeFile as ma,mkdir as ha}from"node:fs/promises";import{dirname as wa}from"node:path";var ya=["openai-completions","openai-responses","anthropic-messages"];function ir(r){if(!r||typeof r!="object")return!1;let e=r;if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id)||typeof e.name!="string"||!e.name.trim()||e.name.length>100||typeof e.modelId!="string"||!e.modelId.trim()||e.modelId.length>200||!ya.includes(e.api)||typeof e.baseUrl!="string"||e.baseUrl.length>2048)return!1;try{let t=new URL(e.baseUrl);return(t.protocol==="https:"||t.protocol==="http:")&&!!t.hostname&&!t.username&&!t.password&&!t.hash}catch{return!1}}async function sn(r,e){if(!ir(e))throw new Error("\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u540D\u79F0\u3001\u5730\u5740\u6216\u6A21\u578B\u65E0\u6548");let t;try{t=await pa(r,"utf8")}catch(c){if(c.code!=="ENOENT")throw c}let i;if(t===void 0)i={providers:{}};else{try{i=JSON.parse(t)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!i||typeof i!="object"||!i.providers||typeof i.providers!="object"||Array.isArray(i.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(i.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let n={...i,providers:{...i.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await ha(wa(r),{recursive:!0});let s=t===void 0?384:(await ga(r)).mode&511,o=`${r}.pi-web-${da(6).toString("hex")}.tmp`;try{await ma(o,`${JSON.stringify(n,null,2)}
27
27
  `,{mode:s,flag:"wx"}),await ua(o,r)}finally{await fa(o,{force:!0})}}import{randomBytes as ba}from"node:crypto";import{mkdir as ka,readFile as va,rename as Ea,rm as xa,stat as Sa,writeFile as Pa}from"node:fs/promises";import{dirname as Ia}from"node:path";function on(r){if(!r||r.length>2048)return!1;try{let e=new URL(r);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function an(r){if(!r||typeof r!="object")return!1;let e=r;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&cn(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&on(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function cn(r){if(!r||typeof r!="object")return!1;let e=r;if(typeof e.id!="string"||!e.id.trim()||e.id.length>200||e.name!==void 0&&(typeof e.name!="string"||!e.name.trim()||e.name.length>200))return!1;for(let t of[e.contextWindow,e.maxTokens])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))return!1;return e.input===void 0||Array.isArray(e.input)&&e.input.length>0&&e.input.every(t=>t==="text"||t==="image")&&new Set(e.input).size===e.input.length}async function ln(r){let e;try{e=await va(r,"utf8")}catch(i){if(i.code!=="ENOENT")throw i}if(e===void 0)return{config:{providers:{}}};let t;try{t=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!t||typeof t!="object"||!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:t,existing:e}}async function Ca(r,e,t){await ka(Ia(r),{recursive:!0});let i=t===void 0?384:(await Sa(r)).mode&511,n=`${r}.pi-web-${ba(6).toString("hex")}.tmp`;try{await Pa(n,`${JSON.stringify(e,null,2)}
28
- `,{mode:i,flag:"wx"}),await Ea(n,r)}finally{await xa(n,{force:!0})}}async function dn(r,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i}=await ln(r),n=i.providers[e],s=new Set(n?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:n?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:s.has(o.id)?"custom":"builtin",overridden:!!n?.modelOverrides?.[o.id]}))}}async function pn(r,e,t,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:n,existing:s}=await ln(r),o={...n.providers[e]??{}},c=[...o.models??[]],l={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!on(t.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");t.baseUrl===null?delete o.baseUrl:o.baseUrl=t.baseUrl}else if(t.action==="save"){if(!cn(t.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let p={id:t.model.id.trim(),...t.model.name===void 0?{}:{name:t.model.name},...t.model.contextWindow===void 0?{}:{contextWindow:t.model.contextWindow},...t.model.maxTokens===void 0?{}:{maxTokens:t.model.maxTokens},...t.model.input===void 0?{}:{input:t.model.input}},u=t.originalId,h=u===void 0?-1:c.findIndex(d=>d.id===u);if(u===void 0&&(c.some(d=>d.id===p.id)||i.getModel(e,p.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(h>=0){if(p.id!==u&&(c.some(g=>g.id===p.id)||i.getModel(e,p.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let d={...c[h],...p};for(let g of["name","contextWindow","maxTokens","input"])p[g]===void 0&&delete d[g];c[h]=d}else if(u!==void 0&&i.getModel(e,u)){if(p.id!==u)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:d,...g}=p;l[u]={...l[u],...g};for(let m of["name","contextWindow","maxTokens","input"])p[m]===void 0&&delete l[u][m]}else{if(u!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");c.push(p)}}else{let p=c.findIndex(u=>u.id===t.id);if(p>=0)c.splice(p,1);else if(Object.hasOwn(l,t.id))delete l[t.id];else throw new Error("\u53EA\u80FD\u79FB\u9664\u81EA\u5B9A\u4E49\u6A21\u578B\u6216\u6062\u590D\u5DF2\u4FEE\u6539\u7684\u5185\u7F6E\u6A21\u578B")}c.length?o.models=c:delete o.models,Object.keys(l).length?o.modelOverrides=l:delete o.modelOverrides,Object.keys(o).length?n.providers[e]=o:delete n.providers[e],await Ca(r,n,s)}function un(r){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(r.trim())}import{randomBytes as fn,createHash as _a}from"node:crypto";import{fileURLToPath as Na}from"node:url";var bt="pi-webapp@0.1.31-alpha.3+9f4be3fc82f32eb4dfbc",se="9f4be3fc82f32eb4dfbc";var Aa="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function Ta(r=process.env,e=console.warn){let t=i=>{let n={enabled:!1,environment:r.PI_WEB_SENTRY_ENVIRONMENT||"production",release:bt,buildId:se},s=r[`PI_WEB_SENTRY_${i}_DSN`]??r.PI_WEB_SENTRY_DSN??Aa;if(r.PI_WEB_SENTRY_ENABLED==="false"||!s)return n;try{let o=new URL(s);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...n,enabled:!0,dsn:s}}catch{return e(`pi-webapp: invalid ${i.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),n}};return{browser:t("BROWSER"),node:t("NODE")}}var ue=class{config;ready;reporter;client;salt=fn(16);breadcrumbs=new He;seen=new WeakSet;early=[];state={nodeVersion:process.version,platform:process.platform};fatal;closed=!1;failed=!1;get enabled(){return this.config.node.enabled&&!this.closed&&!this.failed}constructor(e={}){if(this.config=Ta(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=Na(import.meta.url).replace(/\\/g,"/"),i=t.lastIndexOf("/src/"),n=i>=0?t.slice(0,i+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=s=>{s.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:n)&&this.capture(s,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=import("@sentry/node").then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:se,integrations:[],transport:e.transport??(i=>_i(t.createTransport,i)),stackParser:t.defaultStackParser,beforeSend:Ci,sendClientReports:!1,dataCollection:{...Si,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new pt(this.client,"node",se,t,this.breadcrumbs),this.reporter.setState(this.state);for(let i of this.early)this.reporter.capture(i.error,i.context,i.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,t={}){try{if(!this.enabled||xe(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,t);if(this.early.length>=20)return;let i=fn(16).toString("hex");return this.early.push({error:Me(e),context:ne(t),eventId:i}),i}catch{return}}setState(e){this.state=ne({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return _a("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),t;try{await Promise.race([this.ready,new Promise(i=>{t=setTimeout(i,500)})])}finally{clearTimeout(t),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as Ja}from"@earendil-works/pi-coding-agent";function he(r,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(r.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!r.idle&&!t)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(t&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as Ra}from"node:crypto";function qe(r){let e=[],t=r;for(;;){let i=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!i||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(i[3]))break;let n;try{n=JSON.parse(i[2])}catch{break}e.unshift({name:n,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(n)}),t=t.slice(0,i.index)}return{text:t,attachments:e}}var Ke=r=>Buffer.byteLength(r.text)+r.images.reduce((e,t)=>e+t.data.length,0),U=class extends Error{status=409},we=class{entries=[];pumping=!1;changed;constructor(e=()=>{}){this.changed=e}get length(){return this.entries.length}get sending(){return this.entries.some(e=>e.status==="sending")}view(){return this.entries.map(e=>({id:e.id,revision:e.revision,...qe(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,t=[],i){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((n,s)=>n+Ke(s),Ke({text:e,images:t}))>64*1024*1024)throw new U("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:Ra(),revision:1,text:e,images:t.map(n=>({...n})),correlation:i,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new U("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let i=this.entries.find(n=>n.id===e);if(!i||i.revision!==t)throw new U("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(i.status!=="queued")throw new U("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return i}async update(e,t,i,n){let s=this.find(e,t);if(i.kind==="remove"){this.entries=this.entries.filter(o=>o!==s),this.changed();return}if(i.kind==="edit"){let o=qe(s.text),c=s.text.slice(o.text.length).replace(/^\n\n/u,""),l=[i.text.trim(),c].filter(Boolean).join(`
28
+ `,{mode:i,flag:"wx"}),await Ea(n,r)}finally{await xa(n,{force:!0})}}async function dn(r,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i}=await ln(r),n=i.providers[e],s=new Set(n?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:n?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:s.has(o.id)?"custom":"builtin",overridden:!!n?.modelOverrides?.[o.id]}))}}async function pn(r,e,t,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:n,existing:s}=await ln(r),o={...n.providers[e]??{}},c=[...o.models??[]],l={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!on(t.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");t.baseUrl===null?delete o.baseUrl:o.baseUrl=t.baseUrl}else if(t.action==="save"){if(!cn(t.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let p={id:t.model.id.trim(),...t.model.name===void 0?{}:{name:t.model.name},...t.model.contextWindow===void 0?{}:{contextWindow:t.model.contextWindow},...t.model.maxTokens===void 0?{}:{maxTokens:t.model.maxTokens},...t.model.input===void 0?{}:{input:t.model.input}},u=t.originalId,h=u===void 0?-1:c.findIndex(d=>d.id===u);if(u===void 0&&(c.some(d=>d.id===p.id)||i.getModel(e,p.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(h>=0){if(p.id!==u&&(c.some(g=>g.id===p.id)||i.getModel(e,p.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let d={...c[h],...p};for(let g of["name","contextWindow","maxTokens","input"])p[g]===void 0&&delete d[g];c[h]=d}else if(u!==void 0&&i.getModel(e,u)){if(p.id!==u)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:d,...g}=p;l[u]={...l[u],...g};for(let m of["name","contextWindow","maxTokens","input"])p[m]===void 0&&delete l[u][m]}else{if(u!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");c.push(p)}}else{let p=c.findIndex(u=>u.id===t.id);if(p>=0)c.splice(p,1);else if(Object.hasOwn(l,t.id))delete l[t.id];else throw new Error("\u53EA\u80FD\u79FB\u9664\u81EA\u5B9A\u4E49\u6A21\u578B\u6216\u6062\u590D\u5DF2\u4FEE\u6539\u7684\u5185\u7F6E\u6A21\u578B")}c.length?o.models=c:delete o.models,Object.keys(l).length?o.modelOverrides=l:delete o.modelOverrides,Object.keys(o).length?n.providers[e]=o:delete n.providers[e],await Ca(r,n,s)}function un(r){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(r.trim())}import{randomBytes as fn,createHash as _a}from"node:crypto";import{fileURLToPath as Na}from"node:url";var bt="pi-webapp@0.1.31-alpha.4+4c8a8ae92e46a7895c5a",se="4c8a8ae92e46a7895c5a";var Aa="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function Ta(r=process.env,e=console.warn){let t=i=>{let n={enabled:!1,environment:r.PI_WEB_SENTRY_ENVIRONMENT||"production",release:bt,buildId:se},s=r[`PI_WEB_SENTRY_${i}_DSN`]??r.PI_WEB_SENTRY_DSN??Aa;if(r.PI_WEB_SENTRY_ENABLED==="false"||!s)return n;try{let o=new URL(s);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...n,enabled:!0,dsn:s}}catch{return e(`pi-webapp: invalid ${i.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),n}};return{browser:t("BROWSER"),node:t("NODE")}}var ue=class{config;ready;reporter;client;salt=fn(16);breadcrumbs=new He;seen=new WeakSet;early=[];state={nodeVersion:process.version,platform:process.platform};fatal;closed=!1;failed=!1;get enabled(){return this.config.node.enabled&&!this.closed&&!this.failed}constructor(e={}){if(this.config=Ta(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=Na(import.meta.url).replace(/\\/g,"/"),i=t.lastIndexOf("/src/"),n=i>=0?t.slice(0,i+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=s=>{s.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:n)&&this.capture(s,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=import("@sentry/node").then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:se,integrations:[],transport:e.transport??(i=>_i(t.createTransport,i)),stackParser:t.defaultStackParser,beforeSend:Ci,sendClientReports:!1,dataCollection:{...Si,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new pt(this.client,"node",se,t,this.breadcrumbs),this.reporter.setState(this.state);for(let i of this.early)this.reporter.capture(i.error,i.context,i.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,t={}){try{if(!this.enabled||xe(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,t);if(this.early.length>=20)return;let i=fn(16).toString("hex");return this.early.push({error:Me(e),context:ne(t),eventId:i}),i}catch{return}}setState(e){this.state=ne({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return _a("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),t;try{await Promise.race([this.ready,new Promise(i=>{t=setTimeout(i,500)})])}finally{clearTimeout(t),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as Ja}from"@earendil-works/pi-coding-agent";function he(r,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(r.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!r.idle&&!t)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(t&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as Ra}from"node:crypto";function qe(r){let e=[],t=r;for(;;){let i=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!i||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(i[3]))break;let n;try{n=JSON.parse(i[2])}catch{break}e.unshift({name:n,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(n)}),t=t.slice(0,i.index)}return{text:t,attachments:e}}var Ke=r=>Buffer.byteLength(r.text)+r.images.reduce((e,t)=>e+t.data.length,0),U=class extends Error{status=409},we=class{entries=[];pumping=!1;changed;constructor(e=()=>{}){this.changed=e}get length(){return this.entries.length}get sending(){return this.entries.some(e=>e.status==="sending")}view(){return this.entries.map(e=>({id:e.id,revision:e.revision,...qe(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,t=[],i){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((n,s)=>n+Ke(s),Ke({text:e,images:t}))>64*1024*1024)throw new U("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:Ra(),revision:1,text:e,images:t.map(n=>({...n})),correlation:i,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new U("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let i=this.entries.find(n=>n.id===e);if(!i||i.revision!==t)throw new U("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(i.status!=="queued")throw new U("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return i}async update(e,t,i,n){let s=this.find(e,t);if(i.kind==="remove"){this.entries=this.entries.filter(o=>o!==s),this.changed();return}if(i.kind==="edit"){let o=qe(s.text),c=s.text.slice(o.text.length).replace(/^\n\n/u,""),l=[i.text.trim(),c].filter(Boolean).join(`
29
29
 
30
30
  `);if(this.validateText(l),this.entries.reduce((p,u)=>p+Ke(u),0)-Ke(s)+Ke({text:l,images:s.images})>64*1024*1024)throw new U("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");s.text=l,s.revision++,delete s.error,this.changed();return}await this.deliver(s,n)}async deliver(e,t){e.status="sending",e.revision++,delete e.error,this.changed();try{await t(e.text,e.images,e.correlation),this.entries=this.entries.filter(i=>i!==e)}catch(i){throw e.status="queued",e.revision++,e.error=i instanceof Error?i.message:"\u53D1\u9001\u5931\u8D25",i}finally{this.changed()}}schedule(e,t){let i=this.entries[0];this.pumping||!i||i.status!=="queued"||i.error||!e()||(this.pumping=!0,i.status="sending",i.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){i.status="queued",i.revision++,this.changed();return}await this.deliver(i,t)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,t)}})()}))}};import{readFile as gn}from"node:fs/promises";import{join as mn}from"node:path";async function hn(r){try{let e=JSON.parse(await gn(mn(r,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,i=await gn(mn(r,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let s of[...Object.values(e),{assets:Array.isArray(i)?i:[]}])if(!(!s||typeof s!="object"))for(let o of[s.file,...Array.isArray(s.css)?s.css:[],...Array.isArray(s.assets)?s.assets:[]])typeof o=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(o)&&t.add(o);let n={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...t].map(s=>[`/${s}`,{path:s,type:n[s.split(".").pop()]}]))}catch{return{}}}import{access as Ma,readFile as nr,realpath as vt,rename as Oa,rm as Wa,writeFile as Fa}from"node:fs/promises";import{randomUUID as Ba}from"node:crypto";import{dirname as kt,join as ae,resolve as ja,sep as bn}from"node:path";import{createRequire as $a}from"node:module";var Da=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function ye(r){let e=typeof r=="string"&&Da.exec(r);if(!e||e[0]!==r)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let t=e.slice(1,4).map(Number),i=e[4]?.split(".")??[];if(!t.every(Number.isSafeInteger)||i.some(n=>/^\d+$/.test(n)&&n.length>1&&n[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:t,prerelease:i}}function oe(r,e){let t=ye(r),i=ye(e);for(let n=0;n<3;n++)if(t.core[n]!==i.core[n])return t.core[n]>i.core[n]?1:-1;if(!t.prerelease.length||!i.prerelease.length)return+!t.prerelease.length-+!i.prerelease.length;for(let n=0;n<Math.max(t.prerelease.length,i.prerelease.length);n++){let s=t.prerelease[n],o=i.prerelease[n];if(s===void 0||o===void 0)return s===void 0?-1:1;if(s===o)continue;let c=/^\d+$/.test(s),l=/^\d+$/.test(o);return c!==l?c?-1:1:c&&s.length!==o.length?s.length>o.length?1:-1:s>o?1:-1}return 0}function wn(r){try{return ye(r).prerelease.length===0}catch{return!1}}function yn(r){try{return ye(r),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(r)}catch{return!1}}var Se=1,kn=r=>ae(r,"pi-web","desktop-update.json");async function Oe(r,e){let t=$a(ae(r,"package.json"));for(let i of t.resolve.paths(e)??[]){let n=ae(i,e);try{if(JSON.parse(await nr(ae(n,"package.json"),"utf8")).name===e)return await vt(n)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function sr(r,e){if(oe(e?.version,e?.version),e.desktopProtocolVersion!==Se||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await vt(ja(kt(e.launcher),"..")),i=await vt(ae(r,"pi-web","releases")),n=kt(kt(t));if(await vt(e.launcher)!==ae(t,"bin","pi-webapp.mjs")||kt(n)!==i||!n.startsWith(i+bn)||!n.slice(i.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(n.slice(i.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let s=JSON.parse(await nr(ae(t,"package.json"),"utf8"));if(s.name!=="pi-webapp"||s.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(s.piWebappDesktopProtocol!==Se)throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF0C\u5C1A\u672A\u5207\u6362\u8FD0\u884C\u7248\u672C");let o=await Oe(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(n+bn))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let c=ae(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,c,ae(t,"dist","extension.js"),ae(t,"web","dist","index.html")].map(l=>Ma(l))),e.fallbackVersion!==void 0&&ye(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:c,desktopProtocolVersion:Se,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}async function vn(r,e){try{let t=JSON.parse(await nr(kn(r),"utf8"));return oe(t.version,e)<0&&t.fallbackVersion!==e?null:await sr(r,t)}catch{return null}}async function En(r,e){let t=kn(r),i=`${t}.${Ba()}.tmp`;try{await Fa(i,JSON.stringify(e),{mode:384}),await Oa(i,t)}finally{await Wa(i,{force:!0})}}var Ha={"/":{path:"index.html",type:"text/html; charset=utf-8"},"/assets/app.js":{path:"assets/app.js",type:"text/javascript; charset=utf-8"},"/assets/style.css":{path:"assets/style.css",type:"text/css; charset=utf-8"}};function b(r,e,t){typeof t=="object"&&t!==null&&"error"in t&&(t={errorCode:e>=500?"server_error":"validation_error",...t,requestId:r.getHeader("X-Request-ID"),operationId:r.getHeader("X-Operation-ID")}),r.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),r.end(JSON.stringify(t))}function qa(r,e){let t=r.headers.authorization;if(typeof t!="string"||!t.startsWith("Bearer "))return!1;let i=Buffer.from(t.slice(7),"utf8");return i.length===e.length&&La(i,e)}async function Ka(r,e=64*1024){let t=0,i=[];for await(let n of r){let s=Buffer.isBuffer(n)?n:Buffer.from(n);if(t+=s.length,t>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");i.push(s)}return JSON.parse(Buffer.concat(i).toString("utf8"))}async function Xa(r){let e=0,t=[];for await(let i of r){let n=Buffer.isBuffer(i)?i:Buffer.from(i);if(e+=n.length,e>wt)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(n)}return Buffer.concat(t)}async function Ya(r,e=0){await new Promise((i,n)=>{r.once("error",n),r.listen(e,"127.0.0.1",()=>{r.off("error",n),i()})});let t=r.address();if(t===null||typeof t=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return t.port}async function Sn(r,e,t=new ue,i={}){t.setState({piVersion:Ja});let n=process.env.PI_WEBAPP_RESTART_TOKEN,s=n&&/^[A-Za-z0-9_-]{32}$/.test(n)?n:xn(24).toString("base64url"),o=Buffer.from(s),c=Yi(),l=new Set,p=new gt(i.pluginSettingsFile??ar(Va(),"pi-web","plugins.json"));try{await p.load()}catch(k){throw await t.close(),k}let u=new mt(Ui(),p),h=async()=>await r.plugins?.()??{plugins:[],errors:[]},d=()=>({type:"plugin_state",disabled:u.plugins.filter(k=>!p.enabled(k.metadata.id)).map(k=>k.metadata.id)}),g=()=>{for(let k of l)k.write(`${JSON.stringify(d())}
31
31
  `)},m=new Map,y=new yt((k,w)=>t.capture(k,w)),N=k=>t.setState({nodeVersion:process.version,platform:process.platform,session:t.session(k.sessionId),idle:k.idle,model:k.model,thinkingLevel:k.thinkingLevel,messageCount:k.messages.length}),P="",W=!1,Z={...Ha,...await hn(e)};for(let k of await Ua(ar(e,"assets")).catch(()=>[])){let w=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(k);if(!w)continue;let H={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};Z[`/assets/${k}`]={path:`assets/${k}`,type:H[w[1]]}}let ge=za(async(k,w)=>{let H=xn(18).toString("base64"),me=X=>typeof X=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(X),ke=me(k.headers["x-request-id"])?k.headers["x-request-id"]:or(),q={requestId:ke,operationId:me(k.headers["x-operation-id"])?k.headers["x-operation-id"]:void 0};w.setHeader("X-Request-ID",ke),q.operationId&&w.setHeader("X-Operation-ID",q.operationId);let x="/",fs=performance.now(),K=(X,f,v)=>{let T=!xe(X)&&Pi(x)?de(X,"Agent or provider operation failed"):X,O=t.capture(T,{...q,route:x,method:k.method,status:f,stage:"http"});b(w,f,{error:v,errorId:O,errorReported:t.enabled,errorCode:xe(X)?"validation_error":"unexpected_error"})};w.once("finish",()=>{x.startsWith("/api/telemetry/")||t.breadcrumb("request",{...q,route:x,method:k.method,status:w.statusCode,durationMs:Math.round(performance.now()-fs)})});try{w.setHeader("X-Content-Type-Options","nosniff"),w.setHeader("Referrer-Policy","no-referrer"),w.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${H}'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'${t.config.browser.dsn?` ${new URL(t.config.browser.dsn).origin}`:""}; img-src 'self' data: blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`);try{x=new URL(k.url??"/",P).pathname}catch{b(w,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let X=Z[x];if(k.method==="GET"&&X){try{let f=await Ga(ar(e,X.path));w.writeHead(200,{"Content-Type":X.type,"Cache-Control":"no-store"}),w.end(x==="/"?f.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${H}">`):f)}catch(f){K(f,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x.startsWith("/plugins/")){try{let f=await r.pluginAsset?.(k.url??x);if(!f){b(w,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}w.writeHead(200,{"Content-Type":f.type,"Cache-Control":"no-store"}),w.end(f.bytes)}catch(f){K(f,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!x.startsWith("/api/")){b(w,404,{error:"\u672A\u627E\u5230"});return}if(!qa(k,o)){b(w,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(k.method==="GET"&&x==="/api/telemetry/config"){b(w,200,t.config.browser);return}if(k.method==="GET"&&x==="/api/update/version"){try{b(w,200,{current:await r.selfUpdate?.runningVersion()??null,desktopProtocolVersion:Se})}catch(f){K(f,503,f instanceof Error?f.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(k.method==="GET"&&x==="/api/update"){try{b(w,200,await r.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(f){K(f,503,f instanceof Error?f.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(k.method==="GET"&&x==="/api/image"){let f=new URL(k.url??x,P),v=f.searchParams.get("sessionId")??"",I=f.searchParams.get("messageId")??"",T=Number(f.searchParams.get("index"));if(!v||v!==r.snapshot().sessionId||!I||!Number.isInteger(T)||T<0||T>100){b(w,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let O=r.image?.(v,I,T);if(!O||!["image/png","image/jpeg","image/webp","image/gif"].includes(O.mimeType)){b(w,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}w.writeHead(200,{"Content-Type":O.mimeType,"Cache-Control":"private, no-store"}),w.end(O.data);return}if(k.method==="POST"&&x==="/api/attachment"){if(k.headers.origin!==void 0&&k.headers.origin!==P){b(w,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let f=new URL(k.url??x,P),v=f.searchParams.get("sessionId"),I=f.searchParams.get("name");try{if(!v||!I||I.length>1024||v!==r.snapshot().sessionId){b(w,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(k.headers["content-length"]??0)>wt){b(w,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let T=await tn(v,I,k.headers["content-type"]??"application/octet-stream",await Xa(k));if(v!==r.snapshot().sessionId){b(w,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}m.set(T.id,T),b(w,201,{id:T.id,name:T.name,bytes:T.bytes})}catch(T){K(T,400,T instanceof Error?T.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(k.method==="GET"&&x==="/api/session"){try{let f=r.snapshot();N(f),b(w,200,f)}catch(f){K(f,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/plugin-management"){try{b(w,200,u.inventory(await h()))}catch(f){K(f,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/plugins"){try{b(w,200,u.catalog(await h()))}catch(f){K(f,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/providers"){try{b(w,200,await r.providers?.()??[])}catch(f){K(f,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/provider/models"){let f=new URL(k.url??x,P).searchParams.get("providerId")??"";try{if(!f||!r.providerModels){b(w,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}b(w,200,await r.providerModels(f))}catch(v){K(v,400,v instanceof Error?v.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/provider/login/active"){b(w,200,{active:y.getActive()??null});return}if(k.method==="GET"&&x==="/api/provider/login"){let f=new URL(k.url??x,P).searchParams.get("id")??"",v=y.get(f);b(w,v?200:404,v??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(k.method==="GET"&&(x==="/api/models"||x==="/api/config"||x==="/api/workspaces"||x==="/api/commands")){try{b(w,200,x==="/api/models"?await r.models():x==="/api/config"?await r.config():x==="/api/commands"?r.commands?.()??[]:await r.workspaces())}catch(f){K(f,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/directory/capability"){b(w,200,{kind:c});return}if(k.method==="GET"&&x==="/api/events"){let f;try{f=r.snapshot(),N(f)}catch(v){K(v,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}w.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),l.add(w),w.write(`${JSON.stringify({type:"snapshot",session:f})}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-webapp",
3
- "version": "0.1.31-alpha.3",
3
+ "version": "0.1.31-alpha.4",
4
4
  "type": "module",
5
5
  "piWebappDesktopProtocol": 1,
6
6
  "piWebappDataVersion": 1,
@@ -17,7 +17,7 @@
17
17
  "pi-webapp": "./bin/pi-webapp.mjs"
18
18
  },
19
19
  "pi": {
20
- "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.31-alpha.3/assets/cover-webapp.png",
20
+ "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.31-alpha.4/assets/cover-webapp.png",
21
21
  "extensions": [
22
22
  "./dist/extension.js"
23
23
  ]