openpond 0.2.0 → 0.2.2

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 (220) hide show
  1. package/dist/chunks/actions-command-F55CBR2K.js +2 -0
  2. package/dist/chunks/app-layer-GNYLOBCX.js +3 -0
  3. package/dist/chunks/app-server-runtime-VAGY4LQS.js +2 -0
  4. package/dist/chunks/apps-HZ5JGBDR.js +2 -0
  5. package/dist/chunks/chunk-22UARBPW.js +3 -0
  6. package/dist/chunks/chunk-3A7HZJNE.js +1 -0
  7. package/dist/chunks/chunk-3M53YXEI.js +2 -0
  8. package/dist/chunks/chunk-3NDRIQTI.js +2 -0
  9. package/dist/chunks/chunk-6FA3GG5B.js +33 -0
  10. package/dist/chunks/chunk-6MI4KKWF.js +2 -0
  11. package/dist/chunks/chunk-7D2LMRP7.js +2 -0
  12. package/dist/chunks/chunk-A42DFLOR.js +16 -0
  13. package/dist/chunks/chunk-AF57BF75.js +24 -0
  14. package/dist/chunks/chunk-BX4J2VDU.js +2 -0
  15. package/dist/chunks/chunk-BZMVB3GS.js +2 -0
  16. package/dist/chunks/chunk-CCJG7GLE.js +5 -0
  17. package/dist/chunks/chunk-CWQWV2T3.js +2 -0
  18. package/dist/chunks/chunk-DUA3QP6Y.js +19 -0
  19. package/dist/chunks/chunk-EAPFMACH.js +10 -0
  20. package/dist/chunks/chunk-EG3XB6M6.js +5 -0
  21. package/dist/chunks/chunk-ES2ISFJC.js +66 -0
  22. package/dist/chunks/chunk-FTQLQJQV.js +2 -0
  23. package/dist/chunks/chunk-FYCJSUFV.js +53 -0
  24. package/dist/chunks/chunk-GEANXBLX.js +2 -0
  25. package/dist/chunks/chunk-GLUWATL5.js +2 -0
  26. package/dist/chunks/chunk-GPZYIVFV.js +2199 -0
  27. package/dist/chunks/chunk-H7IWJN7L.js +17 -0
  28. package/dist/chunks/chunk-HZP5U2AA.js +3 -0
  29. package/dist/chunks/chunk-I5K74TOH.js +3 -0
  30. package/dist/chunks/chunk-I7G35U7K.js +2 -0
  31. package/dist/chunks/chunk-IR3YJWPW.js +7 -0
  32. package/dist/chunks/chunk-J7WZSLHS.js +18 -0
  33. package/dist/chunks/chunk-K35OOAW2.js +6 -0
  34. package/dist/chunks/chunk-KDXLNQNF.js +12 -0
  35. package/dist/chunks/chunk-KJYNLFWD.js +2872 -0
  36. package/dist/chunks/chunk-KV2IXO2T.js +6 -0
  37. package/dist/chunks/chunk-NVGMZ2IN.js +2 -0
  38. package/dist/chunks/chunk-OGPHXXCD.js +1 -0
  39. package/dist/chunks/chunk-RAKJWIYO.js +36 -0
  40. package/dist/chunks/chunk-RWSAGQTP.js +2 -0
  41. package/dist/chunks/chunk-SDO4FC4Q.js +2 -0
  42. package/dist/chunks/chunk-T5XCPX4P.js +3 -0
  43. package/dist/chunks/chunk-VYUMTRB3.js +5 -0
  44. package/dist/chunks/chunk-X37KMV27.js +1 -0
  45. package/dist/chunks/chunk-XAYIETBO.js +28 -0
  46. package/dist/chunks/chunk-XEOEKFG6.js +71 -0
  47. package/dist/chunks/chunk-ZVOO7FKM.js +2 -0
  48. package/dist/chunks/cli-UYTSZB4Y.js +2 -0
  49. package/dist/chunks/configuration-command-HAPIYG25.js +2 -0
  50. package/dist/chunks/continual-D75WA7E7.js +7 -0
  51. package/dist/chunks/core-commands-N37UZEVE.js +2 -0
  52. package/dist/chunks/database-X2CUV732.js +2 -0
  53. package/dist/chunks/desktop-test-V7FBEG7U.js +3 -0
  54. package/dist/chunks/dist-NKLXFA37.js +2 -0
  55. package/dist/chunks/extension-NEPOQ44P.js +5 -0
  56. package/dist/chunks/help-HC4N5ZQC.js +8 -0
  57. package/dist/chunks/module-ES6BEMUI-ZVL3F6NW.js +2 -0
  58. package/dist/chunks/module-asyncify-2EFITU5U-R7TVXNAE.js +2 -0
  59. package/dist/chunks/opchat-C7XRN4ZW.js +3 -0
  60. package/dist/chunks/organizations-LQGRZJ2V.js +2 -0
  61. package/dist/chunks/profile-UWM24A7R.js +3 -0
  62. package/dist/chunks/project-agent-2ME52ZJW.js +2 -0
  63. package/dist/chunks/sandbox-command-53L3ZICT.js +2 -0
  64. package/dist/chunks/sandbox-template-55HUM5H7.js +10 -0
  65. package/dist/chunks/src-EYJF2LWV.js +319 -0
  66. package/dist/chunks/src-VGW2UEMV.js +82 -0
  67. package/dist/chunks/taskset-PISBOILQ.js +2 -0
  68. package/dist/chunks/teams-bot-FHD2HCHN.js +3 -0
  69. package/dist/chunks/training-2NDOWH5S.js +2 -0
  70. package/dist/chunks/workspaces-CQFVCR7T.js +2 -0
  71. package/dist/cli.js +3 -109
  72. package/dist/index.js +1 -31230
  73. package/dist/sandbox-template/manifest.js +1 -18380
  74. package/dist/web/assets/App-BoJQRfeu.js +176 -0
  75. package/dist/web/assets/AppDialog-rdfmJsGF.js +1 -0
  76. package/dist/web/assets/AppTerminalPanel-CLW0kxtg.js +2 -0
  77. package/dist/web/assets/{AppsView-B1NUuAIf.js → AppsView-DxMXadnp.js} +1 -1
  78. package/dist/web/assets/{BrowserSidebar-DOvYxXeP.js → BrowserSidebar-BH_jl0JS.js} +1 -1
  79. package/dist/web/assets/{CartesianChart-pOrYpzBr.js → CartesianChart-oT_rMYpf.js} +1 -1
  80. package/dist/web/assets/{CollaborationTabs-CgbR-MBJ.js → CollaborationTabs-CukgFGE0.js} +1 -1
  81. package/dist/web/assets/{CommandMenu-CrIr4qUX.js → CommandMenu-2btBTgOF.js} +1 -1
  82. package/dist/web/assets/{CommunityView-CvAVQ_HZ.js → CommunityView-DMTREmN5.js} +1 -1
  83. package/dist/web/assets/{ComposerCreateImproveStrip-DybcKwwd.js → ComposerCreateImproveStrip-3tN55cg9.js} +1 -1
  84. package/dist/web/assets/GetStartedView-CMHL24_w.js +1 -0
  85. package/dist/web/assets/HostedModelLearningReview-CqkSelkC.js +1 -0
  86. package/dist/web/assets/HostedModelLearningSettings-xqd2lSW3.js +1 -0
  87. package/dist/web/assets/LabModelVersionDetailPage-Bpnya5DM.js +1 -0
  88. package/dist/web/assets/{LabSkillSidebar-CuaYrtiu.js → LabSkillSidebar-BKZjScr8.js} +1 -1
  89. package/dist/web/assets/LabsRoute-BhPFmA_Z.js +32 -0
  90. package/dist/web/assets/LabsRoute-C1FWCoYb.css +1 -0
  91. package/dist/web/assets/MainChatThread-Bosxokt-.js +2 -0
  92. package/dist/web/assets/MainPane-Di-Rwe7x.js +8 -0
  93. package/dist/web/assets/{MarkdownText-DOlVQR8a.js → MarkdownText-dK4SBPp_.js} +1 -1
  94. package/dist/web/assets/{Messages-DMubppta.js → Messages-ftYRMKYa.js} +6 -6
  95. package/dist/web/assets/{NativeSkillSidebar-DSFwZ-od.js → NativeSkillSidebar-Cwo7JdB2.js} +1 -1
  96. package/dist/web/assets/{NewExperienceSwitcher-Dj0ePIJ-.js → NewExperienceSwitcher-C1_JzTq2.js} +1 -1
  97. package/dist/web/assets/{NewProjectDialog-B8NQV-Ji.js → NewProjectDialog-CxP6v6YW.js} +1 -1
  98. package/dist/web/assets/{OutputsPage-D_LDYTgV.js → OutputsPage-DL21_Alp.js} +1 -1
  99. package/dist/web/assets/{ProjectsPage-xjDYPc_W.js → ProjectsPage-BO9VyvMA.js} +1 -1
  100. package/dist/web/assets/RightChatPanelStack-DaqAnzdR.js +1 -0
  101. package/dist/web/assets/{RightSidebarHomePanel-j0VckZUu.js → RightSidebarHomePanel-PbUG12AO.js} +1 -1
  102. package/dist/web/assets/{ScheduledWorkPage-1aT4bBY-.js → ScheduledWorkPage-BhL-cXML.js} +1 -1
  103. package/dist/web/assets/{SettingsView-BSpuMDpv.js → SettingsView-D6-s7G88.js} +7 -7
  104. package/dist/web/assets/TeamChatView-DbS1N-fo.js +3 -0
  105. package/dist/web/assets/{TerminalOverlay-CrSwUk2d.js → TerminalOverlay-CphyBXJR.js} +3 -3
  106. package/dist/web/assets/{TrainingCreationPanel-B4HMRwUg.js → TrainingCreationPanel-Czsdraix.js} +1 -1
  107. package/dist/web/assets/{TrainingDraftPanel-D4r1tN3I.js → TrainingDraftPanel-Bq3B5pUk.js} +1 -1
  108. package/dist/web/assets/{UsageSettingsSection-2aymqwIM.js → UsageSettingsSection-B74FNwaP.js} +5 -5
  109. package/dist/web/assets/{WorkSidebarPanel-B0X0OiR6.js → WorkSidebarPanel-BgaK4XSg.js} +1 -1
  110. package/dist/web/assets/WorkspaceDiffPanel-C3seHnVY.js +14 -0
  111. package/dist/web/assets/{WorkspaceEnvironmentMenu-OAfMEt7L.js → WorkspaceEnvironmentMenu-DPghQUdv.js} +3 -3
  112. package/dist/web/assets/{WorkspaceGitDialogs-YxcPH2Rq.js → WorkspaceGitDialogs-D8c6Okb_.js} +1 -1
  113. package/dist/web/assets/{WorkspaceMonacoEditor-COKTiQZl.js → WorkspaceMonacoEditor-2kjRFf4l.js} +36 -36
  114. package/dist/web/assets/{arrow-up-right-_TX-awvK.js → arrow-up-right-C5X-29oa.js} +1 -1
  115. package/dist/web/assets/chat-file-links-Bmz9kVct.js +1 -0
  116. package/dist/web/assets/chevron-up-NbP9vY4E.js +1 -0
  117. package/dist/web/assets/{clipboard-CyRSS8Sy.js → clipboard-fvHMXPWa.js} +1 -1
  118. package/dist/web/assets/{cloud-upload-uBJBUYTy.js → cloud-upload-BAycsdHL.js} +1 -1
  119. package/dist/web/assets/{cssMode-BrXSsZYs.js → cssMode-Yis679a5.js} +1 -1
  120. package/dist/web/assets/{folder-open-DktdZNW7.js → folder-open-bii4KUCv.js} +1 -1
  121. package/dist/web/assets/{folder-plus-DO06i9Vo.js → folder-plus-B0B7mUCx.js} +1 -1
  122. package/dist/web/assets/{git-commit-horizontal-zFSIkPs7.js → git-commit-horizontal-B6yTdtnB.js} +1 -1
  123. package/dist/web/assets/{htmlMode-X9UMFkjt.js → htmlMode-DHeBSKVF.js} +1 -1
  124. package/dist/web/assets/{index-UOGdfLzi.js → index-667pXXsu.js} +1 -1
  125. package/dist/web/assets/{index-ByQIHpc9.css → index-BGMzUaup.css} +1 -1
  126. package/dist/web/assets/{info-BEJXUqCD.js → info-NCOESX3I.js} +1 -1
  127. package/dist/web/assets/{jsonMode-DIsB-j2E.js → jsonMode-C4oxy1cU.js} +1 -1
  128. package/dist/web/assets/{lspLanguageFeatures-CmZ17KpA.js → lspLanguageFeatures-CLj3WGZW.js} +1 -1
  129. package/dist/web/assets/{minimize-2-DumTpFtE.js → minimize-2-DtI1vgd7.js} +1 -1
  130. package/dist/web/assets/{monaco.contribution-D6w5PJji.js → monaco.contribution-DZPgekIQ.js} +2 -2
  131. package/dist/web/assets/{monaco.contribution-DJ_NmcHu.js → monaco.contribution-Ddw-TznO.js} +2 -2
  132. package/dist/web/assets/{monaco.contribution-YVDfJcG4.js → monaco.contribution-DhVPJ-oY.js} +2 -2
  133. package/dist/web/assets/{monaco.contribution-LZEujgny.js → monaco.contribution-DrW6DjWP.js} +2 -2
  134. package/dist/web/assets/{play-CLFeH7CU.js → play-DB3XFAnG.js} +1 -1
  135. package/dist/web/assets/{python-Djbda_qZ.js → python-DLyUeEeL.js} +1 -1
  136. package/dist/web/assets/{refresh-cw-B4IpQ_7Q.js → refresh-cw-0zSLZtfp.js} +1 -1
  137. package/dist/web/assets/{save-BbTHztnA.js → save-BCZlshOA.js} +1 -1
  138. package/dist/web/assets/{square-BJrVbmz6.js → square-CRytZWR_.js} +1 -1
  139. package/dist/web/assets/{toggleHighContrast-BopU5W9S.js → toggleHighContrast-TXg0rI_R.js} +1 -1
  140. package/dist/web/assets/{tsMode-CH_0_YDX.js → tsMode-Bj1019AY.js} +1 -1
  141. package/dist/web/assets/{upload-UumVeufu.js → upload-CnE9u7GB.js} +1 -1
  142. package/dist/web/assets/{useLocalAgentSchedules-BRa23U7O.js → useLocalAgentSchedules-qI87RHVI.js} +1 -1
  143. package/dist/web/assets/{wifi-off-BWJWivn6.js → wifi-off-CfuwRBx7.js} +1 -1
  144. package/dist/web/assets/{workers-pTe8RvSI.js → workers-CXdUI7wU.js} +1 -1
  145. package/dist/web/assets/{yaml-DNLASORn.js → yaml-AP8aiwLm.js} +1 -1
  146. package/dist/web/index.html +2 -2
  147. package/package.json +4 -3
  148. package/dist/chunks/actions-command-6N5XWMR6.js +0 -185
  149. package/dist/chunks/app-layer-F3CGXB33.js +0 -216
  150. package/dist/chunks/app-server-runtime-RHO5TFUC.js +0 -23
  151. package/dist/chunks/apps-L5XCL7QY.js +0 -429
  152. package/dist/chunks/chunk-26AMV5ZI.js +0 -634
  153. package/dist/chunks/chunk-3EB7I67T.js +0 -630
  154. package/dist/chunks/chunk-3ELF4FXY.js +0 -96
  155. package/dist/chunks/chunk-3VEYNDHN.js +0 -669
  156. package/dist/chunks/chunk-4KA25HUP.js +0 -5648
  157. package/dist/chunks/chunk-4L3ZJS2T.js +0 -1207
  158. package/dist/chunks/chunk-6SMNG6YA.js +0 -1303
  159. package/dist/chunks/chunk-7RIGZB7N.js +0 -1148
  160. package/dist/chunks/chunk-A6G3PFA5.js +0 -2164
  161. package/dist/chunks/chunk-BVY5JYM6.js +0 -512
  162. package/dist/chunks/chunk-DLQQIWN2.js +0 -648
  163. package/dist/chunks/chunk-FJ2JGB2N.js +0 -1373
  164. package/dist/chunks/chunk-FQS2QL5F.js +0 -14522
  165. package/dist/chunks/chunk-G65WAOJV.js +0 -1643
  166. package/dist/chunks/chunk-JTHL5XJ2.js +0 -1838
  167. package/dist/chunks/chunk-K4TZEHAW.js +0 -602
  168. package/dist/chunks/chunk-KCRCIQPD.js +0 -66
  169. package/dist/chunks/chunk-KSRWKXRB.js +0 -12
  170. package/dist/chunks/chunk-MUMPWI4O.js +0 -92
  171. package/dist/chunks/chunk-NTK22KJD.js +0 -10707
  172. package/dist/chunks/chunk-OCBRPU2K.js +0 -629
  173. package/dist/chunks/chunk-PS37DB5F.js +0 -183
  174. package/dist/chunks/chunk-R3C3MNSI.js +0 -140
  175. package/dist/chunks/chunk-SMNFI2FU.js +0 -113
  176. package/dist/chunks/chunk-UACZUFIA.js +0 -47
  177. package/dist/chunks/chunk-UZMVNKXM.js +0 -1275
  178. package/dist/chunks/chunk-VT6BLHMB.js +0 -67198
  179. package/dist/chunks/chunk-W5GKHH77.js +0 -168
  180. package/dist/chunks/chunk-X6F4LBTQ.js +0 -832
  181. package/dist/chunks/chunk-X7ZG4TSW.js +0 -3063
  182. package/dist/chunks/chunk-XA4KBDMY.js +0 -13723
  183. package/dist/chunks/chunk-YVCYVDNP.js +0 -746
  184. package/dist/chunks/chunk-ZNQEROWP.js +0 -254
  185. package/dist/chunks/cli-D2MUUBEX.js +0 -23
  186. package/dist/chunks/configuration-command-NR6JYIUD.js +0 -187
  187. package/dist/chunks/continual-37CE4LLJ.js +0 -803
  188. package/dist/chunks/core-commands-SWGIOZLW.js +0 -50
  189. package/dist/chunks/database-DEYUZDIM.js +0 -20
  190. package/dist/chunks/desktop-test-QOS7G5NE.js +0 -148
  191. package/dist/chunks/dist-AKYCQNNF.js +0 -187
  192. package/dist/chunks/extension-HJUJBQAD.js +0 -9378
  193. package/dist/chunks/help-J6PZ23IC.js +0 -67
  194. package/dist/chunks/opchat-ABX5YBAT.js +0 -169
  195. package/dist/chunks/organizations-CPNC47DO.js +0 -806
  196. package/dist/chunks/profile-Q3HB5MIO.js +0 -1136
  197. package/dist/chunks/project-agent-YHUBX4OR.js +0 -516
  198. package/dist/chunks/sandbox-command-YFL5QTWX.js +0 -1661
  199. package/dist/chunks/sandbox-template-Z6P7NTNF.js +0 -1655
  200. package/dist/chunks/src-7XEENEBI.js +0 -3628
  201. package/dist/chunks/src-KBBIV4NT.js +0 -56125
  202. package/dist/chunks/taskset-2TRZBRRT.js +0 -66
  203. package/dist/chunks/teams-bot-WD33NLH5.js +0 -146
  204. package/dist/chunks/training-4XH37UZB.js +0 -17
  205. package/dist/chunks/workspaces-WG2MH2WE.js +0 -99
  206. package/dist/web/assets/App-C9aGkxVg.js +0 -173
  207. package/dist/web/assets/AppDialog-CK6_lg8c.js +0 -1
  208. package/dist/web/assets/AppTerminalPanel-BKqgX4sd.js +0 -2
  209. package/dist/web/assets/GetStartedView-DVInkexN.js +0 -1
  210. package/dist/web/assets/LabModelVersionDetailPage-NaaPElmM.js +0 -1
  211. package/dist/web/assets/LabsRoute-BRR6x3SX.js +0 -2
  212. package/dist/web/assets/LabsRoute-CGFgymTX.css +0 -1
  213. package/dist/web/assets/MainChatThread-BfkjCZB9.js +0 -2
  214. package/dist/web/assets/MainPane-Gw-YK38n.js +0 -8
  215. package/dist/web/assets/RightChatPanelStack-BktRQ9wg.js +0 -1
  216. package/dist/web/assets/TeamChatView-BPWJbDf1.js +0 -3
  217. package/dist/web/assets/WorkspaceDiffPanel-Pg7GL0br.js +0 -14
  218. package/dist/web/assets/chat-file-links-CWLsRYvW.js +0 -1
  219. package/dist/web/assets/chevron-up--mNnEqha.js +0 -1
  220. package/dist/web/assets/index-BEPmTPIA.js +0 -1
@@ -0,0 +1,17 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{a as n}from"./chunk-FTQLQJQV.js";import{execFileSync as h}from"node:child_process";import{chmodSync as P,lstatSync as U}from"node:fs";var s=class extends Error{static{n(this,"PersistenceError")}issue;constructor(o,r){super(o.message,r),this.name="PersistenceError",this.issue=o}};function j(e,o){return e instanceof s?e.issue:{code:"STORAGE_UNAVAILABLE",path:o,message:"OpenPond could not access its storage.",action:"Check the folder permissions and available disk space, then retry."}}n(j,"persistenceIssue");function m(e){return e?.code==="ENOENT"}n(m,"isMissing");function A(e={}){let o={...process.env,...e};for(let r of Object.keys(o))r.toLowerCase()==="psmodulepath"&&delete o[r];return o}n(A,"windowsPowerShellEnvironment");var O=new Map,v=["$ErrorActionPreference='Stop'","$identity=[System.Security.Principal.WindowsIdentity]::GetCurrent().User","$acl=New-Object System.Security.AccessControl.DirectorySecurity","$acl.SetOwner($identity)","$acl.SetAccessRuleProtection($true,$false)","$rule=New-Object System.Security.AccessControl.FileSystemAccessRule($identity,'FullControl','ContainerInherit,ObjectInherit','None','Allow')","$acl.AddAccessRule($rule)","Set-Acl -LiteralPath $env:OPENPOND_PRIVATE_DIRECTORY -AclObject $acl"].join("; ");function u(e){if(process.platform!=="win32"){P(e,448);return}let o=U(e),r=`${o.dev}:${o.ino}:${o.birthtimeMs}`;if(O.get(e)!==r)try{h("powershell.exe",["-NoProfile","-NonInteractive","-Command",v],{env:A({OPENPOND_PRIVATE_DIRECTORY:e}),stdio:["ignore","ignore","pipe"],timeout:3e4,windowsHide:!0}),O.set(e,r)}catch(t){throw new s({code:"PRIVATE_STORAGE_UNAVAILABLE",path:e,message:"OpenPond could not restrict this storage folder to its owner.",action:"Use a local folder that supports private access controls, then retry."},{cause:t})}}n(u,"protectPrivateDirectory");import{lstatSync as g}from"node:fs";import R from"node:path";function f(e){let o=R.resolve(e);for(;;){try{let t=g(o),a=process.platform==="darwin"&&["/tmp","/var","/etc"].includes(o);if(t.isSymbolicLink()&&!a)throw new s({code:"UNSAFE_STORAGE_PATH",path:o,message:"A managed storage path passes through a symbolic link.",action:"Use the canonical local folder and keep managed subdirectories inside that home."})}catch(t){if(!m(t))throw t}let r=R.dirname(o);if(r===o)return;o=r}}n(f,"assertStorageAncestors");import{mkdirSync as C,chmodSync as x,existsSync as N,lstatSync as D}from"node:fs";import d from"node:path";import{DatabaseSync as M}from"node:sqlite";import{AsyncLocalStorage as _}from"node:async_hooks";import X from"node:path";var I=new _,S=n(()=>I.getStore(),"currentOpenPondHome");function w(e,o){return I.run(X.resolve(e),o)}n(w,"withOpenPondHome");function ne(e,o){return Object.fromEntries(Object.entries(o).map(([r,t])=>[r,typeof t=="function"?(...a)=>w(e,()=>t(...a)):t]))}n(ne,"bindHomeCallbacks");import l from"node:os";import i from"node:path";function F(e={}){let o=e.env??process.env,r=e.home?.trim()||(e.env?void 0:S())||o.OPENPOND_HOME?.trim();if(r)return i.resolve(y(r));for(let t of["OPENPOND_APP_HOME","OPENPOND_CONFIG_DIR"])if(o[t]?.trim())throw new s({code:"RETIRED_HOME_OPTION",path:t,message:`${t} has been replaced by OPENPOND_HOME.`,action:"Set OPENPOND_HOME to the destination home. Use openpond config migrate --source-app-home to import a previous installation."});return i.join(l.homedir(),e.channel==="nightly"?".openpond-nightly":".openpond")}n(F,"resolveOpenPondHome");function y(e){return e==="~"?l.homedir():e.startsWith("~/")?i.join(l.homedir(),e.slice(2)):e}n(y,"expandHome");function T(e=F()){let o=i.resolve(e);return{home:o,config:i.join(o,"config.toml"),marker:i.join(o,"storage.json"),database:i.join(o,"state","state.sqlite"),cache:i.join(o,"cache","cache.sqlite"),credentials:i.join(o,"secrets","credentials.json"),key:i.join(o,"secrets","credentials.key"),token:i.join(o,"secrets","server-token"),runtime:i.join(o,"runtime"),library:i.join(o,"library"),instructions:i.join(o,"instructions")}}n(T,"storagePaths");function pe(e,o,r=!0){return i.resolve(o,r?y(e):e)}n(pe,"resolveConfigPath");var b=`
3
+ CREATE TABLE IF NOT EXISTS scaffold_registrations (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
4
+ CREATE TABLE IF NOT EXISTS account_sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
5
+ CREATE TABLE IF NOT EXISTS account_selection (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
6
+ CREATE TABLE IF NOT EXISTS profile_installations (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
7
+ CREATE TABLE IF NOT EXISTS extension_installations (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
8
+ CREATE TABLE IF NOT EXISTS client_preferences (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
9
+ CREATE TABLE IF NOT EXISTS saved_local_projects (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
10
+ CREATE TABLE IF NOT EXISTS codex_sidebar_state (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
11
+ CREATE TABLE IF NOT EXISTS browser_tab_state (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
12
+ CREATE TABLE IF NOT EXISTS project_trust (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
13
+ CREATE TABLE IF NOT EXISTS refiner_bindings (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
14
+ CREATE TABLE IF NOT EXISTS refiner_transitions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
15
+ CREATE TABLE IF NOT EXISTS config_run_snapshots (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
16
+ CREATE TABLE IF NOT EXISTS provider_connection_state (id TEXT PRIMARY KEY, payload TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 1);
17
+ `;function Y(e,o=!1){if(f(d.dirname(e)),o||(C(d.dirname(e),{recursive:!0,mode:448}),u(d.dirname(e))),N(e)&&D(e).isSymbolicLink())throw new s({code:"UNSAFE_STORAGE_PATH",path:e,message:"Storage database cannot be a symbolic link.",action:"Choose a regular local database file."});let r=new M(e,{readOnly:o});try{return r.exec("PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON;"),o||(r.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;"),process.platform!=="win32"&&x(e,384)),r}catch(t){throw r.close(),t}}n(Y,"openStorageDatabase");function p(e,o){let r=Y(T(e).database);try{return r.exec(b),o(r)}finally{r.close()}}n(p,"withLocalDatabase");function fe(e,o,r){return N(T(e).database)?p(e,t=>{let a=t.prepare(`SELECT payload, revision FROM ${o} WHERE id = ?`).get(r);return a?{value:JSON.parse(a.payload),revision:a.revision}:null}):null}n(fe,"getLocalRecord");function Ie(e,o){return N(T(e).database)?p(e,r=>Object.fromEntries(r.prepare(`SELECT id, payload, revision FROM ${o} ORDER BY id`).all().map(t=>[t.id,{value:JSON.parse(t.payload),revision:t.revision}]))):{}}n(Ie,"listLocalRecords");function Se(e,o,r,t,a){return p(e,c=>{c.exec("BEGIN IMMEDIATE");try{let E=c.prepare(`SELECT revision FROM ${o} WHERE id = ?`).get(r);if(a!==void 0&&a!==(E?.revision??null))throw new s({code:"STATE_CONFLICT",path:o,message:"This record changed while it was being edited.",action:"Reload the latest record and retry."});let L=(E?.revision??0)+1;return c.prepare(`INSERT INTO ${o} (id, payload, revision) VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload, revision=excluded.revision`).run(r,JSON.stringify(t),L),c.exec("COMMIT"),L}catch(E){throw c.exec("ROLLBACK"),E}})}n(Se,"putLocalRecord");function ye(e,o,r){p(e,t=>{t.prepare(`DELETE FROM ${o} WHERE id = ?`).run(r)})}n(ye,"deleteLocalRecord");export{w as a,ne as b,s as c,j as d,m as e,F as f,y as g,T as h,pe as i,A as j,u as k,f as l,b as m,Y as n,p as o,fe as p,Ie as q,Se as r,ye as s};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{b as t}from"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";var O=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),v=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function E(n){let a=typeof n=="string"?new TextEncoder().encode(n):n,r=Math.ceil((a.byteLength+9)/64)*64,d=new Uint8Array(r);d.set(a),d[a.byteLength]=128;let b=a.byteLength*8,A=new DataView(d.buffer);A.setUint32(r-8,Math.floor(b/4294967296),!1),A.setUint32(r-4,b>>>0,!1);let e=new Uint32Array(O),f=new Uint32Array(64);for(let u=0;u<r;u+=64){for(let o=0;o<16;o+=1)f[o]=A.getUint32(u+o*4,!1);for(let o=16;o<64;o+=1){let g=f[o-15],S=f[o-2],T=i(g,7)^i(g,18)^g>>>3,w=i(S,17)^i(S,19)^S>>>10;f[o]=f[o-16]+T+f[o-7]+w>>>0}let s=e[0],p=e[1],h=e[2],_=e[3],x=e[4],y=e[5],R=e[6],H=e[7];for(let o=0;o<64;o+=1){let g=x&y^~x&R,S=s&p^s&h^p&h,T=i(s,2)^i(s,13)^i(s,22),w=i(x,6)^i(x,11)^i(x,25),j=H+w+g+v[o]+f[o]>>>0,L=T+S>>>0;H=R,R=y,y=x,x=_+j>>>0,_=h,h=p,p=s,s=j+L>>>0}e[0]=e[0]+s>>>0,e[1]=e[1]+p>>>0,e[2]=e[2]+h>>>0,e[3]=e[3]+_>>>0,e[4]=e[4]+x>>>0,e[5]=e[5]+y>>>0,e[6]=e[6]+R>>>0,e[7]=e[7]+H>>>0}return Array.from(e,u=>u.toString(16).padStart(8,"0")).join("")}c(E,"sha256Hex");function i(n,a){return n>>>a|n<<32-a}c(i,"rotateRight");var z=2e3,U=25e7,l=t.string().trim().min(1).max(240),m=t.string().regex(/^[a-f0-9]{64}$/),Y=t.string().datetime({offset:!0}),q=t.record(t.string(),t.unknown()).default({}),M=t.object({id:l,contentHash:m}).strict(),F=M.extend({revision:t.number().int().positive()}).strict(),W=t.object({id:l,path:t.string().trim().min(1).max(z).refine(N),contentHash:m,sizeBytes:t.number().int().nonnegative().max(U),mediaType:t.string().trim().min(1).max(200),visibility:t.enum(["policy","verifier","host_private"])}).strict(),G=t.object({id:l,contentHash:m,mediaType:t.string().trim().min(1).max(200).nullable().default(null),sizeBytes:t.number().int().nonnegative().max(U).nullable().default(null)}).strict(),K=t.enum(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function B(n){return`${JSON.stringify(I(n),null,2)}
3
+ `}c(B,"canonicalJson");function C(n){return E(n)}c(C,"sha256");function P(n){return C(B(n))}c(P,"contentHash");function Q(n,a){let{contentHash:r,...d}=n,b=P(d);if(r!==b)throw new Error(`${a} contentHash is ${r}; expected ${b}.`)}c(Q,"assertContentHash");function N(n){let a=n.replaceAll("\\","/");return!a||a.startsWith("/")||a.includes("\0")?!1:!a.split("/").some(r=>!r||r==="."||r==="..")}c(N,"safeRelativePath");function I(n){return Array.isArray(n)?n.map(I):!n||typeof n!="object"?n:Object.fromEntries(Object.entries(n).sort(([a],[r])=>a.localeCompare(r)).map(([a,r])=>[a,I(r)]))}c(I,"sortValue");var ae=t.object({provider:l,model:l,revision:t.string().trim().min(1).max(500).nullable().default(null),artifactHash:m.nullable().default(null),tokenizerRevision:t.string().trim().min(1).max(500).nullable().default(null),chatTemplateHash:m.nullable().default(null)}).strict(),$=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],D=t.enum($),oe=t.object({providerId:D,modelId:t.string().trim().min(1).max(300)});export{l as a,m as b,Y as c,q as d,M as e,F as f,W as g,G as h,K as i,B as j,C as k,P as l,Q as m,ae as n,$ as o,D as p,oe as q};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{c as O}from"./chunk-GLUWATL5.js";import{a as r}from"./chunk-FTQLQJQV.js";import{randomUUID as P}from"node:crypto";function g(e){let t=p(e);if(!t)throw new Error("apiBaseUrl is required");return t}r(g,"normalizeApiBaseUrl");function x(e){return e.replace(/\/+$/,"")}r(x,"trimTrailingSlashes");function p(e){let t=x(e?.trim()??"");return t?(t=t.replace(/\/chat\/completions$/i,"").replace(/\/models(?:\/[^/]+)?$/i,""),t.endsWith("/opchat/v1")?t:t.endsWith("/opchat")?`${t}/v1`:(t.endsWith("/v1")&&(t=t.slice(0,-3)),`${x(t)}/opchat/v1`)):null}r(p,"normalizeOptionalOpChatApiBaseUrl");function M(e={}){let t=e.env??(typeof process<"u"?process.env:{}),n=p(e.opChatApiBaseUrl)??p(t.OPENPOND_OPCHAT_API_URL);if(n)return n;let o=p(e.chatApiBaseUrl)??p(t.OPENPOND_CHAT_API_URL)??p(t.OPENPOND_GATEWAY_URL);return o||(p(e.apiBaseUrl)??p(t.OPENPOND_API_URL)??O)}r(M,"resolveOpChatApiBaseUrl");function W(e={}){return M(e)}r(W,"resolveHostedChatApiBaseUrl");function $(e){let t=e.trim();if(!t)throw new Error("OpenPond API key is required");return t}r($,"requireToken");function h(e,t,n){let o=new Headers;return o.set("Authorization",`Bearer ${$(e)}`),o.set("Content-Type","application/json"),o.set("Accept",t),o.set("x-openpond-client","openpond-code"),o.set("x-openpond-request-id",n||P()),o}r(h,"hostedHeaders");async function f(e){let t=await e.text().catch(()=>"");if(!t)return e.statusText||`HTTP ${e.status}`;try{let n=JSON.parse(t),o=typeof n.error=="string"||n.error&&typeof n.error=="object"&&!Array.isArray(n.error)?n.error:null,s=typeof n.code=="string"?n.code:o&&typeof o!="string"&&typeof o.code=="string"?o.code:null,i=typeof n.message=="string"?n.message:o&&typeof o!="string"&&typeof o.message=="string"?o.message:null,a=typeof o=="string"?o:o&&typeof o.type=="string"?o.type:null;return[s,a,i].filter(Boolean).join(": ")||t}catch{return t}}r(f,"readError");function b(e,t){let n={model:e.model,messages:e.messages,stream:t};typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.maxTokens=="number"&&(n.max_tokens=e.maxTokens),e.tools&&(n.tools=e.tools);let o=e.toolChoice??e.tool_choice;return o!==void 0&&(n.tool_choice=o),e.metadata&&(n.metadata=e.metadata),n}r(b,"buildHostedChatBody");async function _(e){let n=`${g(e.apiBaseUrl)}/models`,o=await fetch(n,{method:"GET",headers:h(e.token,"application/json"),signal:e.signal});if(!o.ok)throw new Error(`Hosted model list failed: ${o.status} ${await f(o)}`);return await o.json()}r(_,"listOpChatModels");async function C(e){let n=`${g(e.apiBaseUrl)}/models/${encodeURIComponent(e.model)}`,o=await fetch(n,{method:"GET",headers:h(e.token,"application/json"),signal:e.signal});if(!o.ok)throw new Error(`Hosted model lookup failed: ${o.status} ${await f(o)}`);return await o.json()}r(C,"getOpChatModel");var F=_;async function A(e){let n=`${g(e.apiBaseUrl)}/providers`,o=await fetch(n,{method:"GET",headers:h(e.token,"application/json"),signal:e.signal});if(!o.ok)throw new Error(`Hosted provider list failed: ${o.status} ${await f(o)}`);return await o.json()}r(A,"listOpChatProviders");async function Y(e){let n=`${g(e.apiBaseUrl)}/providers/${encodeURIComponent(e.provider)}`,o=await fetch(n,{method:"GET",headers:h(e.token,"application/json"),signal:e.signal});if(!o.ok)throw new Error(`Hosted provider lookup failed: ${o.status} ${await f(o)}`);return await o.json()}r(Y,"getOpChatProvider");var V=A;async function k(e){let n=`${g(e.apiBaseUrl)}/chat/completions`,o=await fetch(n,{method:"POST",headers:h(e.token,"application/json",e.requestId),body:JSON.stringify(b(e,!1)),signal:e.signal});if(!o.ok)throw new Error(`Hosted chat failed: ${o.status} ${await f(o)}`);return await o.json()}r(k,"sendHostedChatTurn");async function*E(e,t){let n=e.getReader(),o=new TextDecoder,s="",i=r(()=>t?.reason instanceof Error?t.reason:new Error("hosted_chat_aborted"),"readAbortError");try{for(;;){if(t?.aborted)throw i();let a=await n.read();if(a.done)break;s+=o.decode(a.value,{stream:!0});let l=s.split(`
3
+ `);s=l.pop()||"";for(let d of l){let c=d.trim();if(!c.startsWith("data:"))continue;let u=c.slice(5).trim();if(u){if(u==="[DONE]")return;yield JSON.parse(u)}}}}finally{try{n.releaseLock()}catch{}}}r(E,"parseOpenAISSE");async function*R(e){let n=`${g(e.apiBaseUrl)}/chat/completions`,o=await fetch(n,{method:"POST",headers:h(e.token,"text/event-stream",e.requestId),body:JSON.stringify(b(e,!0)),signal:e.signal});if(!o.ok||!o.body)throw new Error(`Hosted chat stream failed: ${o.status} ${await f(o)}`);for await(let s of E(o.body,e.signal)){let i=s;if(i.error)throw new Error(i.error.message||"Hosted chat stream error");i.usage&&(yield{type:"usage",usage:i.usage,raw:s});let a=i.choices?.[0];if(!a)continue;let l=a.delta?.content;l&&(yield{type:"text_delta",text:l,raw:s});let d=a.delta?.reasoning_content;d&&(yield{type:"reasoning_delta",text:d,raw:s});let c=a.delta?.tool_calls;Array.isArray(c)&&c.length>0&&(yield{type:"tool_call_delta",toolCalls:c,raw:s}),a.finish_reason!==void 0&&a.finish_reason!==null&&(yield{type:"finish",finishReason:a.finish_reason,raw:s})}}r(R,"streamHostedChatTurn");var q="openpond-chat",I="deepseek-v4-flash",D="not-a-real-opchat-model";async function Z(e){let t=e.defaultModel||q,n=e.compatibilityModel||I,o=e.invalidModel||D,s=e.log||(()=>{});s(`opchat base: ${e.apiBaseUrl}`);let a=(await _({apiBaseUrl:e.apiBaseUrl,token:e.token})).data.map(T=>T.id);v(a,t),v(a,n),s(`models: ${a.join(", ")}`);let l=await C({apiBaseUrl:e.apiBaseUrl,token:e.token,model:t}),d=await C({apiBaseUrl:e.apiBaseUrl,token:e.token,model:n}),c=await N({apiBaseUrl:e.apiBaseUrl,token:e.token,model:o});s(`invalid model error: ${c}`);let u=H(t,await k({apiBaseUrl:e.apiBaseUrl,token:e.token,model:t,messages:[{role:"user",content:"Reply with a short plain sentence confirming OpChat works."}],metadata:{source:"openpond-code-opchat-smoke",mode:"non_stream"}}));B(u,`${t} non-streaming response`),s(`${t} non-stream: id=${u.id??"unknown"} usage=${U(u.usage)}`);let m=e.skipStream?void 0:await j({apiBaseUrl:e.apiBaseUrl,token:e.token,model:t});m&&s(`${t} stream: chunks=${m.textDeltaCount} finish=${m.finishReason??"none"} usage=${U(m.usage)}`);let w=H(n,await k({apiBaseUrl:e.apiBaseUrl,token:e.token,model:n,messages:[{role:"user",content:"Reply with one short sentence confirming compatibility."}],metadata:{source:"openpond-code-opchat-smoke",mode:"compatibility_non_stream"}}));B(w,`${n} non-streaming response`),s(`${n} non-stream: id=${w.id??"unknown"} usage=${U(w.usage)}`);let y=e.skipTool?void 0:await L({apiBaseUrl:e.apiBaseUrl,token:e.token,model:t});return y&&s(`${t} tool: calls=${y.toolCallCount} names=${y.toolNames.join(",")}`),{apiBaseUrl:e.apiBaseUrl,listedModels:a,defaultModel:t,compatibilityModel:n,modelLookups:[l.id,d.id],invalidModelError:c,nonStreaming:u,compatibilityNonStreaming:w,...m?{streaming:m}:{},...y?{toolCalling:y}:{}}}r(Z,"runOpChatSmoke");async function N(e){try{await C(e)}catch(t){return t instanceof Error?t.message:String(t)}throw new Error(`expected invalid model ${e.model} to fail`)}r(N,"expectInvalidModel");async function j(e){let t=Date.now(),n=null,o="",s=0,i=null,a=null;for await(let l of R({apiBaseUrl:e.apiBaseUrl,token:e.token,model:e.model,messages:[{role:"user",content:"Reply with a short streamed sentence."}],metadata:{source:"openpond-code-opchat-smoke",mode:"stream"}}))l.type==="text_delta"?(n??=Date.now(),o+=l.text,s+=1):l.type==="finish"?i=l.finishReason:l.type==="usage"&&(a=l.usage);if(s===0||!o.trim())throw new Error("streaming response did not emit text deltas");if(!i)throw new Error("streaming response did not emit a terminal finish marker");return{model:e.model,textDeltaCount:s,textPreview:S(o),firstTextMs:n===null?null:n-t,totalMs:Date.now()-t,finishReason:i,usage:a}}r(j,"runStreamSmoke");async function L(e){let t=[{type:"function",function:{name:"get_current_weather",description:"Get the current weather for a city.",parameters:{type:"object",properties:{location:{type:"string",description:"City and region, for example Boston, MA."}},required:["location"]}}}],n=[{role:"user",content:"Use the get_current_weather tool for Boston, then wait for the result."}],s=(await k({apiBaseUrl:e.apiBaseUrl,token:e.token,model:e.model,messages:n,tools:t,toolChoice:"auto",metadata:{source:"openpond-code-opchat-smoke",mode:"tool_call"}})).choices?.[0],i=s?.message?.tool_calls??[];if(i.length===0)throw new Error("tool smoke did not receive an assistant tool call");let a=G(i),l=H(e.model,await k({apiBaseUrl:e.apiBaseUrl,token:e.token,model:e.model,messages:[...n,{role:"assistant",content:s?.message?.content??null,tool_calls:i},...a],metadata:{source:"openpond-code-opchat-smoke",mode:"tool_result"}}));return B(l,"tool follow-up response"),{model:e.model,toolCallCount:i.length,toolNames:i.map(d=>d.function?.name).filter(d=>!!d),finishReason:s?.finish_reason??null,followUp:l}}r(L,"runToolSmoke");function G(e){return e.map((t,n)=>{if(!t.id)throw new Error(`tool call ${n} is missing an id`);return{role:"tool",tool_call_id:t.id,content:JSON.stringify({location:"Boston, MA",temperature:"58 F",conditions:"clear"})}})}r(G,"buildToolResultMessages");function H(e,t){let n=t.choices?.[0];return{model:e,id:t.id??null,finishReason:n?.finish_reason??null,textPreview:S(n?.message?.content??""),usage:t.usage??null}}r(H,"summarizeCompletion");function v(e,t){if(!e.includes(t))throw new Error(`model list did not include ${t}`)}r(v,"requireModel");function B(e,t){if(!e.textPreview.trim())throw new Error(`${t} did not include assistant text`)}r(B,"requireText");function S(e,t=120){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}...`}r(S,"previewText");function U(e){return e?String(e.total_tokens??e.input_tokens??e.output_tokens??"unknown"):"none"}r(U,"formatUsage");export{M as a,W as b,_ as c,C as d,F as e,A as f,Y as g,V as h,k as i,R as j,Z as k};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{e as g,g as $,h as O,i as C}from"./chunk-T5XCPX4P.js";import{a as w}from"./chunk-3M53YXEI.js";import{a as r}from"./chunk-FTQLQJQV.js";var L=Symbol("openpondCliOptionValues"),a=class extends Error{static{r(this,"CliUsageError")}exitCode=2;constructor(t){super(t),this.name="CliUsageError"}},K=new Set(["maxOutputBytes","timeoutSec"]);function k(n){let t=[...n],o="",i={},e={},u=[];for(;t.length>0;){let s=t.shift();if(s==="--"){u.push(...t);break}if(s.startsWith("--")){let f=s.indexOf("="),c=f>=0?s.slice(2,f):s.slice(2),p=N(c),d=f>=0?s.slice(f+1):P(t,p,o);h(i,e,p,d,o)}else _(s)?y(s,t,i,e):o?u.push(s):o=s}return Object.defineProperty(i,L,{value:e,enumerable:!1,configurable:!1,writable:!1}),V(o,i),{command:o,options:i,rest:u}}r(k,"parseArgs");function N(n){return n.replace(/-([a-z])/g,(t,o)=>o.toUpperCase())}r(N,"normalizeCliOptionKey");function _(n){return/^-[^-].*/.test(n)&&!S(n)}r(_,"isShortOptionToken");function y(n,t,o,i){let e=n.slice(1);if(!e)return;let u=e.indexOf("="),s=u>=0?e.slice(0,u):e,f=u>=0?e.slice(u+1):null;if(s.length!==1){for(let d of s){let m=g[d];if(!m)throw new a(`unknown short option -${d}`);if(C(m)!=="boolean")throw new a(`short option -${d} requires its own value`);h(o,i,m,"true")}return}let c=g[s];if(!c)throw new a(`unknown short option -${s}`);let p=f??P(t,c);h(o,i,c,p)}r(y,"parseShortOptionToken");function P(n,t,o){let i=I(t,o);if(i==="boolean")return n[0]&&x(n[0])?n.shift():"true";if(i){let e=n.shift();if(e===void 0||R(e)&&!S(e))throw e!==void 0&&n.unshift(e),new a(`${l(t)} must be ${b(i)}`);return e}return n[0]&&!n[0].startsWith("--")?n.shift():"true"}r(P,"readOptionValue");function h(n,t,o,i,e){T(o,i,e),n[o]=i,(t[o]??=[]).push(i)}r(h,"setParsedOption");function T(n,t,o){let i=I(n,o);if(i){if(i==="boolean"){if(!x(t))throw new a(`${l(n)} must be a boolean`);return}if(t.trim().length===0||t==="true")throw new a(`${l(n)} must be ${b(i)}`);if(i==="number"||i==="integer"){let e=Number(t);if(!Number.isFinite(e))throw new a(`${l(n)} must be ${b(i)}`);if(i==="integer"&&!Number.isInteger(e))throw new a(`${l(n)} must be an integer`);if(i==="integer"&&K.has(n)&&e<=0)throw new a(`${l(n)} must be a positive integer`);return}if(i==="json")try{w(t,l(n))}catch(e){throw new a(e instanceof Error?e.message:String(e))}}}r(T,"validateParsedOptionValue");function I(n,t){return t?O(t,n):C(n)}r(I,"typedOptionKind");function l(n){return n.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}r(l,"cliOptionLabel");function E(n){return n==="json"?"JSON value":n}r(E,"optionKindLabel");function b(n){let t=E(n);return/^[aeiou]/i.test(t)?`an ${t}`:`a ${t}`}r(b,"optionKindPhrase");function x(n){return/^(true|false|1|0|yes|no)$/i.test(n)}r(x,"isBooleanLiteral");function R(n){return n.startsWith("-")&&n!=="-"}r(R,"isOptionLike");function S(n){return/^-\d+(?:\.\d+)?$/.test(n)}r(S,"isNegativeNumber");function V(n,t){let o=n?$(n):null;for(let i of Object.keys(t))if(!O(n,i)){let e=l(i),u=o?` for ${o.name}`:"";throw new a(`unknown option --${e}${u}`)}}r(V,"validateCommandOptions");export{a,k as b};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{a as n}from"./chunk-FTQLQJQV.js";var y={JS_EVAL_TYPE_GLOBAL:0,JS_EVAL_TYPE_MODULE:1,JS_EVAL_TYPE_DIRECT:2,JS_EVAL_TYPE_INDIRECT:3,JS_EVAL_TYPE_MASK:3,JS_EVAL_FLAG_STRICT:8,JS_EVAL_FLAG_STRIP:16,JS_EVAL_FLAG_COMPILE_ONLY:32,JS_EVAL_FLAG_BACKTRACE_BARRIER:64},Q={BaseObjects:1,Date:2,Eval:4,StringNormalize:8,RegExp:16,RegExpCompiler:32,JSON:64,Proxy:128,MapSet:256,TypedArrays:512,Promise:1024,BigInt:2048,BigFloat:4096,BigDecimal:8192,OperatorOverloading:16384,BignumExt:32768},P={Pending:0,Fulfilled:1,Rejected:2},v={JS_GPN_STRING_MASK:1,JS_GPN_SYMBOL_MASK:2,JS_GPN_PRIVATE_MASK:4,JS_GPN_ENUM_ONLY:16,JS_GPN_SET_ENUM:32,QTS_GPN_NUMBER_MASK:64,QTS_STANDARD_COMPLIANT_NUMBER:128},b={IsStrictlyEqual:0,IsSameValue:1,IsSameValueZero:2};var re=Object.defineProperty,ie=n((e,t)=>{for(var r in t)re(e,r,{get:t[r],enumerable:!0})},"__export"),C=!1;function x(...e){C&&console.log("quickjs-emscripten:",...e)}n(x,"debugLog");var se={};ie(se,{QuickJSAsyncifyError:n(()=>$,"QuickJSAsyncifyError"),QuickJSAsyncifySuspended:n(()=>z,"QuickJSAsyncifySuspended"),QuickJSEmptyGetOwnPropertyNames:n(()=>q,"QuickJSEmptyGetOwnPropertyNames"),QuickJSEmscriptenModuleError:n(()=>oe,"QuickJSEmscriptenModuleError"),QuickJSHostRefInvalid:n(()=>f,"QuickJSHostRefInvalid"),QuickJSHostRefRangeExceeded:n(()=>W,"QuickJSHostRefRangeExceeded"),QuickJSMemoryLeakDetected:n(()=>ne,"QuickJSMemoryLeakDetected"),QuickJSNotImplemented:n(()=>D,"QuickJSNotImplemented"),QuickJSPromisePending:n(()=>Y,"QuickJSPromisePending"),QuickJSUnknownIntrinsic:n(()=>K,"QuickJSUnknownIntrinsic"),QuickJSUnwrapError:n(()=>R,"QuickJSUnwrapError"),QuickJSUseAfterFree:n(()=>k,"QuickJSUseAfterFree"),QuickJSWrongOwner:n(()=>U,"QuickJSWrongOwner")});var R=class extends Error{static{n(this,"QuickJSUnwrapError")}constructor(e,t){let r=typeof e=="object"&&e&&"message"in e?String(e.message):String(e);super(r),this.cause=e,this.context=t,this.name="QuickJSUnwrapError"}},U=class extends Error{static{n(this,"QuickJSWrongOwner")}constructor(){super(...arguments),this.name="QuickJSWrongOwner"}},k=class extends Error{static{n(this,"QuickJSUseAfterFree")}constructor(){super(...arguments),this.name="QuickJSUseAfterFree"}},D=class extends Error{static{n(this,"QuickJSNotImplemented")}constructor(){super(...arguments),this.name="QuickJSNotImplemented"}},$=class extends Error{static{n(this,"QuickJSAsyncifyError")}constructor(){super(...arguments),this.name="QuickJSAsyncifyError"}},z=class extends Error{static{n(this,"QuickJSAsyncifySuspended")}constructor(){super(...arguments),this.name="QuickJSAsyncifySuspended"}},ne=class extends Error{static{n(this,"QuickJSMemoryLeakDetected")}constructor(){super(...arguments),this.name="QuickJSMemoryLeakDetected"}},oe=class extends Error{static{n(this,"QuickJSEmscriptenModuleError")}constructor(){super(...arguments),this.name="QuickJSEmscriptenModuleError"}},K=class extends TypeError{static{n(this,"QuickJSUnknownIntrinsic")}constructor(){super(...arguments),this.name="QuickJSUnknownIntrinsic"}},Y=class extends Error{static{n(this,"QuickJSPromisePending")}constructor(){super(...arguments),this.name="QuickJSPromisePending"}},q=class extends Error{static{n(this,"QuickJSEmptyGetOwnPropertyNames")}constructor(){super(...arguments),this.name="QuickJSEmptyGetOwnPropertyNames"}},W=class extends Error{static{n(this,"QuickJSHostRefRangeExceeded")}constructor(){super(...arguments),this.name="QuickJSHostRefRangeExceeded"}},f=class extends Error{static{n(this,"QuickJSHostRefInvalid")}constructor(){super(...arguments),this.name="QuickJSHostRefInvalid"}};function*Z(e){return yield e}n(Z,"awaitYield");function ue(e){return Z(L(e))}n(ue,"awaitYieldOf");var I=Z;I.of=ue;function O(e,t){return(...r)=>{let i=t.call(e,I,...r);return L(i)}}n(O,"maybeAsyncFn");function ae(e,t){let r=t.call(e,I);return L(r)}n(ae,"maybeAsync");function L(e){function t(r){return r.done?r.value:r.value instanceof Promise?r.value.then(i=>t(e.next(i)),i=>t(e.throw(i))):t(e.next(r.value))}return n(t,"handleNextStep"),t(e.next())}n(L,"awaitEachYieldedPromise");var d=class{static{n(this,"UsingDisposable")}[Symbol.dispose](){return this.dispose()}},J=Symbol.dispose??Symbol.for("Symbol.dispose"),V=d.prototype;V[J]||(V[J]=function(){return this.dispose()});var c=class X extends d{static{n(this,"_Lifetime")}constructor(t,r,i,s){super(),this._value=t,this.copier=r,this.disposer=i,this._owner=s,this._alive=!0,this._constructorStack=C?new Error("Lifetime constructed").stack:void 0}get alive(){return this._alive}get value(){return this.assertAlive(),this._value}get owner(){return this._owner}get dupable(){return!!this.copier}dup(){if(this.assertAlive(),!this.copier)throw new Error("Non-dupable lifetime");return new X(this.copier(this._value),this.copier,this.disposer,this._owner)}consume(t){this.assertAlive();let r=t(this);return this.dispose(),r}map(t){return this.assertAlive(),t(this)}tap(t){return t(this),this}dispose(){this.assertAlive(),this.disposer&&this.disposer(this._value),this._alive=!1}assertAlive(){if(!this.alive)throw this._constructorStack?new k(`Lifetime not alive
3
+ ${this._constructorStack}
4
+ Lifetime used`):new k("Lifetime not alive")}},S=class extends c{static{n(this,"StaticLifetime")}constructor(e,t){super(e,void 0,void 0,t)}get dupable(){return!0}dup(){return this}dispose(){}},F=class extends c{static{n(this,"WeakLifetime")}constructor(e,t,r,i){super(e,t,r,i)}dispose(){this._alive=!1}};function H(e,t){let r;try{e.dispose()}catch(i){r=i}if(t&&r)throw Object.assign(t,{message:`${t.message}
5
+ Then, failed to dispose scope: ${r.message}`,disposeError:r}),t;if(t||r)throw t||r}n(H,"scopeFinally");var m=class E extends d{static{n(this,"_Scope")}constructor(){super(...arguments),this._disposables=new c(new Set),this.manage=t=>(this._disposables.value.add(t),t)}static withScope(t){let r=new E,i;try{return t(r)}catch(s){throw i=s,s}finally{H(r,i)}}static withScopeMaybeAsync(t,r){return ae(void 0,function*(i){let s=new E,o;try{return yield*i.of(r.call(t,i,s))}catch(a){throw o=a,a}finally{H(s,o)}})}static async withScopeAsync(t){let r=new E,i;try{return await t(r)}catch(s){throw i=s,s}finally{H(r,i)}}get alive(){return this._disposables.alive}dispose(){let t=Array.from(this._disposables.value.values()).reverse();for(let r of t)r.alive&&r.dispose();this._disposables.dispose()}};function le(e){let t=e?Array.from(e):[];function r(){return t.forEach(s=>s.alive?s.dispose():void 0)}n(r,"disposeAlive");function i(){return t.some(s=>s.alive)}return n(i,"someIsAlive"),Object.defineProperty(t,J,{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"dispose",{configurable:!0,enumerable:!1,value:r}),Object.defineProperty(t,"alive",{configurable:!0,enumerable:!1,get:i}),t}n(le,"createDisposableArray");function A(e){return!!(e&&(typeof e=="object"||typeof e=="function")&&"alive"in e&&typeof e.alive=="boolean"&&"dispose"in e&&typeof e.dispose=="function")}n(A,"isDisposable");var N=class ee extends d{static{n(this,"_AbstractDisposableResult")}static success(t){return new he(t)}static fail(t,r){return new ce(t,r)}static is(t){return t instanceof ee}},he=class extends N{static{n(this,"DisposableSuccess")}constructor(e){super(),this.value=e}get alive(){return A(this.value)?this.value.alive:!0}dispose(){A(this.value)&&this.value.dispose()}unwrap(){return this.value}unwrapOr(e){return this.value}},ce=class extends N{static{n(this,"DisposableFail")}constructor(e,t){super(),this.error=e,this.onUnwrap=t}get alive(){return A(this.error)?this.error.alive:!0}dispose(){A(this.error)&&this.error.dispose()}unwrap(){throw this.onUnwrap(this),this.error}unwrapOr(e){return e}},g=N,me=class extends d{static{n(this,"QuickJSDeferredPromise")}constructor(e){super(),this.resolve=t=>{this.resolveHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.resolveHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.reject=t=>{this.rejectHandle.alive&&(this.context.unwrapResult(this.context.callFunction(this.rejectHandle,this.context.undefined,t||this.context.undefined)).dispose(),this.disposeResolvers(),this.onSettled())},this.dispose=()=>{this.handle.alive&&this.handle.dispose(),this.disposeResolvers()},this.context=e.context,this.owner=e.context.runtime,this.handle=e.promiseHandle,this.settled=new Promise(t=>{this.onSettled=t}),this.resolveHandle=e.resolveHandle,this.rejectHandle=e.rejectHandle}get alive(){return this.handle.alive||this.resolveHandle.alive||this.rejectHandle.alive}disposeResolvers(){this.resolveHandle.alive&&this.resolveHandle.dispose(),this.rejectHandle.alive&&this.rejectHandle.dispose()}},te=class{static{n(this,"ModuleMemory")}constructor(e){this.module=e}toPointerArray(e){let t=new Int32Array(e.map(s=>s.value)),r=t.length*t.BYTES_PER_ELEMENT,i=this.module._malloc(r);return new Uint8Array(this.module.HEAPU8.buffer,i,r).set(new Uint8Array(t.buffer)),new c(i,void 0,s=>this.module._free(s))}newTypedArray(e,t){let r=new e(new Array(t).fill(0)),i=r.length*r.BYTES_PER_ELEMENT,s=this.module._malloc(i),o=new e(this.module.HEAPU8.buffer,s,t);return o.set(r),new c({typedArray:o,ptr:s},void 0,a=>this.module._free(a.ptr))}newMutablePointerArray(e){return this.newTypedArray(Int32Array,e)}newHeapCharPointer(e){let t=this.module.lengthBytesUTF8(e),r=t+1,i=this.module._malloc(r);return this.module.stringToUTF8(e,i,r),new c({ptr:i,strlen:t},void 0,s=>this.module._free(s.ptr))}newHeapBufferPointer(e){let t=e.byteLength,r=this.module._malloc(t);return this.module.HEAPU8.set(e,r),new c({pointer:r,numBytes:t},void 0,i=>this.module._free(i.pointer))}consumeHeapCharPointer(e){let t=this.module.UTF8ToString(e);return this.module._free(e),t}};var Me=Object.freeze({BaseObjects:!0,Date:!0,Eval:!0,StringNormalize:!0,RegExp:!0,JSON:!0,Proxy:!0,MapSet:!0,TypedArrays:!0,Promise:!0});function de(e){if(!e)return 0;let t=0;for(let[r,i]of Object.entries(e)){if(!(r in Q))throw new K(r);i&&(t|=Q[r])}return t}n(de,"intrinsicsToFlags");function fe(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{type:t,strict:r,strip:i,compileOnly:s,backtraceBarrier:o}=e,a=0;return t==="global"&&(a|=y.JS_EVAL_TYPE_GLOBAL),t==="module"&&(a|=y.JS_EVAL_TYPE_MODULE),r&&(a|=y.JS_EVAL_FLAG_STRICT),i&&(a|=y.JS_EVAL_FLAG_STRIP),s&&(a|=y.JS_EVAL_FLAG_COMPILE_ONLY),o&&(a|=y.JS_EVAL_FLAG_BACKTRACE_BARRIER),a}n(fe,"evalOptionsToFlags");function pe(e){if(typeof e=="number")return e;if(e===void 0)return 0;let{strings:t,symbols:r,quickjsPrivate:i,onlyEnumerable:s,numbers:o,numbersAsStrings:a}=e,u=0;return t&&(u|=v.JS_GPN_STRING_MASK),r&&(u|=v.JS_GPN_SYMBOL_MASK),i&&(u|=v.JS_GPN_PRIVATE_MASK),s&&(u|=v.JS_GPN_ENUM_ONLY),o&&(u|=v.QTS_GPN_NUMBER_MASK),a&&(u|=v.QTS_STANDARD_COMPLIANT_NUMBER),u}n(pe,"getOwnPropertyNamesOptionsToFlags");function ye(...e){let t=[];for(let r of e)r!==void 0&&(t=t.concat(r));return t}n(ye,"concat");var ve=class extends d{static{n(this,"QuickJSIterator")}constructor(e,t){super(),this.handle=e,this.context=t,this._isDone=!1,this.owner=t.runtime}[Symbol.iterator](){return this}next(e){if(!this.alive||this._isDone)return{done:!0,value:void 0};let t=this._next??(this._next=this.context.getProp(this.handle,"next"));return this.callIteratorMethod(t,e)}return(e){if(!this.alive)return{done:!0,value:void 0};let t=this.context.getProp(this.handle,"return");if(t===this.context.undefined&&e===void 0)return this.dispose(),{done:!0,value:void 0};let r=this.callIteratorMethod(t,e);return t.dispose(),this.dispose(),r}throw(e){if(!this.alive)return{done:!0,value:void 0};let t=e instanceof c?e:this.context.newError(e),r=this.context.getProp(this.handle,"throw"),i=this.callIteratorMethod(r,e);return t.alive&&t.dispose(),r.dispose(),this.dispose(),i}get alive(){return this.handle.alive}dispose(){this._isDone=!0,this.handle.dispose(),this._next?.dispose()}callIteratorMethod(e,t){let r=t?this.context.callFunction(e,this.handle,t):this.context.callFunction(e,this.handle);if(r.error)return this.dispose(),{value:r};let i=this.context.getProp(r.value,"done").consume(o=>this.context.dump(o)),s=this.context.getProp(r.value,"value");return r.value.dispose(),i&&this.dispose(),{value:g.success(s),done:i}}},B=-2147483648,j=2147483647,T=0;function M(e){return e>>8}n(M,"getGroupId");var Se=class{static{n(this,"HostRefMap")}constructor(){this.nextId=B,this.freelist=[],this.groups=new Map}put(e){let t=this.allocateId(),r=M(t),i=this.groups.get(r);return i||(i=new Map,this.groups.set(r,i)),i.set(t,e),t}get(e){if(e===T)throw new f("no host reference id defined");let t=M(e),r=this.groups.get(t);if(!r)throw new f(`host reference id ${e} is not defined`);let i=r.get(e);if(!i)throw new f(`host reference id ${e} is not defined`);return i}delete(e){if(e===T)throw new f("no host reference id defined");let t=M(e),r=this.groups.get(t);if(!r)throw new f(`host reference id ${e} is not defined`);r.delete(e),r.size===0&&this.groups.delete(t),this.freelist.push(e)}allocateId(){if(this.freelist.length>0)return this.freelist.shift();if(this.nextId===T&&this.nextId++,this.nextId>j)throw new W(`HostRefMap: too many host refs created without disposing. Max simultaneous host refs: ${j-B}`);return this.nextId++}},G=class extends d{static{n(this,"HostRef")}constructor(e,t,r){if(r===T)throw new f("cannot create HostRef with undefined id");super(),this.runtime=e,this.handle=t,this.id=r}get alive(){return this.handle.alive}dispose(){this.handle.dispose()}get value(){return this.runtime.hostRefs.get(this.id)}},we=class extends te{static{n(this,"ContextMemory")}constructor(e){super(e.module),this.scope=new m,this.copyJSValue=t=>this.ffi.QTS_DupValuePointer(this.ctx.value,t),this.freeJSValue=t=>{this.ffi.QTS_FreeValuePointer(this.ctx.value,t)},e.ownedLifetimes?.forEach(t=>this.scope.manage(t)),this.owner=e.owner,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=this.scope.manage(e.ctx)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}[Symbol.dispose](){return this.dispose()}manage(e){return this.scope.manage(e)}consumeJSCharPointer(e){let t=this.module.UTF8ToString(e);return this.ffi.QTS_FreeCString(this.ctx.value,e),t}heapValueHandle(e,t){let r=t?i=>{t(),this.freeJSValue(i)}:this.freeJSValue;return new c(e,this.copyJSValue,r,this.owner)}staticHeapValueHandle(e){return this.manage(this.heapValueHandle(e)),new S(e,this.owner)}},ge=class extends d{static{n(this,"QuickJSContext")}constructor(e){super(),this._undefined=void 0,this._null=void 0,this._false=void 0,this._true=void 0,this._global=void 0,this._BigInt=void 0,this._Symbol=void 0,this._SymbolIterator=void 0,this._SymbolAsyncIterator=void 0,this.cToHostCallbacks={callFunction:n((t,r,i,s,o)=>{if(t!==this.ctx.value)throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");let a=this.getFunction(o);return m.withScopeMaybeAsync(this,function*(u,l){let p=l.manage(new F(r,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime)),w=new Array(i);for(let h=0;h<i;h++){let _=this.ffi.QTS_ArgvGetJSValueConstPointer(s,h);w[h]=l.manage(new F(_,this.memory.copyJSValue,this.memory.freeJSValue,this.runtime))}try{let h=yield*u(a.apply(p,w));if(h){if("error"in h&&h.error)throw this.runtime.debugLog("throw error",h.error),h.error;let _=l.manage(h instanceof c?h:h.value);return this.ffi.QTS_DupValuePointer(this.ctx.value,_.value)}return 0}catch(h){return this.errorToHandle(h).consume(_=>this.ffi.QTS_Throw(this.ctx.value,_.value))}})},"callFunction")},this.runtime=e.runtime,this.module=e.module,this.ffi=e.ffi,this.rt=e.rt,this.ctx=e.ctx,this.memory=new we({...e,owner:this.runtime}),e.callbacks.setContextCallbacks(this.ctx.value,this.cToHostCallbacks),this.dump=this.dump.bind(this),this.getString=this.getString.bind(this),this.getNumber=this.getNumber.bind(this),this.resolvePromise=this.resolvePromise.bind(this),this.uint32Out=this.memory.manage(this.memory.newTypedArray(Uint32Array,1))}get alive(){return this.memory.alive}dispose(){this.memory.dispose()}get undefined(){if(this._undefined)return this._undefined;let e=this.ffi.QTS_GetUndefined();return this._undefined=new S(e)}get null(){if(this._null)return this._null;let e=this.ffi.QTS_GetNull();return this._null=new S(e)}get true(){if(this._true)return this._true;let e=this.ffi.QTS_GetTrue();return this._true=new S(e)}get false(){if(this._false)return this._false;let e=this.ffi.QTS_GetFalse();return this._false=new S(e)}get global(){if(this._global)return this._global;let e=this.ffi.QTS_GetGlobalObject(this.ctx.value);return this._global=this.memory.staticHeapValueHandle(e),this._global}newNumber(e){return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value,e))}newString(e){let t=this.memory.newHeapCharPointer(e).consume(r=>this.ffi.QTS_NewString(this.ctx.value,r.value.ptr));return this.memory.heapValueHandle(t)}newUniqueSymbol(e){let t=(typeof e=="symbol"?e.description:e)??"",r=this.memory.newHeapCharPointer(t).consume(i=>this.ffi.QTS_NewSymbol(this.ctx.value,i.value.ptr,0));return this.memory.heapValueHandle(r)}newSymbolFor(e){let t=(typeof e=="symbol"?e.description:e)??"",r=this.memory.newHeapCharPointer(t).consume(i=>this.ffi.QTS_NewSymbol(this.ctx.value,i.value.ptr,1));return this.memory.heapValueHandle(r)}getWellKnownSymbol(e){return this._Symbol??(this._Symbol=this.memory.manage(this.getProp(this.global,"Symbol"))),this.getProp(this._Symbol,e)}newBigInt(e){if(!this._BigInt){let i=this.getProp(this.global,"BigInt");this.memory.manage(i),this._BigInt=new S(i.value,this.runtime)}let t=this._BigInt,r=String(e);return this.newString(r).consume(i=>this.unwrapResult(this.callFunction(t,this.undefined,i)))}newObject(e){e&&this.runtime.assertOwned(e);let t=e?this.ffi.QTS_NewObjectProto(this.ctx.value,e.value):this.ffi.QTS_NewObject(this.ctx.value);return this.memory.heapValueHandle(t)}newArray(){let e=this.ffi.QTS_NewArray(this.ctx.value);return this.memory.heapValueHandle(e)}newArrayBuffer(e){let t=new Uint8Array(e),r=this.memory.newHeapBufferPointer(t),i=this.ffi.QTS_NewArrayBuffer(this.ctx.value,r.value.pointer,t.length);return this.memory.heapValueHandle(i)}newPromise(e){let t=m.withScope(r=>{let i=r.manage(this.memory.newMutablePointerArray(2)),s=this.ffi.QTS_NewPromiseCapability(this.ctx.value,i.value.ptr),o=this.memory.heapValueHandle(s),[a,u]=Array.from(i.value.typedArray).map(l=>this.memory.heapValueHandle(l));return new me({context:this,promiseHandle:o,resolveHandle:a,rejectHandle:u})});return e&&typeof e=="function"&&(e=new Promise(e)),e&&Promise.resolve(e).then(t.resolve,r=>r instanceof c?t.reject(r):this.newError(r).consume(t.reject)),t}newFunction(e,t){let r=typeof e=="function"?e:t;if(!r)throw new TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:r.length,isConstructor:!1,fn:r})}newConstructorFunction(e,t){let r=typeof e=="function"?e:t;if(!r)throw new TypeError("Expected a function");return this.newFunctionWithOptions({name:typeof e=="string"?e:void 0,length:r.length,isConstructor:!0,fn:r})}newFunctionWithOptions(e){let{name:t,length:r,isConstructor:i,fn:s}=e,o=this.runtime.hostRefs.put(s);try{return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value,t??"",r,i,o))}catch(a){throw this.runtime.hostRefs.delete(o),a}}newError(e){let t=this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));return e&&typeof e=="object"?(e.name!==void 0&&this.newString(e.name).consume(r=>this.setProp(t,"name",r)),e.message!==void 0&&this.newString(e.message).consume(r=>this.setProp(t,"message",r))):typeof e=="string"?this.newString(e).consume(r=>this.setProp(t,"message",r)):e!==void 0&&this.newString(String(e)).consume(r=>this.setProp(t,"message",r)),t}newHostRef(e){let t=this.runtime.hostRefs.put(e);try{let r=this.memory.heapValueHandle(this.ffi.QTS_NewHostRef(this.ctx.value,t));return new G(this.runtime,r,t)}catch(r){throw this.runtime.hostRefs.delete(t),r}}toHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t!==0)return this.runtime.hostRefs.get(t),new G(this.runtime,e.dup(),t)}unwrapHostRef(e){let t=this.ffi.QTS_GetHostRefId(e.value);if(t===0)throw new f("handle is not a HostRef");return this.runtime.hostRefs.get(t)}typeof(e){return this.runtime.assertOwned(e),this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value,e.value))}getNumber(e){return this.runtime.assertOwned(e),this.ffi.QTS_GetFloat64(this.ctx.value,e.value)}getString(e){return this.runtime.assertOwned(e),this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value,e.value))}getSymbol(e){this.runtime.assertOwned(e);let t=this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value,e.value));return this.ffi.QTS_IsGlobalSymbol(this.ctx.value,e.value)?Symbol.for(t):Symbol(t)}getBigInt(e){this.runtime.assertOwned(e);let t=this.getString(e);return BigInt(t)}getArrayBuffer(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_GetArrayBufferLength(this.ctx.value,e.value),r=this.ffi.QTS_GetArrayBuffer(this.ctx.value,e.value);if(!r)throw new Error("Couldn't allocate memory to get ArrayBuffer");return new c(this.module.HEAPU8.subarray(r,r+t),void 0,()=>this.module._free(r))}getPromiseState(e){this.runtime.assertOwned(e);let t=this.ffi.QTS_PromiseState(this.ctx.value,e.value);if(t<0)return{type:"fulfilled",value:e,notAPromise:!0};if(t===P.Pending)return{type:"pending",get error(){return new Y("Cannot unwrap a pending promise")}};let r=this.ffi.QTS_PromiseResult(this.ctx.value,e.value),i=this.memory.heapValueHandle(r);if(t===P.Fulfilled)return{type:"fulfilled",value:i};if(t===P.Rejected)return{type:"rejected",error:i};throw i.dispose(),new Error(`Unknown JSPromiseStateEnum: ${t}`)}resolvePromise(e){this.runtime.assertOwned(e);let t=m.withScope(r=>{let i=r.manage(this.getProp(this.global,"Promise")),s=r.manage(this.getProp(i,"resolve"));return this.callFunction(s,i,e)});return t.error?Promise.resolve(t):new Promise(r=>{m.withScope(i=>{let s=i.manage(this.newFunction("resolve",l=>{r(this.success(l&&l.dup()))})),o=i.manage(this.newFunction("reject",l=>{r(this.fail(l&&l.dup()))})),a=i.manage(t.value),u=i.manage(this.getProp(a,"then"));this.callFunction(u,a,s,o).unwrap().dispose()})})}isEqual(e,t,r=b.IsStrictlyEqual){if(e===t)return!0;this.runtime.assertOwned(e),this.runtime.assertOwned(t);let i=this.ffi.QTS_IsEqual(this.ctx.value,e.value,t.value,r);if(i===-1)throw new D("WASM variant does not expose equality");return!!i}eq(e,t){return this.isEqual(e,t,b.IsStrictlyEqual)}sameValue(e,t){return this.isEqual(e,t,b.IsSameValue)}sameValueZero(e,t){return this.isEqual(e,t,b.IsSameValueZero)}getProp(e,t){this.runtime.assertOwned(e);let r;return typeof t=="number"&&t>=0?r=this.ffi.QTS_GetPropNumber(this.ctx.value,e.value,t):r=this.borrowPropertyKey(t).consume(i=>this.ffi.QTS_GetProp(this.ctx.value,e.value,i.value)),this.memory.heapValueHandle(r)}getLength(e){if(this.runtime.assertOwned(e),!(this.ffi.QTS_GetLength(this.ctx.value,this.uint32Out.value.ptr,e.value)<0))return this.uint32Out.value.typedArray[0]}getOwnPropertyNames(e,t={strings:!0,numbersAsStrings:!0}){this.runtime.assertOwned(e),e.value;let r=pe(t);if(r===0)throw new q("No options set, will return an empty array");return m.withScope(i=>{let s=i.manage(this.memory.newMutablePointerArray(1)),o=this.ffi.QTS_GetOwnPropertyNames(this.ctx.value,s.value.ptr,this.uint32Out.value.ptr,e.value,r);if(o)return this.fail(this.memory.heapValueHandle(o));let a=this.uint32Out.value.typedArray[0],u=s.value.typedArray[0],l=new Uint32Array(this.module.HEAP8.buffer,u,a),p=Array.from(l).map(w=>this.memory.heapValueHandle(w));return this.ffi.QTS_FreeVoidPointer(this.ctx.value,u),this.success(le(p))})}getIterator(e){let t=this._SymbolIterator??(this._SymbolIterator=this.memory.manage(this.getWellKnownSymbol("iterator")));return m.withScope(r=>{let i=r.manage(this.getProp(e,t)),s=this.callFunction(i,e);return s.error?s:this.success(new ve(s.value,this))})}setProp(e,t,r){this.runtime.assertOwned(e),this.borrowPropertyKey(t).consume(i=>this.ffi.QTS_SetProp(this.ctx.value,e.value,i.value,r.value))}defineProp(e,t,r){this.runtime.assertOwned(e),m.withScope(i=>{let s=i.manage(this.borrowPropertyKey(t)),o=r.value||this.undefined,a=!!r.configurable,u=!!r.enumerable,l=!!r.value,p=r.get?i.manage(this.newFunction(r.get.name,r.get)):this.undefined,w=r.set?i.manage(this.newFunction(r.set.name,r.set)):this.undefined;this.ffi.QTS_DefineProp(this.ctx.value,e.value,s.value,o.value,p.value,w.value,a,u,l)})}callFunction(e,t,...r){this.runtime.assertOwned(e);let i,s=r[0];s===void 0||Array.isArray(s)?i=s??[]:i=r;let o=this.memory.toPointerArray(i).consume(u=>this.ffi.QTS_Call(this.ctx.value,e.value,t.value,i.length,u.value)),a=this.ffi.QTS_ResolveException(this.ctx.value,o);return a?(this.ffi.QTS_FreeValuePointer(this.ctx.value,o),this.fail(this.memory.heapValueHandle(a))):this.success(this.memory.heapValueHandle(o))}callMethod(e,t,r=[]){return this.getProp(e,t).consume(i=>this.callFunction(i,e,r))}evalCode(e,t="eval.js",r){let i=r===void 0?1:0,s=fe(r),o=this.memory.newHeapCharPointer(e).consume(u=>this.ffi.QTS_Eval(this.ctx.value,u.value.ptr,u.value.strlen,t,i,s)),a=this.ffi.QTS_ResolveException(this.ctx.value,o);return a?(this.ffi.QTS_FreeValuePointer(this.ctx.value,o),this.fail(this.memory.heapValueHandle(a))):this.success(this.memory.heapValueHandle(o))}throw(e){return this.errorToHandle(e).consume(t=>this.ffi.QTS_Throw(this.ctx.value,t.value))}borrowPropertyKey(e){return typeof e=="number"?this.newNumber(e):typeof e=="string"?this.newString(e):new S(e.value,this.runtime)}getMemory(e){if(e===this.rt.value)return this.memory;throw new Error("Private API. Cannot get memory from a different runtime")}dump(e){this.runtime.assertOwned(e);let t=this.typeof(e);if(t==="string")return this.getString(e);if(t==="number")return this.getNumber(e);if(t==="bigint")return this.getBigInt(e);if(t==="undefined")return;if(t==="symbol")return this.getSymbol(e);let r=this.getPromiseState(e);if(r.type==="fulfilled"&&!r.notAPromise)return e.dispose(),{type:r.type,value:r.value.consume(this.dump)};if(r.type==="pending")return e.dispose(),{type:r.type};if(r.type==="rejected")return e.dispose(),{type:r.type,error:r.error.consume(this.dump)};let i=this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value,e.value));try{return JSON.parse(i)}catch{return i}}unwrapResult(e){if(e.error){let t="context"in e.error?e.error.context:this,r=e.error.consume(i=>this.dump(i));if(r&&typeof r=="object"&&typeof r.message=="string"){let{message:i,name:s,stack:o,...a}=r,u=new R(r,t);typeof s=="string"&&(u.name=r.name),u.message=i;let l=u.stack;throw typeof o=="string"&&(u.stack=`${s}: ${i}
6
+ ${r.stack}Host: ${l}`),Object.assign(u,a),u}throw new R(r)}return e.value}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getFunction(e){let t=this.runtime.hostRefs.get(e);if(typeof t!="function")throw new Error(`Host reference ${e} is not a function`);return t}errorToHandle(e){return e instanceof c?e:this.newError(e)}encodeBinaryJSON(e){let t=this.ffi.QTS_bjson_encode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}decodeBinaryJSON(e){let t=this.ffi.QTS_bjson_decode(this.ctx.value,e.value);return this.memory.heapValueHandle(t)}success(e){return g.success(e)}fail(e){return g.fail(e,t=>this.unwrapResult(t))}},_e=class extends d{static{n(this,"QuickJSRuntime")}constructor(e){super(),this.scope=new m,this.contextMap=new Map,this.hostRefs=new Se,this._debugMode=!1,this.cToHostCallbacks={freeHostRef:n((t,r)=>{if(t!==this.rt.value)throw new Error("Runtime pointer mismatch");this.hostRefs.delete(r)},"freeHostRef"),shouldInterrupt:n(t=>{if(t!==this.rt.value)throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");let r=this.interruptHandler;if(!r)throw new Error("QuickJSContext had no interrupt handler");return r(this)?1:0},"shouldInterrupt"),loadModuleSource:O(this,function*(t,r,i,s){let o=this.moduleLoader;if(!o)throw new Error("Runtime has no module loader");if(r!==this.rt.value)throw new Error("Runtime pointer mismatch");let a=this.contextMap.get(i)??this.newContext({contextPointer:i});try{let u=yield*t(o(s,a));if(typeof u=="object"&&"error"in u&&u.error)throw this.debugLog("cToHostLoadModule: loader returned error",u.error),u.error;let l=typeof u=="string"?u:"value"in u?u.value:u;return this.memory.newHeapCharPointer(l).value.ptr}catch(u){return this.debugLog("cToHostLoadModule: caught error",u),a.throw(u),0}}),normalizeModule:O(this,function*(t,r,i,s,o){let a=this.moduleNormalizer;if(!a)throw new Error("Runtime has no module normalizer");if(r!==this.rt.value)throw new Error("Runtime pointer mismatch");let u=this.contextMap.get(i)??this.newContext({contextPointer:i});try{let l=yield*t(a(s,o,u));if(typeof l=="object"&&"error"in l&&l.error)throw this.debugLog("cToHostNormalizeModule: normalizer returned error",l.error),l.error;let p=typeof l=="string"?l:l.value;return u.getMemory(this.rt.value).newHeapCharPointer(p).value.ptr}catch(l){return this.debugLog("normalizeModule: caught error",l),u.throw(l),0}})},e.ownedLifetimes?.forEach(t=>this.scope.manage(t)),this.module=e.module,this.memory=new te(this.module),this.ffi=e.ffi,this.rt=e.rt,this.callbacks=e.callbacks,this.scope.manage(this.rt),this.callbacks.setRuntimeCallbacks(this.rt.value,this.cToHostCallbacks),this.executePendingJobs=this.executePendingJobs.bind(this),C&&this.setDebugMode(!0)}get alive(){return this.scope.alive}dispose(){return this.scope.dispose()}newContext(e={}){let t=de(e.intrinsics),r=new c(e.contextPointer||this.ffi.QTS_NewContext(this.rt.value,t),void 0,s=>{this.contextMap.delete(s),this.callbacks.deleteContext(s),this.ffi.QTS_FreeContext(s)}),i=new ge({module:this.module,ctx:r,ffi:this.ffi,rt:this.rt,ownedLifetimes:e.ownedLifetimes,runtime:this,callbacks:this.callbacks});return this.contextMap.set(r.value,i),i}setModuleLoader(e,t){this.moduleLoader=e,this.moduleNormalizer=t,this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value,this.moduleNormalizer?1:0)}removeModuleLoader(){this.moduleLoader=void 0,this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value)}hasPendingJob(){return!!this.ffi.QTS_IsJobPending(this.rt.value)}setInterruptHandler(e){let t=this.interruptHandler;this.interruptHandler=e,t||this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value)}removeInterruptHandler(){this.interruptHandler&&(this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value),this.interruptHandler=void 0)}executePendingJobs(e=-1){let t=this.memory.newMutablePointerArray(1),r=this.ffi.QTS_ExecutePendingJob(this.rt.value,e??-1,t.value.ptr),i=t.value.typedArray[0];if(t.dispose(),i===0)return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value,r),g.success(0);let s=this.contextMap.get(i)??this.newContext({contextPointer:i}),o=s.getMemory(this.rt.value).heapValueHandle(r);if(s.typeof(o)==="number"){let a=s.getNumber(o);return o.dispose(),g.success(a)}else{let a=Object.assign(o,{context:s});return g.fail(a,u=>s.unwrapResult(u))}}setMemoryLimit(e){if(e<0&&e!==-1)throw new Error("Cannot set memory limit to negative number. To unset, pass -1");this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value,e)}computeMemoryUsage(){let e=this.getSystemContext().getMemory(this.rt.value);return e.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value,e.ctx.value))}dumpMemoryUsage(){return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value))}setMaxStackSize(e){if(e<0)throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value,e)}assertOwned(e){if(e.owner&&e.owner.rt!==this.rt)throw new U(`Handle is not owned by this runtime: ${e.owner.rt.value} != ${this.rt.value}`)}setDebugMode(e){this._debugMode=e,this.ffi.DEBUG&&this.rt.alive&&this.ffi.QTS_SetDebugLogEnabled(this.rt.value,e?1:0)}isDebugMode(){return this._debugMode}debugLog(...e){this._debugMode&&console.log("quickjs-emscripten:",...e)}[Symbol.for("nodejs.util.inspect.custom")](){return this.alive?`${this.constructor.name} { rt: ${this.rt.value} }`:`${this.constructor.name} { disposed }`}getSystemContext(){return this.context||(this.context=this.scope.manage(this.newContext())),this.context}},be=class{static{n(this,"QuickJSEmscriptenModuleCallbacks")}constructor(e){this.freeHostRef=e.freeHostRef,this.callFunction=e.callFunction,this.shouldInterrupt=e.shouldInterrupt,this.loadModuleSource=e.loadModuleSource,this.normalizeModule=e.normalizeModule}},xe=class{static{n(this,"QuickJSModuleCallbacks")}constructor(e){this.contextCallbacks=new Map,this.runtimeCallbacks=new Map,this.suspendedCount=0,this.cToHostCallbacks=new be({freeHostRef:n((t,r,i)=>{let s=this.runtimeCallbacks.get(r);if(!s)throw new Error(`QuickJSRuntime(rt = ${r}) not found when trying to free HostRef(id = ${i})`);s.freeHostRef(r,i)},"freeHostRef"),callFunction:n((t,r,i,s,o,a)=>this.handleAsyncify(t,()=>{try{let u=this.contextCallbacks.get(r);if(!u)throw new Error(`QuickJSContext(ctx = ${r}) not found for C function call "${a}"`);return u.callFunction(r,i,s,o,a)}catch(u){return console.error("[C to host error: returning null]",u),0}}),"callFunction"),shouldInterrupt:n((t,r)=>this.handleAsyncify(t,()=>{try{let i=this.runtimeCallbacks.get(r);if(!i)throw new Error(`QuickJSRuntime(rt = ${r}) not found for C interrupt`);return i.shouldInterrupt(r)}catch(i){return console.error("[C to host interrupt: returning error]",i),1}}),"shouldInterrupt"),loadModuleSource:n((t,r,i,s)=>this.handleAsyncify(t,()=>{try{let o=this.runtimeCallbacks.get(r);if(!o)throw new Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let a=o.loadModuleSource;if(!a)throw new Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return a(r,i,s)}catch(o){return console.error("[C to host module loader error: returning null]",o),0}}),"loadModuleSource"),normalizeModule:n((t,r,i,s,o)=>this.handleAsyncify(t,()=>{try{let a=this.runtimeCallbacks.get(r);if(!a)throw new Error(`QuickJSRuntime(rt = ${r}) not found for C module loader`);let u=a.normalizeModule;if(!u)throw new Error(`QuickJSRuntime(rt = ${r}) does not support module loading`);return u(r,i,s,o)}catch(a){return console.error("[C to host module loader error: returning null]",a),0}}),"normalizeModule")}),this.module=e,this.module.callbacks=this.cToHostCallbacks}setRuntimeCallbacks(e,t){this.runtimeCallbacks.set(e,t)}deleteRuntime(e){this.runtimeCallbacks.delete(e)}setContextCallbacks(e,t){this.contextCallbacks.set(e,t)}deleteContext(e){this.contextCallbacks.delete(e)}handleAsyncify(e,t){if(e)return e.handleSleep(i=>{try{let s=t();if(!(s instanceof Promise)){x("asyncify.handleSleep: not suspending:",s),i(s);return}if(this.suspended)throw new $(`Already suspended at: ${this.suspended.stack}
7
+ Attempted to suspend at:`);this.suspended=new z(`(${this.suspendedCount++})`),x("asyncify.handleSleep: suspending:",this.suspended),s.then(o=>{this.suspended=void 0,x("asyncify.handleSleep: resolved:",o),i(o)},o=>{x("asyncify.handleSleep: rejected:",o),console.error("QuickJS: cannot handle error in suspended function",o),this.suspended=void 0})}catch(s){throw x("asyncify.handleSleep: error:",s),this.suspended=void 0,s}});let r=t();if(r instanceof Promise)throw new Error("Promise return value not supported in non-asyncify context.");return r}};function Pe(e,t){t.interruptHandler&&e.setInterruptHandler(t.interruptHandler),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes)}n(Pe,"applyBaseRuntimeOptions");function Ee(e,t){t.moduleLoader&&e.setModuleLoader(t.moduleLoader),t.shouldInterrupt&&e.setInterruptHandler(t.shouldInterrupt),t.memoryLimitBytes!==void 0&&e.setMemoryLimit(t.memoryLimitBytes),t.maxStackSizeBytes!==void 0&&e.setMaxStackSize(t.maxStackSizeBytes)}n(Ee,"applyModuleEvalRuntimeOptions");var Re=class{static{n(this,"QuickJSWASMModule")}constructor(e,t){this.module=e,this.ffi=t,this.callbacks=new xe(e)}newRuntime(e={}){let t=new c(this.ffi.QTS_NewRuntime(),void 0,i=>{this.ffi.QTS_FreeRuntime(i),this.callbacks.deleteRuntime(i)}),r=new _e({module:this.module,callbacks:this.callbacks,ffi:this.ffi,rt:t});return Pe(r,e),e.moduleLoader&&r.setModuleLoader(e.moduleLoader),r}newContext(e={}){let t=this.newRuntime(),r=t.newContext({...e,ownedLifetimes:ye(t,e.ownedLifetimes)});return t.context=r,r}evalCode(e,t={}){return m.withScope(r=>{let i=r.manage(this.newContext());Ee(i.runtime,t);let s=i.evalCode(e,"eval.js");if(t.memoryLimitBytes!==void 0&&i.runtime.setMemoryLimit(-1),s.error)throw i.dump(r.manage(s.error));return i.dump(r.manage(s.value))})}getWasmMemory(){let e=this.module.quickjsEmscriptenInit?.(()=>{})?.getWasmMemory?.();if(!e)throw new Error("Variant does not support getting WebAssembly.Memory");return e}getFFI(){return this.ffi}};export{D as a,c as b,m as c,de as d,fe as e,ge as f,_e as g,xe as h,Pe as i,Ee as j,Re as k};
@@ -0,0 +1,18 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{d as F}from"./chunk-7D2LMRP7.js";import{a as o}from"./chunk-FTQLQJQV.js";import{spawn as nt,spawnSync as At}from"node:child_process";import{accessSync as vt,constants as Rt,existsSync as _t,promises as Bt}from"node:fs";import et from"node:path";var rt="Git is required for OpenPond app workspaces, but macOS reports Apple Command Line Tools are not installed. OpenPond skipped /usr/bin/git to avoid opening the Xcode installer prompt. Install Command Line Tools with `xcode-select --install`, install Git from Homebrew, or put a non-Apple git binary earlier on PATH.",T;function Lt(e){try{return _t(e)?(vt(e,Rt.X_OK),!0):!1}catch{return!1}}o(Lt,"isExecutable");function Ot(){let e=(process.env.PATH??"").split(et.delimiter).map(t=>t.trim()).filter(Boolean);for(let t of e){let n=et.join(t,"git");if(!(n==="/usr/bin/git"||n==="/bin/git")&&Lt(n))return n}return null}o(Ot,"firstNonAppleGitOnPath");function it(){let e=At("/usr/bin/xcode-select",["-p"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return e.status===0&&!!e.stdout.trim()}o(it,"appleDeveloperToolsAvailable");function Dt(e){if(e!=="git"||process.platform!=="darwin")return{command:e};if(T!==void 0)return{command:T};let t=Ot();return t?(T=t,{command:t}):it()?(T="git",{command:"git"}):{error:rt}}o(Dt,"resolveWorkspaceCommand");function u(e,t,n,r={},i){return new Promise(s=>{let a=Dt(e);if("error"in a){s({code:1,stdout:"",stderr:a.error});return}let c=nt(a.command,t,{cwd:n,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:[i===void 0?"ignore":"pipe","pipe","pipe"]}),d=[],p=[];i!==void 0&&c.stdin?.end(i),c.stdout?.on("data",h=>d.push(h)),c.stderr?.on("data",h=>p.push(h)),c.on("error",h=>{s({code:1,stdout:"",stderr:h.message})}),c.on("close",h=>{s({code:h??1,stdout:Buffer.concat(d).toString("utf8"),stderr:Buffer.concat(p).toString("utf8")})})})}o(u,"runCommand");function Gt(e){return!!(e&&e.includes(rt.slice(0,80)))}o(Gt,"isMacOSGitDeveloperToolsMissing");async function Se(e){await Bt.mkdir(e,{recursive:!0});let t=await u("git",["--version"],e);if(t.code===0)return{ok:!0,command:T??"git",version:(t.stdout||t.stderr).trim()};let n=t.stderr.trim()||t.stdout.trim()||"Git is required for OpenPond app workspaces.";return{ok:!1,error:n,installAction:process.platform==="darwin"&&Gt(n)?"macos_command_line_tools":"manual_git_install"}}o(Se,"checkWorkspaceGitAvailability");function ye(){if(process.platform!=="darwin")return{ok:!1,error:"Apple Command Line Tools installation is only available on macOS."};if(it())return{ok:!0,message:"Apple Command Line Tools already appear to be installed."};try{return nt("/usr/bin/xcode-select",["--install"],{detached:!0,stdio:"ignore"}).unref(),{ok:!0,message:"Opened the Apple Command Line Tools installer."}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}o(ye,"startMacOSCommandLineToolsInstall");import{promises as k}from"node:fs";import m from"node:path";var st=24e3,ot=8e4,It=512*1024,ct=15*1024*1024,Tt=20*1024*1024,Mt=new Set([".cache",".eggs",".git",".ipynb_checkpoints",".mypy_cache",".next",".nox",".nuxt",".openpond",".output",".parcel-cache",".pytest_cache",".pyre",".ruff_cache",".svelte-kit",".tox",".turbo",".venv","__pycache__","artifacts","build","coverage","dist","env","node_modules","out","site-packages","target","venv","volumes"]),zt=new Set([".7z",".avif",".db",".doc",".docx",".gif",".gz",".ico",".jpeg",".jpg",".mov",".mp4",".pdf",".png",".sqlite",".tar",".webp",".xls",".xlsm",".xlsx",".zip"]),$t=new Map([[".avif","image/avif"],[".gif","image/gif"],[".jpeg","image/jpeg"],[".jpg","image/jpeg"],[".png","image/png"],[".webp","image/webp"]]),Nt=new Map([[".m4v","video/x-m4v"],[".mov","video/quicktime"],[".mp4","video/mp4"],[".webm","video/webm"]]),Ht=new Set([".doc",".docx",".pdf"]);function Ut(e){return e.replace(/[^a-zA-Z0-9._-]/g,"-").slice(0,120)||"app"}o(Ut,"safeAppSegment");function N(e){if(!e)return"unknown";try{let t=new URL(e).hostname.toLowerCase();if(t==="github.com"||t.endsWith(".github.com"))return"github";if(t==="openpond.ai"||t.endsWith(".openpond.ai"))return"openpond"}catch{return"unknown"}return"local_git"}o(N,"sourceFromRemote");function $(e){return e.replace(/x-access-token:[^@]+@/g,"x-access-token:***@").replace(/Authorization:\s*Basic\s+[A-Za-z0-9+/=]+/gi,"Authorization: Basic ***")}o($,"redactRemoteUrl");async function G(e){try{return await k.access(e),!0}catch{return!1}}o(G,"pathExists");async function O(e){return await G(e)?(await u("git",["rev-parse","--git-dir"],e)).code===0:!1}o(O,"isGitRepo");function X(e){return e.length<=st?e:`${e.slice(0,st)}
3
+
4
+ [diff truncated]`}o(X,"truncatePatch");function jt(e){return e.length<=ot?e:`${e.slice(0,ot)}
5
+
6
+ [file truncated]`}o(jt,"truncateFileContent");async function I(e,t){let n=m.resolve(e,t),r=m.resolve(e);if(n!==r&&!n.startsWith(`${r}${m.sep}`))return null;try{let i=await k.lstat(n);return!i.isFile()||!Kt(t,i.size)?null:jt(await k.readFile(n,"utf8"))}catch{return null}}o(I,"readWorkspaceFile");async function V(e,t){let n=w(t);if(!n||!Ht.has(m.extname(n).toLowerCase()))return null;let r=m.resolve(e,n),i=m.resolve(e);if(r!==i&&!r.startsWith(`${i}${m.sep}`))return null;try{let s=await k.lstat(r);return!s.isFile()||s.size>Tt?null:(await k.readFile(r)).toString("base64")}catch{return null}}o(V,"readWorkspaceDocumentPreview");function lt(e){return $t.get(m.extname(e).toLowerCase())??null}o(lt,"workspaceImageContentType");function qt(e){return Nt.get(m.extname(e).toLowerCase())??null}o(qt,"localVideoContentType");async function ut(e,t){let n=w(t);if(!n)return null;let r=lt(n);if(!r)return null;let i=m.resolve(e,n),s=m.resolve(e);if(i!==s&&!i.startsWith(`${s}${m.sep}`))return null;try{let a=await k.lstat(i);return!a.isFile()||a.size>ct?null:{path:n,contentType:r,bytes:await k.readFile(i),sizeBytes:a.size}}catch{return null}}o(ut,"readWorkspaceImageFile");async function Ae(e){let t=dt(e);if(!t)return null;let n=lt(t);if(!n)return null;let r=m.resolve(t);try{let i=await k.lstat(r);return!i.isFile()||i.size>ct?null:{path:r,contentType:n,bytes:await k.readFile(r),sizeBytes:i.size}}catch{return null}}o(Ae,"readLocalImageFile");async function ve(e){let t=dt(e);if(!t)return null;let n=qt(t);if(!n)return null;let r=m.resolve(t);try{let i=await k.lstat(r);return i.isFile()?{path:r,contentType:n,sizeBytes:i.size}:null}catch{return null}}o(ve,"readLocalVideoFile");function dt(e){let t=e.trim();if(!t)return null;if(t=t.replace(/^['"`]+|['"`]+$/g,""),t.startsWith("file://"))try{t=decodeURIComponent(new URL(t).pathname)}catch{t=t.replace(/^file:\/\//,"")}return m.isAbsolute(t)?t:null}o(dt,"cleanLocalAssetPath");function Kt(e,t){return t>It?!1:!zt.has(m.extname(e).toLowerCase())}o(Kt,"isReadableTextWorkspaceFile");async function pt(e,t){let n=m.resolve(e,t),r=m.resolve(e);if(n!==r&&!n.startsWith(`${r}${m.sep}`))return!1;try{return(await k.lstat(n)).isDirectory()}catch{return!1}}o(pt,"isWorkspaceDirectory");function w(e){let t=e.replace(/\\/g,"/").replace(/^\.\/+/,"");if(!t.trim()||t.startsWith("/"))return null;let n=t.split("/").filter(Boolean);return n.length===0||n.some(r=>r===".."||r===".git")?null:n.join("/")}o(w,"normalizeWorkspaceFilePath");function y(e){let t=w(e);return t?t.split("/").some(n=>Mt.has(n)||n===".env"||n.startsWith(".env.")||n.endsWith(".egg-info")||n.endsWith(".pyc")||n.endsWith(".pyo")):!0}o(y,"isGeneratedWorkspacePath");async function ft(e,t){if(y(t))return!1;let n=await u("git",["ls-files","--cached","--others","--exclude-standard","--",t],e);return n.code!==0?!1:n.stdout.split(`
7
+ `).map(r=>r.trim()).some(r=>r===t)}o(ft,"isVisibleGitWorkspaceFile");function M(e){if(!e.trim()||e.startsWith("## "))return null;let t=e.slice(0,2),n=e.slice(3).trim(),r=n.includes(" -> ")?n.split(" -> ").pop().trim():n;return r?t==="??"?{path:r,status:"untracked"}:t.includes("A")?{path:r,status:"added"}:t.includes("D")?{path:r,status:"deleted"}:t.includes("R")?{path:r,status:"renamed"}:{path:r,status:"modified"}:null}o(M,"parseStatusLine");function mt(e){let t=e.replace(/^##\s*/,"").split("...")[1]?.trim();if(!t)return{upstreamBranch:null,ahead:0,behind:0};let n=t.indexOf("["),r=(n>=0?t.slice(0,n):t).trim()||null,i=t.match(/ahead\s+(\d+)/),s=t.match(/behind\s+(\d+)/);return{upstreamBranch:r,ahead:i&&Number(i[1])||0,behind:s&&Number(s[1])||0}}o(mt,"parseBranchStatusLine");function H(e){let t=new Map;for(let n of e.split(`
8
+ `)){if(!n.trim())continue;let[r,i,...s]=n.split(" "),a=s.join(" ").trim();a&&t.set(a,{additions:r==="-"?0:Number(r)||0,deletions:i==="-"?0:Number(i)||0})}return t}o(H,"parseNumstat");function U(e){return Array.from(new Set(e.filter(Boolean))).sort((t,n)=>t.localeCompare(n))}o(U,"uniqueSortedPaths");var at=2e3;async function ht(e){let t=[];async function n(r,i=""){if(t.length>=at)return;let s;try{s=await k.readdir(r,{withFileTypes:!0})}catch{return}s.sort((a,c)=>a.name.localeCompare(c.name));for(let a of s){if(t.length>=at)return;let c=i?`${i}/${a.name}`:a.name;if(y(c))continue;let d=m.join(r,a.name);a.isDirectory()?await n(d,c):a.isFile()&&t.push(c)}}return o(n,"walk"),await n(e),U(t)}o(ht,"listPlainWorkspaceFiles");function gt(e){let t=e?.trim();if(!t)return null;try{return new URL(t.includes("://")?t:`https://${t}`).host.replace(/\/+$/,"")}catch{return t.replace(/^https?:\/\//i,"").replace(/\/+$/,"")}}o(gt,"normalizeGitHost");function Xt(e){let t=e?.trim();if(!t)return null;try{let n=new URL(t);return{protocol:n.protocol||"https:",host:n.host}}catch{return null}}o(Xt,"normalizeGitBaseUrl");function Vt(e){let t=gt(e);return!t||t==="openpond.ai"||t==="www.openpond.ai"}o(Vt,"isDefaultOpenPondGitHost");function wt(e,t){let n=e.gitOwner?.trim(),r=e.gitRepo?.trim();if(!n||!r)return null;let i=Xt(t),s=gt(e.gitHost),a=i&&Vt(s)?i.host:s||i?.host||"openpond.ai",c=i&&a===i.host?i.protocol:"https:",d=r.endsWith(".git")?r:`${r}.git`;return`${c}//${a}/${n}/${d}`}o(wt,"expectedRemoteUrl");function Yt(e){try{let t=new URL(e).hostname.toLowerCase();return t==="openpond.ai"||t.endsWith(".openpond.ai")}catch{return!1}}o(Yt,"isOpenPondRemote");function Jt(e,t){return!t||!Yt(e)?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.extraHeader",GIT_CONFIG_VALUE_0:`Authorization: Basic ${Buffer.from(`x-access-token:${t}`,"utf8").toString("base64")}`}}o(Jt,"gitBasicAuthEnv");function Y(e){let t=e.trim();if(!t)throw new Error("Branch name is required");if(t.includes(".."))throw new Error("Branch name cannot contain '..'");if(/[~^:\\\s]/.test(t))throw new Error("Branch name contains unsupported characters");if(t.startsWith("/")||t.endsWith("/")||t.startsWith("-"))throw new Error("Branch name is not safe")}o(Y,"assertSafeBranchName");function R(e,t){let n=m.join(e,"workspaces",Ut(t));return{workspacePath:n,repoPath:m.join(n,"repo")}}o(R,"appWorkspacePaths");async function kt(e,t,n,r){await k.mkdir(t,{recursive:!0});let i=await G(e),s=await u("git",["clone","--quiet",n,e],t,Jt(n,r));if(s.code!==0)throw i||await k.rm(e,{recursive:!0,force:!0}).catch(()=>null),new Error($(s.stderr.trim()||s.stdout.trim()||"git clone failed"));let a=await u("git",["remote","set-url","origin",n],e);if(a.code!==0)throw new Error($(a.stderr.trim()||a.stdout.trim()||"git remote set-url failed"))}o(kt,"cloneWorkspace");async function Wt(e){let t=await u("git",["rev-parse","--git-path","FETCH_HEAD"],e),n=t.code===0&&t.stdout.trim()?m.resolve(e,t.stdout.trim()):m.join(e,".git","FETCH_HEAD");try{return(await k.stat(n)).mtime.toISOString()}catch{return null}}o(Wt,"lastFetchAt");import{promises as Zt}from"node:fs";async function Ge(e,t,n={}){return z(R(e,t.id),t,n)}o(Ge,"loadWorkspaceState");async function z(e,t,n={}){let{workspacePath:r,repoPath:i}=e,s=wt(t,n.gitBaseUrl);await Zt.mkdir(r,{recursive:!0});let a=await O(i),c=null;if(!a&&n.clone&&s)try{await kt(i,r,s,n.token),a=!0}catch(g){c=g instanceof Error?g.message:String(g)}if(!a)return n.allowPlainFolder&&await G(i)?{appId:t.id,source:"local_folder",workspacePath:r,repoPath:i,initialized:!0,remoteUrl:null,expectedRemoteUrl:s,currentBranch:null,headCommit:null,upstreamBranch:null,ahead:0,behind:0,diverged:!1,linkedSourceHeadCommit:n.linkedSourceHeadCommit?.trim()||null,aheadOfLinkedSource:0,behindLinkedSource:0,divergedFromLinkedSource:!1,linkedSourceComparisonError:null,lastFetchAt:null,defaultBranch:t.defaultBranch??null,branches:[],dirty:!1,changedFilesCount:0,untrackedFilesCount:0,error:c,updatedAt:F()}:{appId:t.id,source:N(s),workspacePath:r,repoPath:i,initialized:a,remoteUrl:null,expectedRemoteUrl:s,currentBranch:null,headCommit:null,upstreamBranch:null,ahead:0,behind:0,diverged:!1,linkedSourceHeadCommit:n.linkedSourceHeadCommit?.trim()||null,aheadOfLinkedSource:0,behindLinkedSource:0,divergedFromLinkedSource:!1,linkedSourceComparisonError:null,lastFetchAt:null,defaultBranch:t.defaultBranch??null,branches:[],dirty:!1,changedFilesCount:0,untrackedFilesCount:0,error:c,updatedAt:F()};let[d,p,h,b,A]=await Promise.all([u("git",["branch","--show-current"],i),u("git",["branch","--format=%(refname:short)"],i),u("git",["status","--porcelain=v1","-b"],i),u("git",["config","--get","remote.origin.url"],i),u("git",["rev-parse","--verify","HEAD"],i)]),v=b.code===0&&$(b.stdout.trim())||null,S=h.code===0?h.stdout.split(`
9
+ `).filter(g=>g.trim()):[],C=mt(S.find(g=>g.startsWith("## "))??""),f=S.filter(g=>{if(g.startsWith("## "))return!1;let D=M(g),tt=D?w(D.path):null;return!!(tt&&!y(tt))}),x=f.filter(g=>g.startsWith("??")).length,E=d.code===0&&d.stdout.trim()?d.stdout.trim():null,L=A.code===0&&A.stdout.trim()||null,q=p.code===0?p.stdout.split(`
10
+ `).map(g=>g.trim()).filter(Boolean):[],l=N(v)==="unknown"&&s?s:v??s,W=await Qt(i,n.linkedSourceHeadCommit,L);return{appId:t.id,source:l?N(l):"local_git",workspacePath:r,repoPath:i,initialized:a,remoteUrl:v,expectedRemoteUrl:s,currentBranch:E,headCommit:L,upstreamBranch:C.upstreamBranch,ahead:C.ahead,behind:C.behind,diverged:C.ahead>0&&C.behind>0,linkedSourceHeadCommit:W.linkedSourceHeadCommit,aheadOfLinkedSource:W.aheadOfLinkedSource,behindLinkedSource:W.behindLinkedSource,divergedFromLinkedSource:W.divergedFromLinkedSource,linkedSourceComparisonError:W.error,lastFetchAt:await Wt(i),defaultBranch:t.defaultBranch??null,branches:q,dirty:f.length>0,changedFilesCount:f.length,untrackedFilesCount:x,error:c,updatedAt:F()}}o(z,"loadWorkspaceStateAtPath");async function Qt(e,t,n){let r=t?.trim()||null,i={linkedSourceHeadCommit:r,aheadOfLinkedSource:0,behindLinkedSource:0,divergedFromLinkedSource:!1,error:null};if(!r||!n||r===n)return i;let s=await u("git",["rev-list","--left-right","--count",`${r}...${n}`],e);if(s.code!==0)return{...i,error:s.stderr.trim()||s.stdout.trim()||"Unable to compare linked source commit."};let[a,c]=s.stdout.trim().split(/\s+/,2),d=Number(a)||0,p=Number(c)||0;return{linkedSourceHeadCommit:r,aheadOfLinkedSource:p,behindLinkedSource:d,divergedFromLinkedSource:p>0&&d>0,error:null}}o(Qt,"compareLinkedSourceCommit");async function Ie(e,t,n){return te(R(e,t.id),t,n)}o(Ie,"createAndCheckoutBranch");async function te(e,t,n,r={}){Y(n);let i=await z(e,t,{...r,clone:!1});if(!i.initialized)throw new Error(i.error||"Workspace is not initialized");let s=await u("git",["checkout","-b",n.trim()],i.repoPath);if(s.code!==0)throw new Error(s.stderr.trim()||s.stdout.trim()||"Unable to create branch");return z(e,t,{...r,clone:!1})}o(te,"createAndCheckoutBranchAtPath");async function Te(e,t,n){return ee(R(e,t.id),t,n)}o(Te,"checkoutBranch");async function ee(e,t,n,r={}){Y(n);let i=await z(e,t,{...r,clone:!1});if(!i.initialized)throw new Error(i.error||"Workspace is not initialized");if(i.dirty&&i.currentBranch!==n.trim())throw new Error("Commit or discard local changes before switching branches");let s=await u("git",["checkout",n.trim()],i.repoPath);if(s.code!==0)throw new Error(s.stderr.trim()||s.stdout.trim()||"Unable to switch branch");return z(e,t,{...r,clone:!1})}o(ee,"checkoutBranchAtPath");import P from"node:path";import{promises as yt}from"node:fs";var ne=6,re=60,Pt=1e4,_=new Map;async function j(e,t,n=ne){let r=Math.max(1,Math.floor(n)),i=new Array(e.length),s=0;async function a(){for(;s<e.length;){let c=s;s+=1,i[c]=await t(e[c],c)}}return o(a,"worker"),await Promise.all(Array.from({length:Math.min(r,e.length)},()=>a())),i}o(j,"mapWorkspaceDiffEntriesWithConcurrency");function qe(){_.clear()}o(qe,"clearWorkspaceDiffCacheForTests");async function Ke(e,t,n={}){let{repoPath:r}=R(e,t.id);return ie(r,t.id,n)}o(Ke,"loadWorkspaceDiff");async function ie(e,t,n={}){let r=await O(e);if(!r){let l=await ht(e);return{appId:t,repoPath:e,initialized:l.length>0||await G(e),dirty:!1,filesChanged:0,additions:0,deletions:0,repoFiles:l,files:[],error:null,updatedAt:F()}}let i=await Z(e),s=i.pathPrefix||".",[a,c]=await Promise.all([u("git",["rev-parse","HEAD"],i.commandCwd),u("git",["status","--porcelain=v1","-uall","--",s],i.commandCwd)]);if(c.code!==0)return{appId:t,repoPath:e,initialized:r,dirty:!1,filesChanged:0,additions:0,deletions:0,repoFiles:[],files:[],error:c.stderr.trim()||c.stdout.trim()||"Unable to read workspace diff",updatedAt:F()};let d=c.stdout.split(`
11
+ `).map(M).filter(l=>!!l).map(l=>{let W=B(l.path,i.pathPrefix);if(!W)return null;let g=w(W);return g?{...l,path:g}:null}).filter(l=>l?!y(l.path):!1),p=await oe(e,d),h=ae({repoPath:e,workspaceId:t,includeFileDetails:!!n.includeFileDetails,head:a.code===0?a.stdout.trim():"unborn",pathPrefix:i.pathPrefix,status:c.stdout,worktreeSignature:p}),b=_.get(h);if(b)return J(b);let A=(await j(d,async l=>l.status==="deleted"||!await pt(e,l.path)?l:null)).filter(l=>!!l),v=await u("git",["ls-files","--",s],i.commandCwd),S=U([...v.code===0?v.stdout.split(`
12
+ `).map(l=>B(l.trim(),i.pathPrefix)).filter(l=>!!l):[],...A.map(l=>l.path)].filter(l=>!y(l))),C=await u("git",["diff","--numstat","HEAD","--",s],i.commandCwd),f=C.code===0?Ct(H(C.stdout),i.pathPrefix):new Map,x=n.includeFileDetails?await le(i,A.filter(l=>l.status!=="untracked")):new Map,E=await j(A,async l=>{let g=(n.includeFileDetails||l.status==="untracked")&&l.status!=="deleted"?await I(e,l.path):null,D=l.status==="untracked"?{additions:bt(g),deletions:0}:f.get(l.path)??{additions:0,deletions:0};return n.includeFileDetails?Ft(e,l,i,D,{content:g,patch:l.status==="untracked"?null:x.get(l.path)??null}):{path:l.path,status:l.status,additions:D.additions,deletions:D.deletions,patch:"",content:null}}),L=E.reduce((l,W)=>l+W.additions,0),q=E.reduce((l,W)=>l+W.deletions,0),K={appId:t,repoPath:e,initialized:r,dirty:E.length>0,filesChanged:E.length,additions:L,deletions:q,repoFiles:S,files:E,error:null,updatedAt:F()};return ce(h,K),J(K)}o(ie,"loadWorkspaceDiffAtPath");async function Xe(e,t,n,r){if(!await O(e))throw new Error("Candidate source is not a Git repository.");let s=await Z(e),a=`${n}..${r}`,[c,d,p,h,b]=await Promise.all([u("git",["rev-parse","--verify",`${n}^{commit}`],s.commandCwd),u("git",["rev-parse","--verify",`${r}^{commit}`],s.commandCwd),u("git",["-c","core.quotePath=false","diff","--name-status","--find-renames",a,"--","."],s.commandCwd),u("git",["-c","core.quotePath=false","diff","--no-ext-diff","--unified=80",a,"--","."],s.commandCwd),u("git",["-c","core.quotePath=false","ls-tree","-r","--name-only",r],s.commandCwd)]);if(c.code!==0||d.code!==0)throw new Error("Candidate Git history is no longer available.");if(p.code!==0)throw new Error(p.stderr.trim()||"Unable to read the candidate change.");let A=se(p.stdout).filter(f=>!y(f.path)),v=h.code===0?xt(h.stdout||h.stderr,""):new Map,S=await j(A,async f=>{let x=await u("git",["diff","--numstat",a,"--",f.path],s.commandCwd),E=x.code===0?[...H(x.stdout).values()][0]??{additions:0,deletions:0}:{additions:0,deletions:0},L=f.status==="deleted"?null:await u("git",["show",`${r}:${f.path}`],s.commandCwd);return{path:f.path,status:f.status,additions:E.additions,deletions:E.deletions,patch:X(v.get(f.path)??""),content:L?.code===0?L.stdout:null}}),C=b.code===0?U(b.stdout.split(`
13
+ `).map(f=>f.trim()).filter(f=>f&&!y(f))):S.map(f=>f.path);return{appId:t,repoPath:e,initialized:!0,dirty:S.length>0,filesChanged:S.length,additions:S.reduce((f,x)=>f+x.additions,0),deletions:S.reduce((f,x)=>f+x.deletions,0),repoFiles:C,files:S,error:null,updatedAt:F()}}o(Xe,"loadGitCommitDiffAtPath");function se(e){return e.split(/\r?\n/).filter(Boolean).flatMap(t=>{let[n,r,i]=t.split(" "),s=n?.[0]??"M",a=s==="R"||s==="C"?i:r,c=a?w(a):null;return c?[{path:c,status:s==="A"||s==="C"?"added":s==="D"?"deleted":s==="R"?"renamed":"modified"}]:[]})}o(se,"parseCommitDiffEntries");function bt(e){if(!e)return 0;let t=e.endsWith(`
14
+ `)?e.slice(0,-1):e;return t?t.split(`
15
+ `).length:0}o(bt,"countTextLines");async function oe(e,t){return(await j(t,async r=>{if(r.status==="deleted")return`${r.path} ${r.status} deleted`;let i=P.resolve(e,r.path),s=P.resolve(e);if(i!==s&&!i.startsWith(`${s}${P.sep}`))return`${r.path} ${r.status} outside`;try{let a=await yt.lstat(i),c=a.isDirectory()?"dir":a.isFile()?"file":"other";return`${r.path} ${r.status} ${c} ${a.size} ${Math.trunc(a.mtimeMs)} ${Math.trunc(a.ctimeMs)}`}catch{return`${r.path} ${r.status} missing`}})).sort((r,i)=>r.localeCompare(i)).join(`
16
+ `)}o(oe,"workspaceDiffWorktreeSignature");function ae(e){return JSON.stringify(e)}o(ae,"workspaceDiffCacheKey");function ce(e,t){for(_.has(e)&&_.delete(e),_.set(e,J(t));_.size>re;){let n=_.keys().next().value;if(!n)break;_.delete(n)}}o(ce,"writeWorkspaceDiffCache");function J(e){return{...e,repoFiles:[...e.repoFiles],files:e.files.map(t=>({...t}))}}o(J,"cloneWorkspaceDiffSummary");async function Z(e){let t=await u("git",["rev-parse","--show-toplevel"],e);if(t.code!==0)return{commandCwd:e,pathPrefix:""};let n=t.stdout.trim();if(!n)return{commandCwd:e,pathPrefix:""};let r=P.relative(P.resolve(n),P.resolve(e)),i=w(r.replace(/\\/g,"/"))??"";return{commandCwd:n,pathPrefix:i}}o(Z,"gitWorkspaceContext");function B(e,t){let n=w(e);return n?t?n===t?null:n.startsWith(`${t}/`)?n.slice(t.length+1):null:n:null}o(B,"pathInWorkspace");function Q(e,t){return t?`${t}/${e}`:e}o(Q,"gitPathForWorkspacePath");function Ct(e,t){let n=new Map;for(let[r,i]of e){let s=B(r,t);s&&n.set(s,i)}return n}o(Ct,"scopedNumstat");async function le(e,t){if(t.length===0)return new Map;let n=e.pathPrefix||".",r=await u("git",["-c","core.quotePath=false","diff","--no-ext-diff","--unified=80","HEAD","--",n],e.commandCwd);return r.code!==0?new Map:xt(r.stdout||r.stderr,e.pathPrefix)}o(le,"loadTrackedGitPatchMap");function xt(e,t){let n=new Map;for(let r of e.split(/(?=^diff --git )/m)){if(!r.trim())continue;let i=ue(r,t);i&&n.set(i,r)}return n}o(xt,"parseGitPatchStreamByWorkspacePath");function ue(e,t){let n=e.split(`
17
+ `);for(let a of n){let c=St(a,"+++ ");if(c)return B(c,t)}for(let a of n){let c=St(a,"--- ");if(c)return B(c,t)}for(let a of n)if(a.startsWith("rename to ")){let c=w(a.slice(10).trim());if(c)return B(c,t)}let r=n.find(a=>a.startsWith("diff --git "));if(!r)return null;let i=r.lastIndexOf(" b/");if(i<0)return null;let s=w(r.slice(i+3).trim());return s?B(s,t):null}o(ue,"workspacePathForGitPatchChunk");function St(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).trim();if(!n||n==="/dev/null")return null;let r=n.startsWith("a/")||n.startsWith("b/")?n.slice(2):n;return w(r)}o(St,"gitPatchMarkerPath");async function Ve(e,t,n){let{repoPath:r}=R(e,t.id);return fe(r,n)}o(Ve,"loadWorkspaceFile");async function Ye(e,t,n){let{repoPath:r}=R(e,t.id);return de(r,n)}o(Ye,"loadWorkspaceImageFile");async function de(e,t){let n=await O(e),r=Et(e,t);if(!r)throw new Error("Image not found");if(n&&!await ft(e,r))throw new Error("Image not found");let i=await ut(e,r);if(!i)throw new Error("Image not found");return i}o(de,"loadWorkspaceImageFileAtPath");function Et(e,t){let n=pe(t);if(!n)return null;if(!P.isAbsolute(n))return w(n);let r=P.relative(P.resolve(e),P.resolve(n));return!r||r.startsWith("..")||P.isAbsolute(r)?null:w(r)}o(Et,"normalizeWorkspaceFileRequestPath");function pe(e){let t=e.trim();if(!t)return null;t=t.replace(/^['"`]+|['"`]+$/g,"");let n=t.indexOf("#");n>=0&&(t=t.slice(0,n));let r=t.indexOf("?");if(r>=0&&(t=t.slice(0,r)),t.startsWith("file://"))try{t=decodeURIComponent(new URL(t).pathname)}catch{t=t.replace(/^file:\/\//,"")}return t.trim()||null}o(pe,"cleanWorkspaceFileRequestPath");async function fe(e,t){let n=await O(e),r=Et(e,t);if(!r)throw new Error("File not found");if(y(r))throw new Error("File not found");if(n){let a=await me(e,r);if(a){if(a.content!==null||a.status==="deleted")return a;let c=await V(e,r);return c===null?a:{...a,content:c}}}let i=r,s=await I(e,i)??await V(e,i);if(s===null){let a=await he(e,r);a&&(i=a,s=await I(e,i))}if(s===null)throw new Error("File not found");return{path:i,status:"unchanged",additions:0,deletions:0,patch:"",content:s}}o(fe,"loadWorkspaceFileAtPath");async function me(e,t){let n=await Z(e),r=Q(t,n.pathPrefix),i=await u("git",["status","--porcelain=v1","-uall","--",r],n.commandCwd);if(i.code!==0)return null;let s=i.stdout.split(`
18
+ `).map(M).filter(c=>!!c).map(c=>{let d=B(c.path,n.pathPrefix);if(!d)return null;let p=w(d);return p?{...c,path:p}:null}).find(c=>!!(c&&c.path===t));if(!s)return null;let a=s.status==="untracked"?{additions:bt(await I(e,s.path)),deletions:0}:await we(n,s.path);return Ft(e,s,n,a)}o(me,"loadGitWorkspaceFileAtPath");async function he(e,t){if(t.includes("/")||!ge(t))return null;let n=t.toLowerCase(),r=[],i=[{absolutePath:e,prefix:""}],s=0;for(;i.length>0&&s<Pt;){let c=i.shift(),d;try{d=await yt.readdir(c.absolutePath,{withFileTypes:!0})}catch{continue}d.sort((p,h)=>p.name.localeCompare(h.name));for(let p of d){if(s>=Pt)break;let h=c.prefix?`${c.prefix}/${p.name}`:p.name;if(y(h))continue;s+=1;let b=P.join(c.absolutePath,p.name);p.isDirectory()?i.push({absolutePath:b,prefix:h}):p.isFile()&&p.name.toLowerCase()===n&&r.push(h)}}if(r.length===1)return r[0]??null;let a=r.filter(c=>c.startsWith("docs/working-docs/"));return a.length===1?a[0]??null:null}o(he,"resolveExplicitMarkdownBasenamePath");function ge(e){return/\.(?:md|markdown|mdx)$/i.test(e)}o(ge,"isMarkdownWorkspacePath");async function Ft(e,t,n,r,i={}){let s=i.content!==void 0?i.content:t.status==="deleted"?null:await I(e,t.path),a=Q(t.path,n.pathPrefix),c=t.status==="untracked"?["diff","--no-index","--unified=80","--","/dev/null",P.join(e,t.path)]:["diff","--no-ext-diff","--unified=80","HEAD","--",a],d=i.patch??"";if(i.patch===null||i.patch===void 0){let p=await u("git",c,n.commandCwd);d=p.stdout||p.stderr}return{path:t.path,status:t.status,additions:r.additions,deletions:r.deletions,patch:X(d),content:s}}o(Ft,"loadGitWorkspaceFileDetail");async function we(e,t){let n=Q(t,e.pathPrefix),r=await u("git",["diff","--numstat","HEAD","--",n],e.commandCwd);return r.code!==0?{additions:0,deletions:0}:Ct(H(r.stdout),e.pathPrefix).get(t)??{additions:0,deletions:0}}o(we,"gitNumstatForFile");export{rt as a,u as b,Gt as c,Se as d,ye as e,N as f,$ as g,G as h,O as i,X as j,I as k,V as l,lt as m,qt as n,ut as o,Ae as p,ve as q,pt as r,w as s,y as t,ft as u,M as v,mt as w,H as x,U as y,ht as z,wt as A,Y as B,R as C,kt as D,Wt as E,Ge as F,z as G,Ie as H,te as I,Te as J,ee as K,j as L,qe as M,Ke as N,ie as O,Xe as P,Ve as Q,Ye as R,de as S,fe as T};
@@ -0,0 +1,6 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{q as z,r as V,s as G,t as q}from"./chunk-CCJG7GLE.js";import{a as A,f as v,g as k,h as p,i as f}from"./chunk-3M53YXEI.js";import{a}from"./chunk-FTQLQJQV.js";import{Buffer as Y}from"node:buffer";import{readdirSync as H,readFileSync as Q,statSync as F}from"node:fs";import b from"node:path";var K=500,Z=8*1024*1024,W=8*1024*1024;async function me(e,t){if(!t.sandboxRuntime&&!t.runtimeId)return{sandbox:await X(e,await e.create(t.sandbox,{async:!0}))};let n=t.runtimeId?void 0:await e.createSandboxRuntime(t.sandboxRuntime),r=t.runtimeId??n.id,o=await e.createSandboxRuntimeSandbox(r,t.sandbox);return{sandbox:await X(e,o.sandbox),runtime:o.runtime??n}}a(me,"createSandboxFromPlan");async function X(e,t){if(t.state==="running"||t.state==="stopped")return t;if(t.state==="error")throw new Error(`sandbox create failed: ${t.id}
3
+ ${t.logs.join(`
4
+ `)}`);let n=12*6e4,r=3e3,o=Date.now()+n,i=t;for(;Date.now()<o;){if(await new Promise(s=>setTimeout(s,r)),i=await e.get(t.id),i.state==="running"||i.state==="stopped")return i;if(i.state==="error")throw new Error(`sandbox create failed: ${i.id}
5
+ ${i.logs.join(`
6
+ `)}`)}throw new Error(`sandbox create did not reach running state before timeout: ${i.id} (${i.state})`)}a(X,"waitForSandboxCreateReady");function le(e){let t=e.reservation.mpp?.mode??"no-mpp",n=e.reservation.capturedUsd,r=e.budget.maxUsd,o=e.repo??"-";return[e.id,e.state,`spent=${n}/${r}`,t,o].join(" ")}a(le,"formatSandboxLine");function ge(e){let t=e.template?`${e.template.name}@${e.template.version}`:"-",n=e.replay?.retention?.class??e.storageCost?.retentionClass??"-",r=e.replay?.state??"-",o=e.storageCost?.estimatedMonthlyUsd??"-";return[e.id,e.kind,e.name,e.sandboxId,`storage=${e.storage??"-"}`,`sizeGb=${e.sizeGb??"-"}`,`publishedSnapshot=${t}`,`replay=${r}`,`retention=${n}`,`monthlyUsd=${o}`,e.createdAt].join(" ")}a(ge,"formatSnapshotCatalogLine");function fe(e){let t=e.tags&&e.tags.length>0?e.tags.join(","):"-",n=e.replay?.retention?.class??e.storageCost?.retentionClass??"-",r=e.replay?.state??"-",o=e.storageCost?.estimatedMonthlyUsd??"-";return[e.name,`version=${e.version}`,`snapshot=${e.snapshotId}`,`sandbox=${e.sandboxId}`,`visibility=${e.visibility}`,`useCase=${e.useCase??"-"}`,`tags=${t}`,`replay=${r}`,`retention=${n}`,`monthlyUsd=${o}`,e.createdAt].join(" ")}a(fe,"formatSandboxTemplateLine");function be(e){return[e.id,`team=${e.teamId}`,`status=${e.status}`,`publish=${e.publishStatus??"-"}`,`source=${e.sourceRepoUrl}`,`branch=${e.sourceBranch}`,`snapshot=${e.snapshotId??"-"}`,`error=${e.error??"-"}`,e.createdAt??"-"].join(" ")}a(be,"formatTemplateBuildLine");function pe(e){return[e.id,`team=${e.teamId}`,`state=${e.state}`,`snapshot=${e.snapshotId}`,`sandbox=${e.sandboxId??"-"}`,`command=${e.commandId??"-"}`,`exit=${e.exitCode??"-"}`,`cleanup=${e.cleanup.action}:${e.cleanup.status}`,`error=${e.error??"-"}`,e.createdAt].join(" ")}a(pe,"formatReplayLine");function ye(e){return{path:e.path,status:e.status,sizeBytes:e.sizeBytes,error:e.error,...e.contentsBase64?{contentsBase64:e.contentsBase64}:{}}}a(ye,"summarizeReplayArtifact");function he(e){if(typeof e!="string")return;let t=e.trim();if(t==="delete"||t==="stop"||t==="archive")return t;throw new Error("snapshot-validate --cleanup must be delete, stop, or archive")}a(he,"normalizeSnapshotValidationCleanup");function ee(e){if(typeof e!="string")return;let t=e.trim();if(t==="delete"||t==="stop"||t==="archive")return t;throw new Error("replay cleanup must be delete, stop, or archive")}a(ee,"normalizeReplayCleanup");function xe(e){let t=typeof e.snapshotId=="string"&&e.snapshotId.trim()?e.snapshotId.trim():typeof e.snapshot=="string"&&e.snapshot.trim()?e.snapshot.trim():"";if(!t)throw new Error("replay-start requires --snapshot-id <id>");let n=typeof e.teamId=="string"?e.teamId.trim():"",r=typeof e.projectId=="string"?e.projectId.trim():"",o=typeof e.sourceSandboxId=="string"&&e.sourceSandboxId.trim()?e.sourceSandboxId.trim():"",i=typeof e.entrypoint=="string"&&e.entrypoint.trim()?e.entrypoint.trim():"",s=typeof e.params=="string"&&e.params.trim()?A(e.params,"params"):{};if(!s||typeof s!="object"||Array.isArray(s))throw new Error("params must be a JSON object");let l=typeof e.budgetUsd=="string"&&e.budgetUsd.trim()?e.budgetUsd.trim():typeof e.budget=="string"&&e.budget.trim()?e.budget.trim():"",d=p(e.maxDurationSeconds,"max-duration-seconds"),c=p(e.idleTimeoutSeconds,"idle-timeout-seconds"),u=f(e.artifactPaths),g=typeof e.idempotencyKey=="string"&&e.idempotencyKey.trim()?e.idempotencyKey.trim():"",y=ee(e.cleanup);return{snapshotId:t,...n?{teamId:n}:{},...r?{projectId:r}:{},...o?{sourceSandboxId:o}:{},...i?{entrypoint:i}:{},params:s,...l?{budget:{maxUsd:l}}:{},...d!==void 0?{maxDurationSeconds:d}:{},...c!==void 0?{idleTimeoutSeconds:c}:{},...u.length>0?{artifactPaths:u}:{},...g?{idempotencyKey:g}:{},...y?{cleanup:y}:{}}}a(xe,"buildSandboxReplayInput");function Se(e){let t=typeof e.repo=="string"?e.repo.trim():"",n=typeof e.command=="string"&&e.command.trim()?e.command.trim():void 0,r=typeof e.budgetUsd=="string"&&e.budgetUsd.trim()?e.budgetUsd.trim():typeof e.budget=="string"&&e.budget.trim()?e.budget.trim():"0.05",o=k(e.cpu,"cpu"),i=k(e.memoryGb,"memory-gb"),s=k(e.diskGb,"disk-gb"),l=p(e.maxDurationSeconds,"max-duration-seconds"),d=p(e.idleTimeoutSeconds,"idle-timeout-seconds"),c=typeof e.volumeName=="string"&&e.volumeName.trim()?e.volumeName.trim():"",u=typeof e.volumeMountPath=="string"&&e.volumeMountPath.trim()?e.volumeMountPath.trim():"",g=p(e.volumeStorageGb,"volume-storage-gb"),y=e.volumeDeleteOnSandboxDelete!==void 0?v(e.volumeDeleteOnSandboxDelete):void 0,$=typeof e.integrationConnection=="string"?e.integrationConnection.trim():"",U=f(e.integrationCapabilities),O=f(e.integrationScopes),x=typeof e.teamId=="string"?e.teamId.trim():"",P=typeof e.projectId=="string"?e.projectId.trim():"",S=typeof e.runtimeProjectId=="string"?e.runtimeProjectId.trim():"";if(P&&S&&P!==S)throw new Error("project-id and runtime-project-id must match when both are set");let I=P||S,E=typeof e.agentId=="string"?e.agentId.trim():"",w=typeof e.runtimeAgentId=="string"?e.runtimeAgentId.trim():"";if(E&&w&&E!==w)throw new Error("agent-id and runtime-agent-id must match when both are set");let R=E||w,B=z(e.workflowMode),D=V(e.runtimePromotionPolicy),T=oe(e),M=re(e),h=G(e.runtimeProfileId),_=typeof e.runtimeBaseBranch=="string"&&e.runtimeBaseBranch.trim()?e.runtimeBaseBranch.trim():"",j=typeof e.runtimeBaseSha=="string"&&e.runtimeBaseSha.trim()?e.runtimeBaseSha.trim():"",C=typeof e.runtimeId=="string"&&e.runtimeId.trim()?e.runtimeId.trim():"",L=!!(B||D||_||j||h||C||S||w),N=q(e);if($&&U.length===0)throw new Error("integration-capabilities is required with integration-connection");return{sandbox:{...t?{repo:t}:{},...x?{teamId:x}:{},...I?{projectId:I}:{},...R?{agentId:R}:{},...h?{runtimeProfileId:h}:{},...n?{command:n}:{},...T?{workloadSource:T}:{},...M?{sourceArchive:M}:{},resources:{...o!==void 0?{cpu:o}:{},...i!==void 0?{memoryGb:i}:{},...s!==void 0?{diskGb:s}:{}},budget:{maxUsd:r},quotas:{maxSpendUsd:r,...l!==void 0?{maxDurationSeconds:l}:{},...d!==void 0?{idleTimeoutSeconds:d}:{}},...N.length>0?{env:N}:{},...c||u||g!==void 0?{volumes:[{...c?{name:c}:{},...u?{mountPath:u}:{},...g!==void 0?{storageGb:g}:{},...y!==void 0?{deleteOnSandboxDelete:y}:{}}]}:{},...$?{integrationConnectionLeases:[{connectionId:$,...O.length>0?{scopes:O}:{},capabilities:U,ttlSeconds:3600}]}:{},metadata:{source:"openpond-code"}},...L&&C?{runtimeId:C}:{},...L&&!C?{sandboxRuntime:{...x?{teamId:x}:{},...B?{workflowMode:B}:{},...I?{projectId:I}:{},...R?{agentId:R}:{},baseBranch:_||"master",...j?{baseSha:j}:{},...D?{promotionPolicy:D}:{},...h?{runtimeProfileId:h}:{}}}:{}}}a(Se,"buildSandboxCreateInput");function te(e){return e.length>0&&!e.includes("\0")&&!b.isAbsolute(e)&&!e.split(/[\\/]+/).some(t=>!t||t==="."||t==="..")}a(te,"isSafeDockerContextPath");function ne(e){return e.split(/[\\/]+/).some(t=>{let n=t.toLowerCase();return n===".git"||n==="node_modules"||n===".next"||n===".turbo"||n.startsWith(".env")})}a(ne,"shouldSkipDockerContextPath");function J(e){let t=e.baseDir??e.contextRoot,n=H(t,{withFileTypes:!0}),r=[];for(let o of n){let i=b.join(t,o.name),s=b.relative(e.contextRoot,i).replace(/\\/g,"/");if(!(!s||!te(s)||ne(s))){if(o.isDirectory()){r.push(...J({contextRoot:e.contextRoot,baseDir:i}));continue}o.isFile()&&r.push(s)}}return r}a(J,"collectDockerContextFiles");function re(e){if(!m(e.dockerfile))return;let n=m(e.dockerfileContext)||".",r=b.resolve(process.cwd(),n);if(!F(r).isDirectory())throw new Error(`dockerfile context must be a directory: ${n}`);let i=J({contextRoot:r}).sort();if(i.length===0)throw new Error(`dockerfile context has no files: ${n}`);if(i.length>K)throw new Error(`dockerfile context has too many files: ${i.length} > ${K}`);let s=0,l=i.map(d=>{let c=b.resolve(r,d),u=b.relative(r,c);if(u.startsWith("..")||b.isAbsolute(u))throw new Error(`dockerfile context path escapes context: ${d}`);let g=F(c);if(g.size>Z)throw new Error(`dockerfile context file is too large: ${d} (${g.size} bytes)`);if(s+=g.size,s>W)throw new Error(`dockerfile context is too large: ${s} > ${W}`);return{path:d,type:"file",contentsBase64:Y.from(Q(c)).toString("base64")}});return{source:"client_upload",ref:"client-upload",archive:{version:1,createdAt:new Date().toISOString(),entries:l}}}a(re,"buildDockerfileSourceArchiveInput");function oe(e){let t=m(e.image),n=m(e.dockerfile);if(t&&n)throw new Error("sandbox create accepts only one of --image or --dockerfile");let r=m(e.runtimeWorkspaceRoot);if(t)return{image:{ref:t,...m(e.imageDigest)?{digest:m(e.imageDigest)}:{},...m(e.registrySecretRef)?{registrySecretRef:m(e.registrySecretRef)}:{},...r?{workspaceRoot:r}:{},platform:"linux/amd64"}};if(n){let o=ie(e.dockerBuildArgs),i=f(e.dockerRegistrySecretRefs);return{dockerfile:{path:n,context:m(e.dockerfileContext)||".",...m(e.dockerfileTarget)?{target:m(e.dockerfileTarget)}:{},...Object.keys(o).length>0?{buildArgs:o}:{},...i.length>0?{registrySecretRefs:i}:{},...r?{workspaceRoot:r}:{},platform:"linux/amd64"}}}}a(oe,"buildSandboxWorkloadSourceInput");function ie(e){if(typeof e!="string"||!e.trim())return{};let t=A(e,"docker-build-args");if(!t||typeof t!="object"||Array.isArray(t))throw new Error("docker-build-args must be a JSON object");let n={};for(let[r,o]of Object.entries(t)){if(typeof o!="string")throw new Error("docker-build-args values must be strings");n[r]=o}return n}a(ie,"parseDockerBuildArgs");function m(e){return typeof e=="string"?e.trim():""}a(m,"stringOption");function Ie(e){let t=typeof e.integrationConnection=="string"?e.integrationConnection.trim():"",n=f(e.integrationCapabilities),r=f(e.integrationScopes);if(!t||n.length===0)throw new Error("usage: sandbox integration-attach <sandboxId> --integration-connection <id> --integration-capabilities <csv>");return{connectionId:t,...r.length>0?{scopes:r}:{},capabilities:n,ttlSeconds:3600}}a(Ie,"buildSandboxIntegrationAttachInput");function we(e){let t=typeof e.teamId=="string"?e.teamId.trim():"",n=typeof e.sourceRepoUrl=="string"?e.sourceRepoUrl.trim():"",r=typeof e.sourceProjectId=="string"?e.sourceProjectId.trim():"",o=typeof e.branch=="string"?e.branch.trim():"",i=typeof e.manifestPath=="string"?e.manifestPath.trim():"";if(!t)throw new Error("published-snapshot-build-create requires --team-id <id>");if(!n&&!r)throw new Error("published-snapshot-build-create requires --source-repo-url <url> or --source-project-id <id>");return{teamId:t,...n?{sourceRepoUrl:n}:{},...r?{sourceProjectId:r}:{},...o?{branch:o}:{},...i?{manifestPath:i}:{},publish:v(e.publish)}}a(we,"buildTemplateBuildCreateInput");function Re(e){let t=typeof e.name=="string"?e.name.trim():"";if(!t)throw new Error("snapshot-create requires --name <name>");let n=typeof e.templateName=="string"?e.templateName.trim():"",r=typeof e.templateVersion=="string"&&e.templateVersion.trim()?e.templateVersion.trim():"0.1.0",o=typeof e.templateVisibility=="string"&&e.templateVisibility.trim()?e.templateVisibility.trim():"private";if(o!=="private"&&o!=="team")throw new Error("template-visibility must be private or team");let i=typeof e.validationCommand=="string"&&e.validationCommand.trim()?e.validationCommand.trim():"test -d .",s=typeof e.entrypointCommand=="string"&&e.entrypointCommand.trim()?e.entrypointCommand.trim():"true",l=typeof e.useCase=="string"&&e.useCase.trim()?e.useCase.trim():void 0,d=typeof e.description=="string"&&e.description.trim()?e.description.trim():void 0,c=f(e.tags),u={...v(e.async)?{async:!0}:{},name:t,replay:{entrypoints:[{command:s,name:"default"}],retention:{class:"pinned"},safety:{cleanup:"delete",idleTimeoutSeconds:600,internetEgress:"block",maxDurationSeconds:600,maxSpendUsd:"0.05",publicPreview:!1},validation:{commands:[{command:i}]}}};return n&&(u.template={name:n,version:r,...d?{description:d}:{},...c.length>0?{tags:c}:{},visibility:o,...l?{useCase:l}:{}}),u}a(Re,"buildSnapshotCreateInput");function Ce(e){return{id:e.id,state:e.state,repo:e.repo,runtimeId:e.runtimeId??null,repoRef:e.repoRef??null,sourceCommitSha:e.sourceCommitSha??null,budgetUsd:e.budget.maxUsd,capturedUsd:e.reservation.capturedUsd,reservationRef:e.reservation.mpp?.reservationRef??null,mppMode:e.reservation.mpp?.mode??null,integrationLeases:e.integrationLeases?.map(t=>({leaseId:t.leaseId,provider:t.provider,capabilities:t.capabilities}))??[],previewPorts:e.previewPorts.map(t=>({port:t.port,label:t.label,url:t.url,customDomain:t.customDomain??null})),latestReceipt:e.receipts.at(-1)?.mpp.receiptRef??null}}a(Ce,"summarizeSandbox");export{me as a,X as b,le as c,ge as d,fe as e,be as f,pe as g,ye as h,he as i,xe as j,Se as k,Ie as l,we as m,Re as n,Ce as o};
@@ -0,0 +1,12 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{a as n}from"./chunk-FTQLQJQV.js";var N="https://openpond.ai",$="https://api.openpond.ai",k="https://api.openpond.ai/opchat/v1";function C(o){let e=o.trim().replace(/\/$/,"");if(!e)throw new Error("sandbox API URL must be non-empty");let t=new URL(e),r=t.pathname.replace(/\/$/,"");return r.endsWith("/v1/sandboxes")||r.endsWith("/api/sandboxes")?`${t.origin}${r}`:r.endsWith("/v1")?`${t.origin}${r}/sandboxes`:Q(t.hostname)?`${t.origin}${r}/v1/sandboxes`:t.origin===N?`${$}/v1/sandboxes`:`${t.origin}${r}/api/sandboxes`}n(C,"normalizeSandboxApiUrl");function L(o){let e="/sandboxes";if(!o.endsWith(e))throw new Error("sandbox API URL must end with /sandboxes");return o.slice(0,-e.length)}n(L,"apiRootUrlFromSandboxApiUrl");function Q(o){return o==="api.openpond.ai"||o==="staging-api.openpond.ai"||o.startsWith("api")&&o.endsWith(".openpond.ai")}n(Q,"isOpenPondHostedApiHost");function B(o){return{list:n((e={})=>o.listSandboxRuntimes(e),"list"),create:n(e=>o.createSandboxRuntime(e),"create"),handle:n((e,t=null)=>o.sandboxRuntime(e,t),"handle"),get:n(e=>o.getSandboxRuntime(e),"get"),createSandbox:n((e,t={},r={})=>o.createSandboxRuntimeSandbox(e,t,r),"createSandbox"),updateStatus:n((e,t)=>o.updateSandboxRuntimeStatus(e,t),"updateStatus"),events:n(e=>o.listSandboxRuntimeEvents(e),"events"),event:n((e,t)=>o.emitSandboxRuntimeEvent(e,t),"event"),checkpoint:n((e,t={})=>o.checkpointSandboxRuntime(e,t),"checkpoint"),promote:n((e,t,r={})=>o.promoteSandboxRuntime(e,t,r),"promote"),preserveSource:n((e,t={},r={})=>o.preserveSandboxRuntimeSource(e,t,r),"preserveSource")}}n(B,"createSandboxRuntimeNamespace");function z(o){return{list:n((e={})=>o.list(e),"list"),create:n(e=>o.create(e),"create"),get:n(e=>o.get(e),"get"),pricing:n(()=>o.pricing(),"pricing"),costs:n((e={})=>o.costs(e),"costs")}}n(z,"createSandboxNamespace");function D(o){return{list:n(e=>o.listProjects(e),"list"),upsert:n(e=>o.upsertProject(e),"upsert"),upsertGitRemote:n(e=>o.upsertProjectGitRemote(e),"upsertGitRemote"),get:n((e,t)=>o.getProject(e,t),"get"),update:n((e,t)=>o.updateProject(e,t),"update"),sync:n((e,t)=>o.syncProject(e,t),"sync"),ensureGitRemote:n((e,t)=>o.ensureProjectGitRemote(e,t),"ensureGitRemote"),getGitRemote:n((e,t)=>o.ensureProjectGitRemote(e,t),"getGitRemote"),git:n((e,t)=>o.ensureProjectGitRemote(e,t),"git"),uploadSource:n((e,t)=>o.uploadProjectSource(e,t),"uploadSource"),archive:n((e,t)=>o.archiveProject(e,t),"archive")}}n(D,"createSandboxProjectNamespace");function J(o){return{get:n(e=>o.getHostedProfile(e),"get"),status:n(e=>o.getHostedProfile(e),"status"),ensureHosted:n(e=>o.ensureHostedProfile(e),"ensureHosted"),push:n(e=>o.pushHostedProfile(e),"push")}}n(J,"createSandboxProfileNamespace");function M(o){return{list:n(e=>o.listAgents(e),"list"),upsert:n(e=>o.upsertAgent(e),"upsert"),get:n((e,t)=>o.getAgent(e,t),"get"),update:n((e,t)=>o.updateAgent(e,t),"update"),archive:n((e,t)=>o.archiveAgent(e,t),"archive"),run:n((e,t)=>o.runAgent(e,t),"run"),sourceDeployPlan:n((e,t)=>o.getAgentSourceDeployPlan(e,t),"sourceDeployPlan"),manifestSnapshots:n((e,t)=>o.listAgentManifestSnapshots(e,t),"manifestSnapshots"),requestSourceChecks:n((e,t)=>o.requestAgentSourceChecks(e,t),"requestSourceChecks"),configureSourceSetup:n((e,t)=>o.configureAgentSourceSetup(e,t),"configureSourceSetup"),publishSource:n((e,t)=>o.publishAgentSource(e,t),"publishSource")}}n(M,"createSandboxAgentNamespace");function F(o,e,t=null){let r=n(async(a={},d={})=>{let h=await o.getSandboxRuntime(e);return h.sandboxId?o.get(h.sandboxId):o.createSandboxRuntimeSandbox(e,a,d).then(u=>u.sandbox)},"currentSandbox"),s=n(async(a={},d={})=>{let h=await o.getSandboxRuntime(e);if(!h.sandboxId)return o.createSandboxRuntimeSandbox(e,a,d).then(p=>p.sandbox);let u=await o.get(h.sandboxId);return u.state==="stopped"?o.start(u.id,d).then(p=>p.sandbox):u.state==="archived"?o.restore(u.id).then(p=>p.sandbox):u.state==="deleted"||u.state==="error"?o.createSandboxRuntimeSandbox(e,a,d).then(p=>p.sandbox):u},"resume");return{id:e,initial:t,get:n(()=>o.getSandboxRuntime(e),"get"),sandbox:r,resume:s,createSandbox:n((a={},d={})=>o.createSandboxRuntimeSandbox(e,a,d),"createSandbox"),status:n(async a=>{if(typeof a!="string")return o.updateSandboxRuntimeStatus(e,a);let d=await o.getSandboxRuntime(e);return o.updateSandboxRuntimeStatus(e,{status:a,expectedVersion:d.version})},"status"),events:n(()=>o.listSandboxRuntimeEvents(e),"events"),event:n(a=>o.emitSandboxRuntimeEvent(e,a),"event"),recordCommit:n((a,d={})=>o.emitSandboxRuntimeEvent(e,{...d,type:d.type??"git.commit",commitSha:a}),"recordCommit"),checkpointHint:n((a={})=>o.emitSandboxRuntimeEvent(e,{type:"workflow.checkpoint_hint",summary:a.summary??a.reason??"Workflow checkpoint hint",payload:{...a.payload,reason:a.reason??null},artifactRefs:a.artifactRefs,lifecycleHint:{kind:"checkpoint",reason:a.reason??null}}),"checkpointHint"),waitForUser:n(async(a={})=>{await o.emitSandboxRuntimeEvent(e,{type:"workflow.waiting_for_user",summary:a.summary??a.reason??"Waiting for user",payload:{...a.payload,reason:a.reason??null},lifecycleHint:{kind:"waiting_for_user",reason:a.reason??null}});let d=await o.getSandboxRuntime(e);return d.status==="waiting_for_user"?d:o.updateSandboxRuntimeStatus(e,{status:"waiting_for_user",expectedVersion:d.version,summary:a.summary??a.reason,metadata:{workflowWaitForUserReason:a.reason??null}})},"waitForUser"),keepAlive:n((a={})=>{let d=Z(a);return o.emitSandboxRuntimeEvent(e,{type:"workflow.keepalive",summary:a.summary??a.reason??"Workflow keepalive",payload:{...a.payload,reason:a.reason??null,keepaliveUntil:d},lifecycleHint:{kind:"keepalive",reason:a.reason??null,keepaliveUntil:d}})},"keepAlive"),checkpoint:n(a=>o.checkpointSandboxRuntime(e,a),"checkpoint"),files:{write:n(async(a,d)=>o.uploadFile((await s()).id,a,d),"write"),read:n(async a=>o.downloadFile((await s()).id,a),"read"),readResponse:n(async a=>o.downloadFileResponse((await s()).id,a),"readResponse"),list:n(async(a={})=>o.listFiles((await s()).id,a),"list"),delete:n(async(a,d={})=>o.deleteFile((await s()).id,a,d),"delete"),search:n(async a=>o.searchFiles((await s()).id,a),"search"),stat:n(async a=>o.statFile((await s()).id,a),"stat"),mkdir:n(async a=>o.mkdir((await s()).id,a),"mkdir"),move:n(async a=>o.moveFile((await s()).id,a),"move")},commands:{run:n(async a=>o.exec((await s()).id,typeof a=="string"?{command:a}:a),"run")},ports:{expose:n(async a=>o.openPort((await s()).id,typeof a=="number"?{port:a}:a),"expose")},promote:n((a,d={})=>o.promoteSandboxRuntime(e,a,d),"promote"),preserveSource:n((a={},d={})=>o.preserveSandboxRuntimeSource(e,a,d),"preserveSource"),archive:n(async a=>{let d=a??(await o.getSandboxRuntime(e)).version;return o.updateSandboxRuntimeStatus(e,{status:"archived",expectedVersion:d})},"archive")}}n(F,"createSandboxRuntimeHandle");function Z(o){if(o?.until instanceof Date)return o.until.toISOString();if(typeof o?.until=="string"&&o.until.trim())return new Date(o.until).toISOString();let e=typeof o?.seconds=="number"&&Number.isFinite(o.seconds)?Math.max(1,Math.trunc(o.seconds)):60;return new Date(Date.now()+e*1e3).toISOString()}n(Z,"runtimeKeepaliveUntilIso");async function W(o,e={}){let t=`openpond-code-smoke-${Date.now()}`,r=`openpond-code-exec-ok:${t}`,s=`openpond-code-preview-ok:${t}`,i=`openpond-code-file-ok:${t}`,c=4173,m=null,a=null,d=!1,h=!1;try{let u=await G(o,await o.create({repo:e.repo??"https://github.com/octocat/Hello-World",resources:{cpu:e.cpu??1,memoryGb:e.memoryGb??1,diskGb:e.diskGb??8},budget:{maxUsd:e.budgetUsd??"0.05"},quotas:{maxSpendUsd:e.budgetUsd??"0.05",maxDurationSeconds:600,idleTimeoutSeconds:600,maxOpenPorts:2},metadata:{runId:t,source:"openpond-code-sandbox-smoke"}},{async:!0}));m=u.id;let p=e.expectedMppMode;if(p&&u.reservation.mpp?.mode!==p)throw new Error(`expected ${p} reservation, got ${u.reservation.mpp?.mode??"none"}`);if(!p&&!u.reservation.mpp?.mode)throw new Error("expected sandbox reservation MPP metadata");let S=await o.exec(u.id,{command:[`printf '${r}\\n'`,"test -f README && printf 'repo-clone-ok\\n'","cat > server.cjs <<'EOF'","const { createServer } = require('node:http');",`createServer((_request, response) => response.end('${s}')).listen(${c}, '0.0.0.0');`,"EOF","nohup node server.cjs > server.log 2>&1 & sleep 1"].join(`
3
+ `),timeoutSeconds:120});if(S.command.status!=="succeeded")throw new Error(`expected command success, got ${S.command.status}`);if(!S.command.output.includes(r))throw new Error("expected exec marker");if(await o.uploadFile(u.id,"openpond-code-smoke.txt",i),await o.downloadFile(u.id,"openpond-code-smoke.txt")!==i)throw new Error("expected file roundtrip marker");let g=null;if(e.snapshot||e.fork){let f=await o.createSnapshot(u.id,{async:!0,name:`openpond-code-smoke-${t}`,replay:{entrypoints:[{command:"cat openpond-code-smoke.txt",name:"default"}],retention:{class:"pinned"},safety:{cleanup:"delete",idleTimeoutSeconds:600,internetEgress:"block",maxDurationSeconds:600,maxSpendUsd:e.budgetUsd??"0.05",publicPreview:!1},validation:{commands:[{command:"test -f openpond-code-smoke.txt"}]}}}),l=f.snapshot??(await re(o,u.id,f.snapshotJob?.snapshotId)).snapshot;if(g=l.id,l.state!=="ready")throw new Error(`expected ready snapshot, got ${l.state}`)}if(e.fork){if(!g)throw new Error("expected snapshot id before fork");let f=await G(o,(await o.forkSnapshot(g,{budget:{maxUsd:e.budgetUsd??"0.05"},metadata:{source:"openpond-code-sandbox-smoke-fork",templateSnapshotId:g}},{async:!0})).sandbox);a=f.id;let l=await o.exec(f.id,{command:"cat openpond-code-smoke.txt",timeoutSeconds:120});if(l.command.status!=="succeeded")throw new Error(`expected fork command success, got ${l.command.status}`);if(!l.command.output.includes(i))throw new Error("expected fork snapshot marker");e.keep||(await v(o,f.id),h=!0)}let P=null;if(e.preview!==!1){let f=await o.openPort(u.id,{label:"openpond-code-smoke",port:c}),l=await fetch(f.preview.url);P=l.status;let X=await l.text();if(l.status!==200)throw new Error(`expected preview HTTP 200, got ${l.status}`);if(!X.includes(s))throw new Error("expected preview marker")}let{sandbox:U,receipts:I}=await ee(o,u.id);return e.keep||(await v(o,u.id),d=!0),{deleted:d,execOutput:S.command.output.trim(),fileRoundtrip:!0,forkSandboxId:a,previewStatus:P,receiptRefs:I.map(f=>f.mpp.receiptRef??null),reservationRef:u.reservation.mpp?.reservationRef??null,runId:t,sandboxId:u.id,snapshotId:g,state:U.state}}finally{a&&!e.keep&&!h&&await H(o,a),m&&!e.keep&&!d&&await H(o,m)}}n(W,"runSandboxSmoke");async function ee(o,e){try{await o.stop(e)}catch{await o.stop(e,{async:!0})}let t=await K(o,e,new Set(["stopped","deleted"]),"stop"),r=await te(o,e);if(r.length===0)throw new Error("expected receipt readback");return{sandbox:t,receipts:r}}n(ee,"stopSandboxForSmoke");async function v(o,e){try{let t=await o.delete(e);if(t.state==="deleted")return t;await o.delete(e,{async:!0})}catch{await o.delete(e,{async:!0})}return K(o,e,new Set(["deleted"]),"delete")}n(v,"deleteSandboxForSmoke");async function H(o,e){try{await v(o,e)}catch{await o.delete(e,{async:!0}).catch(()=>{})}}n(H,"cleanupSandboxBestEffort");async function K(o,e,t,r){let c=Date.now()+3e5,m=await o.get(e);for(;Date.now()<c;){if(t.has(m.state))return m;if(m.state==="error")throw new Error(`sandbox ${r} failed: ${e}`);await q(3e3),m=await o.get(e)}throw new Error(`sandbox ${r} did not reach ${[...t].join("/")} before timeout: ${e} (${m.state})`)}n(K,"waitForSandboxState");async function te(o,e){let s=Date.now()+12e4,i=await o.receipts(e);for(;Date.now()<s;){if(i.length>0)return i;await q(3e3),i=await o.receipts(e)}return i}n(te,"waitForReceipts");async function G(o,e){if(e.state==="running"||e.state==="stopped")return e;if(e.state==="error")throw new Error(`sandbox create failed: ${e.id}
4
+ ${e.logs.join(`
5
+ `)}`);let t=12*6e4,r=3e3,s=Date.now()+t,i=e;for(;Date.now()<s;){if(await q(r),i=await o.get(e.id),i.state==="running"||i.state==="stopped")return i;if(i.state==="error")throw new Error(`sandbox create failed: ${i.id}
6
+ ${i.logs.join(`
7
+ `)}`)}throw new Error(`sandbox create did not reach running state before timeout: ${i.id} (${i.state})`)}n(G,"waitForCreateReady");async function re(o,e,t){if(!t)throw new Error("snapshot job did not return snapshot id");let r=12*6e4,s=3e3,i=Date.now()+r,c=await o.get(e);for(;Date.now()<i;){let m=c.snapshots?.find(d=>d.id===t);if(m?.state==="ready")return{sandbox:c,snapshot:m};let a=c.snapshotJobs?.find(d=>d.snapshotId===t);if(a?.status==="failed")throw new Error(`snapshot job failed: ${a.error??t}`);await q(s),c=await o.get(e)}throw new Error(`snapshot did not reach ready state before timeout: ${t}`)}n(re,"waitForSnapshotReady");function q(o){return new Promise(e=>setTimeout(e,o))}n(q,"sleep");function R(o={}){return o.async||o.respondAsync?{Prefer:"respond-async"}:void 0}n(R,"asyncRequestHeaders");var O=class extends Error{static{n(this,"ApiTimeoutError")}timeoutMs;requestUrl;code="OPENPOND_API_TIMEOUT";constructor(e,t){super(`API request timed out after ${e}ms: ${t}`),this.timeoutMs=e,this.requestUrl=t,this.name="ApiTimeoutError"}},b=class extends Error{static{n(this,"ApiResponseTooLargeError")}maximumBytes;requestUrl;code="OPENPOND_API_RESPONSE_TOO_LARGE";constructor(e,t){super(`API response exceeded ${e} bytes: ${t}`),this.maximumBytes=e,this.requestUrl=t,this.name="ApiResponseTooLargeError"}},E=class extends Error{static{n(this,"OpenPondApiError")}status;apiMessage;code;constructor(e,t,r,s=null){let i=s||t;super(`${r} failed: ${e}${i?` ${i}`:""}`),this.status=e,this.apiMessage=s,this.name="OpenPondApiError",this.code=t||"OPENPOND_API_ERROR"}};async function w(o,e,t,r={}){let{timeoutMs:s=3e4,maxResponseBytes:i=8388608,...c}=r,m=`${o}${t}`,a=new Headers(c.headers);a.set("Content-Type","application/json");let d=process.env.OPENPOND_API_KEY,h=e?.trim()||"",u=h.startsWith("opk_"),p=d||(u?h:null);p&&!a.has("openpond-api-key")&&a.set("openpond-api-key",p),e?a.set("Authorization",u?`ApiKey ${h}`:`Bearer ${e}`):d&&!a.has("Authorization")&&a.set("Authorization",`ApiKey ${d}`);let S=new AbortController,x=new O(s,m),g=s>0?setTimeout(()=>S.abort(x),s):null;g?.unref?.();let P=se(c.signal,S.signal,s),U=n(()=>{g&&clearTimeout(g)},"cleanup");try{let I=await fetch(m,{...c,headers:a,signal:P});return oe(I,{cleanup:U,maximumBytes:i,requestUrl:m,timeoutController:S,timeoutError:x})}catch(I){throw U(),S.signal.aborted?x:I}}n(w,"apiFetch");async function T(o,e){let t;try{let r=await o.text();t=r?JSON.parse(r):{}}catch(r){if(r instanceof O||r instanceof b)throw r;t={}}if(!o.ok){let r=typeof t.error=="string"?t.error:null,s=typeof t.message=="string"?t.message:null;throw new E(o.status,r,e,s)}return t}n(T,"readApiJson");function oe(o,e){if(!o.body)return e.cleanup(),o;let t=Number(o.headers.get("content-length"));if(e.maximumBytes>0&&Number.isFinite(t)&&t>e.maximumBytes)throw e.cleanup(),o.body.cancel(),new b(e.maximumBytes,e.requestUrl);let r=o.body.getReader(),s=0,i=new ReadableStream({async pull(c){try{let m=await r.read();if(m.done){e.cleanup(),c.close();return}if(s+=m.value.byteLength,e.maximumBytes>0&&s>e.maximumBytes){e.cleanup(),await r.cancel(),c.error(new b(e.maximumBytes,e.requestUrl));return}c.enqueue(m.value)}catch(m){e.cleanup(),c.error(e.timeoutController.signal.aborted?e.timeoutError:m)}},async cancel(c){e.cleanup(),await r.cancel(c)}});return new Response(i,{headers:o.headers,status:o.status,statusText:o.statusText})}n(oe,"boundedResponse");function se(o,e,t){return t<=0?o??void 0:o?AbortSignal.any([o,e]):e}n(se,"composedSignal");async function j(o){let e=await w(o.sandboxApiUrl,o.apiKey,o.path,{timeoutMs:0,maxResponseBytes:0});if(!e.body)return;let t=e.body.getReader(),r=new TextDecoder,s="";try{for(;;){let{done:i,value:c}=await t.read();if(i)break;s+=r.decode(c,{stream:!0});let m=s.indexOf(`
8
+
9
+ `);for(;m!==-1;){let a=s.slice(0,m);s=s.slice(m+2);let d=ne(a);d&&process.stdout.write(d),m=s.indexOf(`
10
+
11
+ `)}}}finally{t.releaseLock()}}n(j,"streamSandboxEventOutput");function Y(o){return typeof o=="string"?{dataBase64:Buffer.from(o,"utf-8").toString("base64")}:o instanceof Uint8Array?{dataBase64:Buffer.from(o).toString("base64")}:o}n(Y,"normalizePtyInput");function ne(o){if(!o.includes("event: output"))return null;let e=o.split(/\r?\n/).filter(t=>t.startsWith("data: ")).map(t=>t.slice(6));if(e.length===0)return null;try{let t=JSON.parse(e.join(`
12
+ `));return typeof t.output=="string"?t.output:null}catch{return null}}n(ne,"parseProcessOutputEvent");var A=class{static{n(this,"OpenPondSandboxInstanceClient")}apiKey;apiRootUrl;sandboxApiUrl;constructor(e){this.apiKey=e.apiKey,this.sandboxApiUrl=C(e.sandboxApiUrl??e.baseUrl??$),this.apiRootUrl=L(this.sandboxApiUrl)}create(e,t={}){return this.request("",{method:"POST",headers:R(t),body:JSON.stringify(e)}).then(r=>r.sandbox)}get(e){return this.request(`/${encodeURIComponent(e)}`).then(t=>t.sandbox)}exec(e,t){return this.request(`/${encodeURIComponent(e)}/exec`,{method:"POST",body:JSON.stringify(t)})}startProcess(e,t){return this.request(`/${encodeURIComponent(e)}/processes`,{method:"POST",body:JSON.stringify(t)})}listProcesses(e){return this.request(`/${encodeURIComponent(e)}/processes`)}getProcess(e,t,r={}){let s=new URLSearchParams;return r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),this.request(`/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}${s.size>0?`?${s.toString()}`:""}`)}stopProcess(e,t){return this.request(`/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}`,{method:"DELETE"})}async streamProcessOutput(e,t,r={}){let s=new URLSearchParams;r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),await j({sandboxApiUrl:this.sandboxApiUrl,apiKey:this.apiKey,path:`/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}/stream${s.size>0?`?${s.toString()}`:""}`})}startPty(e,t={}){return this.request(`/${encodeURIComponent(e)}/pty`,{method:"POST",body:JSON.stringify(t)})}listPtys(e){return this.request(`/${encodeURIComponent(e)}/pty`)}getPty(e,t,r={}){let s=new URLSearchParams;return r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),this.request(`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}${s.size>0?`?${s.toString()}`:""}`)}writePtyInput(e,t,r){return this.request(`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}/input`,{method:"POST",body:JSON.stringify(Y(r))})}stopPty(e,t){return this.request(`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}`,{method:"DELETE"})}async streamPtyOutput(e,t,r={}){let s=new URLSearchParams;r.since!==void 0&&s.set("since",String(Math.max(0,r.since))),await j({sandboxApiUrl:this.sandboxApiUrl,apiKey:this.apiKey,path:`/${encodeURIComponent(e)}/pty/${encodeURIComponent(t)}/stream${s.size>0?`?${s.toString()}`:""}`})}uploadFile(e,t,r){return this.uploadFileBase64(e,t,Buffer.from(r,"utf-8").toString("base64"))}uploadFileBase64(e,t,r){return this.request(`/${encodeURIComponent(e)}/files`,{method:"POST",body:JSON.stringify({path:t,contentsBase64:r})})}async downloadFile(e,t){let r=await this.downloadFileResponse(e,t);return Buffer.from(r.file.contentsBase64,"base64").toString("utf-8")}downloadFileResponse(e,t){let r=typeof t=="string"?{path:t}:t,s=new URLSearchParams({path:r.path});return r.offsetBytes!==void 0&&s.set("offsetBytes",String(r.offsetBytes)),r.maxBytes!==void 0&&s.set("maxBytes",String(r.maxBytes)),this.request(`/${encodeURIComponent(e)}/files?${s.toString()}`)}listFiles(e,t={}){let r=new URLSearchParams({list:"1"});return t.path&&r.set("path",t.path),t.recursive!==void 0&&r.set("recursive",String(t.recursive)),t.maxEntries!==void 0&&r.set("maxEntries",String(t.maxEntries)),this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`)}deleteFile(e,t,r={}){let s=new URLSearchParams({path:t});return r.recursive!==void 0&&s.set("recursive",String(r.recursive)),this.request(`/${encodeURIComponent(e)}/files?${s.toString()}`,{method:"DELETE"})}statFile(e,t){let r=new URLSearchParams({stat:"1",path:t});return this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`)}mkdir(e,t){let r=typeof t=="string"?{path:t}:t,s=new URLSearchParams({path:r.path});return r.recursive!==void 0&&s.set("recursive",String(r.recursive)),this.request(`/${encodeURIComponent(e)}/files?${s.toString()}`,{method:"PUT"})}moveFile(e,t){let r=new URLSearchParams({fromPath:t.fromPath,toPath:t.toPath});return t.overwrite!==void 0&&r.set("overwrite",String(t.overwrite)),this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`,{method:"PATCH"})}searchFiles(e,t){let r=new URLSearchParams({search:"1",query:t.query});return t.path&&r.set("path",t.path),t.maxResults!==void 0&&r.set("maxResults",String(t.maxResults)),this.request(`/${encodeURIComponent(e)}/files?${r.toString()}`)}openPort(e,t){return this.request(`/${encodeURIComponent(e)}/ports`,{method:"POST",body:JSON.stringify(t)})}createSnapshot(e,t){return this.request(`/${encodeURIComponent(e)}/snapshots`,{method:"POST",body:JSON.stringify(t)})}updateSnapshot(e,t,r){return this.request(`/${encodeURIComponent(e)}/snapshots/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)})}validateSnapshot(e,t,r={}){return this.request(`/${encodeURIComponent(e)}/snapshots/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(r)})}publishSnapshot(e,t){return this.request(`/${encodeURIComponent(e)}/snapshots/${encodeURIComponent(t)}/publish`,{method:"POST"})}fork(e,t={}){return this.request(`/${encodeURIComponent(e)}/fork`,{method:"POST",body:JSON.stringify(t)})}stop(e,t={}){let r=new URLSearchParams;return t.failOnUnpreservedChanges&&r.set("failOnUnpreservedChanges","true"),this.request(`/${encodeURIComponent(e)}/stop${r.size>0?`?${r.toString()}`:""}`,{method:"POST",headers:R(t)})}start(e,t={}){return this.request(`/${encodeURIComponent(e)}/start`,{method:"POST",headers:R(t)})}restore(e){return this.request(`/${encodeURIComponent(e)}/restore`,{method:"POST"})}delete(e,t={}){let r=new URLSearchParams;return t.failOnUnpreservedChanges&&r.set("failOnUnpreservedChanges","true"),this.request(`/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`,{method:"DELETE",headers:R(t)}).then(s=>s.sandbox)}receipts(e){return this.request(`/${encodeURIComponent(e)}/receipts`).then(t=>t.receipts)}logs(e){return this.request(`/${encodeURIComponent(e)}/logs`).then(t=>t.logs)}gitStatus(e){return this.request(`/${encodeURIComponent(e)}/git/status`)}gitDiff(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/diff`,{method:"POST",body:JSON.stringify(t)})}gitExportPatch(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/export-patch`,{method:"POST",body:JSON.stringify(t)})}gitBranch(e,t){return this.request(`/${encodeURIComponent(e)}/git/branch`,{method:"POST",body:JSON.stringify(t)})}gitCommit(e,t){return this.request(`/${encodeURIComponent(e)}/git/commit`,{method:"POST",body:JSON.stringify(t)})}gitPull(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/pull`,{method:"POST",body:JSON.stringify(t)})}gitPush(e,t={}){return this.request(`/${encodeURIComponent(e)}/git/push`,{method:"POST",body:JSON.stringify(t)})}billing(e){return this.request(`/${encodeURIComponent(e)}/billing`)}pricing(){return this.request("/pricing")}costs(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),this.request(`/costs${t.size>0?`?${t.toString()}`:""}`)}integrationLeases(e){return this.request(`/${encodeURIComponent(e)}/integrations`)}attachIntegrationConnection(e,t){return this.request(`/${encodeURIComponent(e)}/integrations`,{method:"POST",body:JSON.stringify(t)})}removeIntegrationLease(e,t){return this.request(`/${encodeURIComponent(e)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:t})})}async request(e,t={}){let r=await w(this.sandboxApiUrl,this.apiKey,e,t);return T(r,"Sandbox request")}async requestApiRoot(e,t={}){let r=await w(this.apiRootUrl,this.apiKey,e,t);return T(r,"OpenPond API request")}};var _=class extends A{static{n(this,"OpenPondSandboxClient")}runtimes=B(this);sandboxes=z(this);profile=J(this);projects=D(this);agents=M(this);list(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),this.request(t.size>0?`?${t.toString()}`:"").then(r=>r.sandboxes)}listSecrets(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),this.requestApiRoot(`/sandbox-secrets${t.size>0?`?${t.toString()}`:""}`).then(r=>r.secrets)}getSecret(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`).then(s=>s.secret)}createSecret(e){return this.requestApiRoot("/sandbox-secrets",{method:"POST",body:JSON.stringify(e)}).then(t=>t.secret)}rotateSecret(e,t){let r=new URLSearchParams;t.teamId&&r.set("teamId",t.teamId);let{teamId:s,...i}=t;return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}/rotate${r.size>0?`?${r.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)}).then(c=>c.secret)}attachSecret(e,t){let r=new URLSearchParams;t.teamId&&r.set("teamId",t.teamId);let{teamId:s,...i}=t;return this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}/attach${r.size>0?`?${r.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)}).then(c=>c.secret)}revokeSecret(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}/revoke${r.size>0?`?${r.toString()}`:""}`,{method:"POST"}).then(s=>s.secret)}deleteSecret(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),this.requestApiRoot(`/sandbox-secrets/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`,{method:"DELETE"}).then(s=>s.secret)}snapshotCatalog(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),e.q&&t.set("q",e.q),e.kind&&t.set("kind",e.kind),e.replayState&&t.set("replayState",e.replayState),e.visibility&&t.set("visibility",e.visibility),e.tag&&t.set("tag",e.tag),e.useCase&&t.set("useCase",e.useCase),e.limit&&t.set("limit",String(e.limit)),this.request(`/catalog/snapshots${t.size>0?`?${t.toString()}`:""}`)}listSandboxRuntimes(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),this.requestApiRoot(`/runtimes${t.size>0?`?${t.toString()}`:""}`).then(r=>r.runtimes)}listProjects(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/projects?${t.toString()}`).then(r=>r.projects)}upsertProject(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/projects?${t.toString()}`,{method:"POST",body:JSON.stringify(e)}).then(r=>r.project)}getHostedProfile(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/profile?${t.toString()}`).then(r=>r.profile)}ensureHostedProfile(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/profile/ensure?${t.toString()}`,{method:"POST"}).then(r=>{if(!r.profile)throw new Error("hosted_profile_missing");return r.profile})}pushHostedProfile(e){let t=new URLSearchParams({teamId:e.teamId}),{teamId:r,...s}=e;return this.requestApiRoot(`/profile/push?${t.toString()}`,{method:"POST",body:JSON.stringify(s)})}async upsertProjectGitRemote(e){let t=await this.upsertProject(e);return this.ensureProjectGitRemote(t.id,{teamId:e.teamId})}getProject(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}?${r.toString()}`).then(s=>s.project)}syncProject(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}/sync?${r.toString()}`,{method:"POST"}).then(s=>s.project)}ensureProjectGitRemote(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}/git?${r.toString()}`,{method:"POST"})}uploadProjectSource(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/projects/${encodeURIComponent(e)}/source?${r.toString()}`,{method:"POST",body:JSON.stringify(i)}).then(c=>c.project)}updateProject(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/projects/${encodeURIComponent(e)}?${r.toString()}`,{method:"PATCH",body:JSON.stringify(i)}).then(c=>c.project)}archiveProject(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/projects/${encodeURIComponent(e)}?${r.toString()}`,{method:"DELETE"}).then(s=>s.project)}listAgents(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/agents?${t.toString()}`).then(r=>r.agents)}upsertAgent(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/agents?${t.toString()}`,{method:"POST",body:JSON.stringify(e)}).then(r=>r.agent)}getAgent(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(e)}?${r.toString()}`).then(s=>s.agent)}archiveAgent(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(e)}?${r.toString()}`,{method:"DELETE"}).then(s=>s.agent)}updateAgent(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}?${r.toString()}`,{method:"PATCH",body:JSON.stringify(i)}).then(c=>c.agent)}runAgent(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/run?${r.toString()}`,{method:"POST",headers:{Prefer:"respond-async"},body:JSON.stringify(i)})}getAgentSourceDeployPlan(e,t){let r=new URLSearchParams({teamId:t.teamId});return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/deploy-plan?${r.toString()}`).then(s=>s.deployPlan)}listAgentManifestSnapshots(e,t){let r=new URLSearchParams({teamId:t.teamId});return t.limit!==void 0&&r.set("limit",String(t.limit)),this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/manifest-snapshots?${r.toString()}`).then(s=>s.manifestSnapshots)}requestAgentSourceChecks(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/checks?${r.toString()}`,{method:"POST",body:JSON.stringify(i),timeoutMs:900*1e3})}configureAgentSourceSetup(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/setup?${r.toString()}`,{method:"POST",body:JSON.stringify(i)})}publishAgentSource(e,t){let r=new URLSearchParams({teamId:t.teamId}),{teamId:s,...i}=t;return this.requestApiRoot(`/agents/${encodeURIComponent(e)}/source/publish?${r.toString()}`,{method:"POST",body:JSON.stringify(i)})}getMicrosoftTeamsBotOverview(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/teams/bot/overview?${t.toString()}`)}bindMicrosoftTeamsBotConversation(e){return this.requestApiRoot("/teams/bot/bindings",{method:"POST",body:JSON.stringify(e)})}rebindMicrosoftTeamsBotConversation(e,t){return this.requestApiRoot(`/teams/bot/bindings/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}unlinkMicrosoftTeamsBotConversation(e){return this.requestApiRoot(`/teams/bot/bindings/${encodeURIComponent(e.bindingId)}`,{method:"DELETE",body:JSON.stringify({teamId:e.teamId})})}sendMicrosoftTeamsBotDiagnostic(e){return this.requestApiRoot("/teams/bot/diagnostics",{method:"POST",body:JSON.stringify(e)})}sendMicrosoftTeamsBotDiagnosticRun(e){return this.requestApiRoot("/teams/bot/diagnostics/run",{method:"POST",body:JSON.stringify(e)})}createSandboxRuntime(e){return this.requestApiRoot("/runtimes",{method:"POST",body:JSON.stringify(e)}).then(t=>t.runtime)}sandboxRuntime(e,t=null){return F(this,e,t)}getSandboxRuntime(e){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}`).then(t=>t.runtime)}createSandboxRuntimeSandbox(e,t={},r={}){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/sandbox`,{method:"POST",headers:R(r),body:JSON.stringify(t)})}updateSandboxRuntimeStatus(e,t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/status`,{method:"PATCH",body:JSON.stringify(t)}).then(r=>r.runtime)}listSandboxRuntimeEvents(e){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/events`)}emitSandboxRuntimeEvent(e,t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/events`,{method:"POST",body:JSON.stringify(t)})}checkpointSandboxRuntime(e,t){return this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/checkpoints`,{method:"POST",body:JSON.stringify(t)}).then(r=>r.runtime)}promoteSandboxRuntime(e,t,r={}){let s=new URLSearchParams;return r.teamId&&s.set("teamId",r.teamId),this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/promote${s.size>0?`?${s.toString()}`:""}`,{method:"POST",body:JSON.stringify(t)})}preserveSandboxRuntimeSource(e,t={},r={}){let s=new URLSearchParams;return r.teamId&&s.set("teamId",r.teamId),this.requestApiRoot(`/runtimes/${encodeURIComponent(e)}/preserve-source${s.size>0?`?${s.toString()}`:""}`,{method:"POST",body:JSON.stringify(t)})}forkSnapshot(e,t={},r={}){let s=new URLSearchParams;t.teamId&&s.set("teamId",t.teamId),t.projectId&&s.set("projectId",t.projectId),r.async&&s.set("async","1");let{teamId:i,projectId:c,...m}=t;return this.request(`/catalog/snapshots/${encodeURIComponent(e)}/fork${s.size>0?`?${s.toString()}`:""}`,{method:"POST",headers:r.async?{Prefer:"respond-async"}:void 0,body:JSON.stringify({...m,snapshotId:e})})}templates(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.q&&t.set("q",e.q),e.name&&t.set("name",e.name),e.version&&t.set("version",e.version),e.visibility&&t.set("visibility",e.visibility),e.tag&&t.set("tag",e.tag),e.useCase&&t.set("useCase",e.useCase),e.limit&&t.set("limit",String(e.limit)),this.request(`/templates${t.size>0?`?${t.toString()}`:""}`)}publishedSnapshots(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.q&&t.set("q",e.q),e.name&&t.set("name",e.name),e.version&&t.set("version",e.version),e.visibility&&t.set("visibility",e.visibility),e.tag&&t.set("tag",e.tag),e.useCase&&t.set("useCase",e.useCase),e.limit&&t.set("limit",String(e.limit)),this.request(`/published-snapshots${t.size>0?`?${t.toString()}`:""}`).then(r=>{let s=r.publishedSnapshots??r.templates;return{...r,templates:s,publishedSnapshots:s}})}launchTemplate(e){let t=new URLSearchParams;e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId);let{teamId:r,projectId:s,...i}=e;return this.request(`/templates/launch${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)})}runPublishedSnapshot(e){let t=new URLSearchParams;e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId);let{teamId:r,projectId:s,...i}=e;return this.request(`/published-snapshots/launch${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)}).then(c=>{let m=c.publishedSnapshot??c.template;return{...c,template:m,publishedSnapshot:m}})}listSchedules(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.sourceSandboxId&&t.set("sourceSandboxId",e.sourceSandboxId),this.request(`/schedules${t.size>0?`?${t.toString()}`:""}`)}createSchedule(e){let t=new URLSearchParams;e.projectId&&t.set("projectId",e.projectId);let{projectId:r,...s}=e;return this.request(`/schedules${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(s)})}getSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`)}updateSchedule(e,t){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}deleteSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"DELETE"})}listScheduleRuns(e,t={}){let r=new URLSearchParams;return t.limit!==void 0&&r.set("limit",String(t.limit)),this.request(`/schedules/${encodeURIComponent(e)}/runs${r.size>0?`?${r.toString()}`:""}`)}runScheduleNow(e,t={}){return this.request(`/schedules/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t)})}listTemplateBuilds(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/sandbox-template-builds?${t.toString()}`).then(r=>r.builds)}createTemplateBuild(e){return this.requestApiRoot("/sandbox-template-builds",{method:"POST",body:JSON.stringify(e)}).then(t=>t.build)}getTemplateBuild(e){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(e)}`).then(t=>t.build)}getTemplateBuildLogs(e){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(e)}/logs`)}cancelTemplateBuild(e){return this.requestApiRoot(`/sandbox-template-builds/${encodeURIComponent(e)}/cancel`,{method:"POST"}).then(t=>t.build)}listPublishedSnapshotBuilds(e){let t=new URLSearchParams({teamId:e.teamId});return this.requestApiRoot(`/published-snapshot-builds?${t.toString()}`).then(r=>r.builds)}createPublishedSnapshotBuild(e){return this.requestApiRoot("/published-snapshot-builds",{method:"POST",body:JSON.stringify(e)}).then(t=>t.build)}getPublishedSnapshotBuild(e){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(e)}`).then(t=>t.build)}getPublishedSnapshotBuildLogs(e){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(e)}/logs`)}cancelPublishedSnapshotBuild(e){return this.requestApiRoot(`/published-snapshot-builds/${encodeURIComponent(e)}/cancel`,{method:"POST"}).then(t=>t.build)}listOrganizations(){return this.requestApiRoot("/organizations").then(e=>e.organizations??e.teams??[])}createOrganization(e){return this.requestApiRoot("/organizations",{method:"POST",body:JSON.stringify(e)}).then(t=>t.organization)}getOrganization(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}`).then(t=>t.organization)}updateOrganization(e,t){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)}).then(r=>r.organization)}listOrganizationMembers(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/members`).then(t=>t.members)}upsertOrganizationMember(e,t){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/members`,{method:"POST",body:JSON.stringify(t)}).then(r=>r.member)}getOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server`).then(t=>t.mcpServer)}generateOrganizationMcpServer(e,t={}){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server`,{method:"POST",body:JSON.stringify(t)}).then(r=>r.mcpServer)}rotateOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server/rotate`,{method:"POST"}).then(t=>t.mcpServer)}disableOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server/disable`,{method:"POST"}).then(t=>t.mcpServer)}enableOrganizationMcpServer(e){return this.requestApiRoot(`/organizations/${encodeURIComponent(e)}/mcp-server/enable`,{method:"POST"}).then(t=>t.mcpServer)}startReplay(e){let t=new URLSearchParams;e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId);let{teamId:r,projectId:s,...i}=e;return this.requestApiRoot(`/sandbox-replays${t.size>0?`?${t.toString()}`:""}`,{method:"POST",body:JSON.stringify(i)})}listReplays(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),this.requestApiRoot(`/sandbox-replays${t.size>0?`?${t.toString()}`:""}`)}getReplay(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}${r.size>0?`?${r.toString()}`:""}`)}getReplayLogs(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}/logs${r.size>0?`?${r.toString()}`:""}`)}getReplayArtifacts(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}/artifacts${r.size>0?`?${r.toString()}`:""}`)}cancelReplay(e,t={}){let r=new URLSearchParams;return t.teamId&&r.set("teamId",t.teamId),t.projectId&&r.set("projectId",t.projectId),this.requestApiRoot(`/sandbox-replays/${encodeURIComponent(e)}/cancel${r.size>0?`?${r.toString()}`:""}`,{method:"POST"})}integrationConnections(e={}){let t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),e.status&&t.set("status",e.status),this.requestApiRoot(`/integrations/connections${t.size>0?`?${t.toString()}`:""}`)}mcpServerConfig(){return{name:"openpond-sandboxes",transport:"streamable-http",url:`${this.sandboxApiUrl}/mcp`,headers:{"openpond-api-key":this.apiKey}}}smoke(e={}){return W(this,e)}};function De(o){return new _(o)}n(De,"createOpenPondSandboxClient");import{randomUUID as ae}from"node:crypto";function ie(o){let e=y(o);if(!e)throw new Error("apiBaseUrl is required");return e}n(ie,"normalizeApiBaseUrl");function V(o){return o.replace(/\/+$/,"")}n(V,"trimTrailingSlashes");function y(o){let e=V(o?.trim()??"");return e?(e=e.replace(/\/chat\/completions$/i,"").replace(/\/models(?:\/[^/]+)?$/i,""),e.endsWith("/opchat/v1")?e:e.endsWith("/opchat")?`${e}/v1`:(e.endsWith("/v1")&&(e=e.slice(0,-3)),`${V(e)}/opchat/v1`)):null}n(y,"normalizeOptionalOpChatApiBaseUrl");function We(o={}){let e=o.env??(typeof process<"u"?process.env:{}),t=y(o.opChatApiBaseUrl)??y(e.OPENPOND_OPCHAT_API_URL);if(t)return t;let r=y(o.chatApiBaseUrl)??y(e.OPENPOND_CHAT_API_URL)??y(e.OPENPOND_GATEWAY_URL);return r||(y(o.apiBaseUrl)??y(e.OPENPOND_API_URL)??k)}n(We,"resolveOpChatApiBaseUrl");function de(o){let e=o.trim();if(!e)throw new Error("OpenPond API key is required");return e}n(de,"requireToken");function ce(o,e,t){let r=new Headers;return r.set("Authorization",`Bearer ${de(o)}`),r.set("Content-Type","application/json"),r.set("Accept",e),r.set("x-openpond-client","openpond-code"),r.set("x-openpond-request-id",t||ae()),r}n(ce,"hostedHeaders");async function me(o){let e=await o.text().catch(()=>"");if(!e)return o.statusText||`HTTP ${o.status}`;try{let t=JSON.parse(e),r=typeof t.error=="string"||t.error&&typeof t.error=="object"&&!Array.isArray(t.error)?t.error:null,s=typeof t.code=="string"?t.code:r&&typeof r!="string"&&typeof r.code=="string"?r.code:null,i=typeof t.message=="string"?t.message:r&&typeof r!="string"&&typeof r.message=="string"?r.message:null,c=typeof r=="string"?r:r&&typeof r.type=="string"?r.type:null;return[s,c,i].filter(Boolean).join(": ")||e}catch{return e}}n(me,"readError");function ue(o,e){let t={model:o.model,messages:o.messages,stream:e};typeof o.temperature=="number"&&(t.temperature=o.temperature),typeof o.maxTokens=="number"&&(t.max_tokens=o.maxTokens),o.tools&&(t.tools=o.tools);let r=o.toolChoice??o.tool_choice;return r!==void 0&&(t.tool_choice=r),o.metadata&&(t.metadata=o.metadata),t}n(ue,"buildHostedChatBody");async function Ke(o){let t=`${ie(o.apiBaseUrl)}/chat/completions`,r=await fetch(t,{method:"POST",headers:ce(o.token,"application/json",o.requestId),body:JSON.stringify(ue(o,!1)),signal:o.signal});if(!r.ok)throw new Error(`Hosted chat failed: ${r.status} ${await me(r)}`);return await r.json()}n(Ke,"sendHostedChatTurn");export{E as a,w as b,T as c,N as d,$ as e,C as f,_ as g,De as h,We as i,Ke as j};