open-axle 0.0.0-stage → 0.1.141
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.
- package/.webpack/main/index.js +2 -0
- package/.webpack/main/native_modules/build/Release/cpufeatures.node +0 -0
- package/.webpack/main/native_modules/lib/protocol/crypto/build/Release/sshcrypto.node +0 -0
- package/.webpack/main/native_modules/pagent.exe +0 -0
- package/.webpack/renderer/1118/index.js +3 -0
- package/.webpack/renderer/1118/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/1122/index.js +3 -0
- package/.webpack/renderer/1122/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/1282/index.js +3 -0
- package/.webpack/renderer/1282/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/1420/index.js +3 -0
- package/.webpack/renderer/1420/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/1438/index.js +3 -0
- package/.webpack/renderer/1438/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/1446/index.js +3 -0
- package/.webpack/renderer/1446/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/1560/index.js +3 -0
- package/.webpack/renderer/1560/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/1710/index.js +3 -0
- package/.webpack/renderer/1710/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/1740/index.js +3 -0
- package/.webpack/renderer/1740/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/1888/index.js +3 -0
- package/.webpack/renderer/1888/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/1914/index.js +3 -0
- package/.webpack/renderer/1914/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/198/index.js +3 -0
- package/.webpack/renderer/198/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/205/index.js +3 -0
- package/.webpack/renderer/205/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2077/index.js +3 -0
- package/.webpack/renderer/2077/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2094/index.js +3 -0
- package/.webpack/renderer/2094/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2244/index.js +3 -0
- package/.webpack/renderer/2244/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2278/index.js +3 -0
- package/.webpack/renderer/2278/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2398/index.js +3 -0
- package/.webpack/renderer/2398/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2586/index.js +3 -0
- package/.webpack/renderer/2586/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2658/index.js +3 -0
- package/.webpack/renderer/2658/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2686/index.js +3 -0
- package/.webpack/renderer/2686/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2692/index.js +3 -0
- package/.webpack/renderer/2692/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2745/index.js +3 -0
- package/.webpack/renderer/2745/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/2962/index.js +3 -0
- package/.webpack/renderer/2962/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/3042/index.js +3 -0
- package/.webpack/renderer/3042/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/3062/index.js +3 -0
- package/.webpack/renderer/3062/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/3096/index.js +3 -0
- package/.webpack/renderer/3096/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/3182/index.js +3 -0
- package/.webpack/renderer/3182/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/3622/index.js +3 -0
- package/.webpack/renderer/3622/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/3726/index.js +3 -0
- package/.webpack/renderer/3726/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/398/index.js +3 -0
- package/.webpack/renderer/398/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/4114/index.js +3 -0
- package/.webpack/renderer/4114/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/4120/index.js +3 -0
- package/.webpack/renderer/4120/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/4334/index.js +3 -0
- package/.webpack/renderer/4334/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/4630/index.js +3 -0
- package/.webpack/renderer/4630/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/4680/index.js +3 -0
- package/.webpack/renderer/4680/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/4698/index.js +3 -0
- package/.webpack/renderer/4698/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/4839/index.js +3 -0
- package/.webpack/renderer/4839/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/494/index.js +3 -0
- package/.webpack/renderer/494/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/4958/index.js +3 -0
- package/.webpack/renderer/4958/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/4962/index.js +3 -0
- package/.webpack/renderer/4962/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/5130/index.js +3 -0
- package/.webpack/renderer/5130/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/5196/index.js +3 -0
- package/.webpack/renderer/5196/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/5364/index.js +3 -0
- package/.webpack/renderer/5364/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/5550/index.js +3 -0
- package/.webpack/renderer/5550/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/558/index.js +3 -0
- package/.webpack/renderer/558/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/5618/index.js +3 -0
- package/.webpack/renderer/5618/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/5628/index.js +1 -0
- package/.webpack/renderer/5786/index.js +3 -0
- package/.webpack/renderer/5786/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/5966/index.js +3 -0
- package/.webpack/renderer/5966/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/6018/index.js +3 -0
- package/.webpack/renderer/6018/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/6134/index.js +3 -0
- package/.webpack/renderer/6134/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/6185/index.js +3 -0
- package/.webpack/renderer/6185/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/6302/index.js +3 -0
- package/.webpack/renderer/6302/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/6414/index.js +3 -0
- package/.webpack/renderer/6414/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/6446/index.js +3 -0
- package/.webpack/renderer/6446/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/6590/index.js +3 -0
- package/.webpack/renderer/6590/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/6830/index.js +3 -0
- package/.webpack/renderer/6830/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/6940/index.js +3 -0
- package/.webpack/renderer/6940/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/6990/index.js +3 -0
- package/.webpack/renderer/6990/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/7048/index.js +3 -0
- package/.webpack/renderer/7048/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/7200/index.js +3 -0
- package/.webpack/renderer/7200/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/7246/index.js +3 -0
- package/.webpack/renderer/7246/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/7466/index.js +3 -0
- package/.webpack/renderer/7466/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/7836/index.js +3 -0
- package/.webpack/renderer/7836/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/7886/index.js +3 -0
- package/.webpack/renderer/7886/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/8230/index.js +3 -0
- package/.webpack/renderer/8230/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/8332/index.js +3 -0
- package/.webpack/renderer/8332/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/8334/index.js +3 -0
- package/.webpack/renderer/8334/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/8390/index.js +3 -0
- package/.webpack/renderer/8390/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/8494/index.js +3 -0
- package/.webpack/renderer/8494/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/8542/index.js +3 -0
- package/.webpack/renderer/8542/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/8566/index.js +3 -0
- package/.webpack/renderer/8566/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/8902/index.js +3 -0
- package/.webpack/renderer/8902/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/8990/index.js +3 -0
- package/.webpack/renderer/8990/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/9034/index.js +3 -0
- package/.webpack/renderer/9034/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/9038/index.js +3 -0
- package/.webpack/renderer/9038/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/910/index.js +3 -0
- package/.webpack/renderer/910/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/9150/index.js +3 -0
- package/.webpack/renderer/9150/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/9355/index.js +3 -0
- package/.webpack/renderer/9355/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/9390/index.js +3 -0
- package/.webpack/renderer/9390/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/946/index.js +3 -0
- package/.webpack/renderer/946/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/9510/index.js +3 -0
- package/.webpack/renderer/9510/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/968/index.js +3 -0
- package/.webpack/renderer/968/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/970/index.js +3 -0
- package/.webpack/renderer/970/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/9838/index.js +3 -0
- package/.webpack/renderer/9838/index.js.LICENSE.txt +6 -0
- package/.webpack/renderer/f6283f7ccaed1249d9eb.ttf +0 -0
- package/.webpack/renderer/main_window/index.html +1 -0
- package/.webpack/renderer/main_window/index.js +3 -0
- package/.webpack/renderer/main_window/index.js.LICENSE.txt +10 -0
- package/.webpack/renderer/main_window/preload.js +2 -0
- package/.webpack/renderer/monaco-css.worker.js +3 -0
- package/.webpack/renderer/monaco-css.worker.js.LICENSE.txt +6 -0
- package/.webpack/renderer/monaco-editor.worker.js +2 -0
- package/.webpack/renderer/monaco-html.worker.js +2 -0
- package/.webpack/renderer/monaco-json.worker.js +3 -0
- package/.webpack/renderer/monaco-json.worker.js.LICENSE.txt +6 -0
- package/.webpack/renderer/monaco-ts.worker.js +8 -0
- package/.webpack/renderer/monaco-ts.worker.js.LICENSE.txt +6 -0
- package/LICENSE +21 -0
- package/README.md +115 -2
- package/bin/open-axle.js +231 -0
- package/dist/attachment.js +903 -0
- package/dist/browser/browser-factory.js +239 -0
- package/dist/browser/browser-interface.js +11 -0
- package/dist/browser/chrome-launcher.js +334 -0
- package/dist/browser/chrome-provider.js +98 -0
- package/dist/browser/chrome.js +1175 -0
- package/dist/common/common.js +851 -0
- package/dist/common/find.js +2985 -0
- package/dist/common/id.js +95 -0
- package/dist/common/protocol.js +16 -0
- package/dist/core/agent.js +585 -0
- package/dist/core/conduit.js +181 -0
- package/dist/core/config.js +391 -0
- package/dist/core/executor.js +300 -0
- package/dist/core/logger.js +124 -0
- package/dist/core/model.js +570 -0
- package/dist/core/parser.js +444 -0
- package/dist/core/prompt.js +474 -0
- package/dist/core/remote.js +308 -0
- package/dist/core/session.js +966 -0
- package/dist/core/tail.js +467 -0
- package/dist/db/db.js +398 -0
- package/dist/diffView.js +404 -0
- package/dist/fileEditor.js +552 -0
- package/dist/fileIcons.js +388 -0
- package/dist/filesTab.js +2878 -0
- package/dist/hoverTip.js +393 -0
- package/dist/imageViewer.js +531 -0
- package/dist/languages.js +196 -0
- package/dist/logView.js +487 -0
- package/dist/main.js +2879 -0
- package/dist/markdown.js +98 -0
- package/dist/pathBox.js +598 -0
- package/dist/preload.js +341 -0
- package/dist/renderer.js +3183 -0
- package/dist/rightWorkspace.js +524 -0
- package/dist/sessionDetail.js +584 -0
- package/dist/sessionsTab.js +992 -0
- package/dist/skills/SYSTEM.md +36 -0
- package/dist/skills/build-manifest.json +15 -0
- package/dist/skills/cmd-runner/SKILL.md +242 -0
- package/dist/skills/cmd-runner/cmd-runner.js +491 -0
- package/dist/skills/curl/SKILL.md +226 -0
- package/dist/skills/curl/curl.js +454 -0
- package/dist/skills/db-accessor/SKILL.md +163 -0
- package/dist/skills/db-accessor/db-accessor.js +725 -0
- package/dist/skills/file-changer/SKILL.md +255 -0
- package/dist/skills/file-changer/file-changer.js +660 -0
- package/dist/skills/file-creator/SKILL.md +199 -0
- package/dist/skills/file-creator/file-creator.js +393 -0
- package/dist/skills/file-grep/SKILL.md +223 -0
- package/dist/skills/file-grep/file-grep.js +620 -0
- package/dist/skills/file-reader/SKILL.md +199 -0
- package/dist/skills/file-reader/file-reader.js +673 -0
- package/dist/skills/finder/SKILL.md +231 -0
- package/dist/skills/finder/finder.js +519 -0
- package/dist/skills/folder-creator/SKILL.md +157 -0
- package/dist/skills/folder-creator/folder-creator.js +402 -0
- package/dist/skills/fs-list/fs-list.js +516 -0
- package/dist/skills/fs-list/skill.md +222 -0
- package/dist/skills/scp/SKILL.md +237 -0
- package/dist/skills/scp/scp.js +417 -0
- package/dist/skills/ssh/SKILL.md +266 -0
- package/dist/skills/ssh/ssh.js +476 -0
- package/dist/skills/web-accessor/SKILL.md +373 -0
- package/dist/skills/web-accessor/web-accessor.js +33454 -0
- package/dist/surfaceCommon.js +258 -0
- package/dist/turnDetail.js +422 -0
- package/dist/viewSpace.js +1375 -0
- package/dist/vimHighlight.js +673 -0
- package/dist/vimTextPane.js +1779 -0
- package/dist/vimView.js +6209 -0
- package/dist/workingDir.js +425 -0
- package/package.json +126 -4
- package/resources/app-icon.png +0 -0
- package/src/attachment.css +460 -0
- package/src/attachment.ts +981 -0
- package/src/browser/browser-factory.ts +252 -0
- package/src/browser/browser-interface.ts +233 -0
- package/src/browser/chrome-launcher.ts +350 -0
- package/src/browser/chrome-provider.ts +106 -0
- package/src/browser/chrome.ts +1303 -0
- package/src/common/common.ts +889 -0
- package/src/common/find.ts +3633 -0
- package/src/common/id.ts +100 -0
- package/src/common/protocol.ts +23 -0
- package/src/core/agent.ts +630 -0
- package/src/core/conduit.ts +199 -0
- package/src/core/config.ts +393 -0
- package/src/core/executor.ts +289 -0
- package/src/core/logger.ts +94 -0
- package/src/core/model.ts +619 -0
- package/src/core/parser.ts +461 -0
- package/src/core/prompt.ts +474 -0
- package/src/core/remote.ts +294 -0
- package/src/core/session.ts +1107 -0
- package/src/core/tail.ts +451 -0
- package/src/db/db.ts +423 -0
- package/src/diffView.css +234 -0
- package/src/diffView.ts +454 -0
- package/src/fileEditor.ts +704 -0
- package/src/fileIcons.ts +425 -0
- package/src/filesTab.ts +3400 -0
- package/src/global.d.ts +21 -0
- package/src/hoverTip.ts +438 -0
- package/src/imageViewer.ts +630 -0
- package/src/index.html +90 -0
- package/src/languages.ts +196 -0
- package/src/logView.ts +536 -0
- package/src/main.ts +2972 -0
- package/src/markdown.ts +99 -0
- package/src/pathBox.ts +701 -0
- package/src/preload.ts +631 -0
- package/src/renderer.ts +3700 -0
- package/src/rightWorkspace.ts +627 -0
- package/src/sessionDetail.css +360 -0
- package/src/sessionDetail.ts +710 -0
- package/src/sessionsTab.css +346 -0
- package/src/sessionsTab.ts +1110 -0
- package/src/skills/SYSTEM.md +36 -0
- package/src/skills/cmd-runner/SKILL.md +242 -0
- package/src/skills/cmd-runner/cmd-runner.ts +428 -0
- package/src/skills/curl/SKILL.md +226 -0
- package/src/skills/curl/curl.ts +398 -0
- package/src/skills/db-accessor/SKILL.md +163 -0
- package/src/skills/db-accessor/db-accessor.ts +405 -0
- package/src/skills/file-changer/SKILL.md +255 -0
- package/src/skills/file-changer/file-changer.ts +516 -0
- package/src/skills/file-creator/SKILL.md +199 -0
- package/src/skills/file-creator/file-creator.ts +249 -0
- package/src/skills/file-grep/SKILL.md +223 -0
- package/src/skills/file-grep/file-grep.ts +520 -0
- package/src/skills/file-reader/SKILL.md +199 -0
- package/src/skills/file-reader/file-reader.ts +282 -0
- package/src/skills/finder/SKILL.md +231 -0
- package/src/skills/finder/finder.ts +417 -0
- package/src/skills/folder-creator/SKILL.md +157 -0
- package/src/skills/folder-creator/folder-creator.ts +283 -0
- package/src/skills/fs-list/fs-list.ts +450 -0
- package/src/skills/fs-list/skill.md +222 -0
- package/src/skills/scp/SKILL.md +237 -0
- package/src/skills/scp/scp.ts +361 -0
- package/src/skills/ssh/SKILL.md +266 -0
- package/src/skills/ssh/ssh.ts +431 -0
- package/src/skills/web-accessor/SKILL.md +373 -0
- package/src/skills/web-accessor/web-accessor.ts +495 -0
- package/src/styles.css +2580 -0
- package/src/surfaceCommon.ts +382 -0
- package/src/turnDetail.css +323 -0
- package/src/turnDetail.ts +501 -0
- package/src/viewSpace.ts +1580 -0
- package/src/vimHighlight.ts +708 -0
- package/src/vimTextPane.css +457 -0
- package/src/vimTextPane.ts +1896 -0
- package/src/vimView.ts +5697 -0
- package/src/workingDir.css +2001 -0
- package/src/workingDir.ts +465 -0
- package/tsconfig.json +20 -0
- package/tsconfig.skills.json +21 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(()=>{var e={5591(e){e.exports={newInvalidAsn1Error:function(e){var t=new Error;return t.name="InvalidAsn1Error",t.message=e||"",t}}},6322(e,t,r){var n=r(5591),s=r(2319),i=r(2043),o=r(6219);for(var a in e.exports={Reader:i,Writer:o},s)s.hasOwnProperty(a)&&(e.exports[a]=s[a]);for(var c in n)n.hasOwnProperty(c)&&(e.exports[c]=n[c])},2043(e,t,r){var n=r(2613),s=r(6714).Buffer,i=r(2319),o=r(5591).newInvalidAsn1Error;function a(e){if(!e||!s.isBuffer(e))throw new TypeError("data must be a node Buffer");this._buf=e,this._size=e.length,this._len=0,this._offset=0}Object.defineProperty(a.prototype,"length",{enumerable:!0,get:function(){return this._len}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){return this._offset}}),Object.defineProperty(a.prototype,"remain",{get:function(){return this._size-this._offset}}),Object.defineProperty(a.prototype,"buffer",{get:function(){return this._buf.slice(this._offset)}}),a.prototype.readByte=function(e){if(this._size-this._offset<1)return null;var t=255&this._buf[this._offset];return e||(this._offset+=1),t},a.prototype.peek=function(){return this.readByte(!0)},a.prototype.readLength=function(e){if(void 0===e&&(e=this._offset),e>=this._size)return null;var t=255&this._buf[e++];if(null===t)return null;if(128&~t)this._len=t;else{if(0==(t&=127))throw o("Indefinite length not supported");if(t>4)throw o("encoding too long");if(this._size-e<t)return null;this._len=0;for(var r=0;r<t;r++)this._len=(this._len<<8)+(255&this._buf[e++])}return e},a.prototype.readSequence=function(e){var t=this.peek();if(null===t)return null;if(void 0!==e&&e!==t)throw o("Expected 0x"+e.toString(16)+": got 0x"+t.toString(16));var r=this.readLength(this._offset+1);return null===r?null:(this._offset=r,t)},a.prototype.readInt=function(){return this._readTag(i.Integer)},a.prototype.readBoolean=function(){return 0!==this._readTag(i.Boolean)},a.prototype.readEnumeration=function(){return this._readTag(i.Enumeration)},a.prototype.readString=function(e,t){e||(e=i.OctetString);var r=this.peek();if(null===r)return null;if(r!==e)throw o("Expected 0x"+e.toString(16)+": got 0x"+r.toString(16));var n=this.readLength(this._offset+1);if(null===n)return null;if(this.length>this._size-n)return null;if(this._offset=n,0===this.length)return t?s.alloc(0):"";var a=this._buf.slice(this._offset,this._offset+this.length);return this._offset+=this.length,t?a:a.toString("utf8")},a.prototype.readOID=function(e){e||(e=i.OID);var t=this.readString(e,!0);if(null===t)return null;for(var r=[],n=0,s=0;s<t.length;s++){var o=255&t[s];n<<=7,n+=127&o,128&o||(r.push(n),n=0)}return n=r.shift(),r.unshift(n%40),r.unshift(n/40|0),r.join(".")},a.prototype._readTag=function(e){n.ok(void 0!==e);var t=this.peek();if(null===t)return null;if(t!==e)throw o("Expected 0x"+e.toString(16)+": got 0x"+t.toString(16));var r=this.readLength(this._offset+1);if(null===r)return null;if(this.length>4)throw o("Integer too long: "+this.length);if(this.length>this._size-r)return null;this._offset=r;for(var s=this._buf[this._offset],i=0,a=0;a<this.length;a++)i<<=8,i|=255&this._buf[this._offset++];return 128&~s||4===a||(i-=1<<8*a),0|i},e.exports=a},2319(e){e.exports={EOC:0,Boolean:1,Integer:2,BitString:3,OctetString:4,Null:5,OID:6,ObjectDescriptor:7,External:8,Real:9,Enumeration:10,PDV:11,Utf8String:12,RelativeOID:13,Sequence:16,Set:17,NumericString:18,PrintableString:19,T61String:20,VideotexString:21,IA5String:22,UTCTime:23,GeneralizedTime:24,GraphicString:25,VisibleString:26,GeneralString:28,UniversalString:29,CharacterString:30,BMPString:31,Constructor:32,Context:128}},6219(e,t,r){var n=r(2613),s=r(6714).Buffer,i=r(2319),o=r(5591).newInvalidAsn1Error,a={size:1024,growthFactor:8};function c(e){var t,r;t=a,r=e||{},n.ok(t),n.equal(typeof t,"object"),n.ok(r),n.equal(typeof r,"object"),Object.getOwnPropertyNames(t).forEach(function(e){if(!r[e]){var n=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(r,e,n)}}),e=r,this._buf=s.alloc(e.size||1024),this._size=this._buf.length,this._offset=0,this._options=e,this._seq=[]}Object.defineProperty(c.prototype,"buffer",{get:function(){if(this._seq.length)throw o(this._seq.length+" unended sequence(s)");return this._buf.slice(0,this._offset)}}),c.prototype.writeByte=function(e){if("number"!=typeof e)throw new TypeError("argument must be a Number");this._ensure(1),this._buf[this._offset++]=e},c.prototype.writeInt=function(e,t){if("number"!=typeof e)throw new TypeError("argument must be a Number");"number"!=typeof t&&(t=i.Integer);for(var r=4;(!(4286578688&e)||-8388608==(4286578688&e))&&r>1;)r--,e<<=8;if(r>4)throw o("BER ints cannot be > 0xffffffff");for(this._ensure(2+r),this._buf[this._offset++]=t,this._buf[this._offset++]=r;r-- >0;)this._buf[this._offset++]=(4278190080&e)>>>24,e<<=8},c.prototype.writeNull=function(){this.writeByte(i.Null),this.writeByte(0)},c.prototype.writeEnumeration=function(e,t){if("number"!=typeof e)throw new TypeError("argument must be a Number");return"number"!=typeof t&&(t=i.Enumeration),this.writeInt(e,t)},c.prototype.writeBoolean=function(e,t){if("boolean"!=typeof e)throw new TypeError("argument must be a Boolean");"number"!=typeof t&&(t=i.Boolean),this._ensure(3),this._buf[this._offset++]=t,this._buf[this._offset++]=1,this._buf[this._offset++]=e?255:0},c.prototype.writeString=function(e,t){if("string"!=typeof e)throw new TypeError("argument must be a string (was: "+typeof e+")");"number"!=typeof t&&(t=i.OctetString);var r=s.byteLength(e);this.writeByte(t),this.writeLength(r),r&&(this._ensure(r),this._buf.write(e,this._offset),this._offset+=r)},c.prototype.writeBuffer=function(e,t){if("number"!=typeof t)throw new TypeError("tag must be a number");if(!s.isBuffer(e))throw new TypeError("argument must be a buffer");this.writeByte(t),this.writeLength(e.length),this._ensure(e.length),e.copy(this._buf,this._offset,0,e.length),this._offset+=e.length},c.prototype.writeStringArray=function(e){if(!e instanceof Array)throw new TypeError("argument must be an Array[String]");var t=this;e.forEach(function(e){t.writeString(e)})},c.prototype.writeOID=function(e,t){if("string"!=typeof e)throw new TypeError("argument must be a string");if("number"!=typeof t&&(t=i.OID),!/^([0-9]+\.){3,}[0-9]+$/.test(e))throw new Error("argument is not a valid OID string");var r=e.split("."),n=[];n.push(40*parseInt(r[0],10)+parseInt(r[1],10)),r.slice(2).forEach(function(e){!function(e,t){t<128?e.push(t):t<16384?(e.push(t>>>7|128),e.push(127&t)):t<2097152?(e.push(t>>>14|128),e.push(t>>>7&255|128),e.push(127&t)):t<268435456?(e.push(t>>>21|128),e.push(t>>>14&255|128),e.push(t>>>7&255|128),e.push(127&t)):(e.push(t>>>28&255|128),e.push(t>>>21&255|128),e.push(t>>>14&255|128),e.push(t>>>7&255|128),e.push(127&t))}(n,parseInt(e,10))});var s=this;this._ensure(2+n.length),this.writeByte(t),this.writeLength(n.length),n.forEach(function(e){s.writeByte(e)})},c.prototype.writeLength=function(e){if("number"!=typeof e)throw new TypeError("argument must be a Number");if(this._ensure(4),e<=127)this._buf[this._offset++]=e;else if(e<=255)this._buf[this._offset++]=129,this._buf[this._offset++]=e;else if(e<=65535)this._buf[this._offset++]=130,this._buf[this._offset++]=e>>8,this._buf[this._offset++]=e;else{if(!(e<=16777215))throw o("Length too long (> 4 bytes)");this._buf[this._offset++]=131,this._buf[this._offset++]=e>>16,this._buf[this._offset++]=e>>8,this._buf[this._offset++]=e}},c.prototype.startSequence=function(e){"number"!=typeof e&&(e=i.Sequence|i.Constructor),this.writeByte(e),this._seq.push(this._offset),this._ensure(3),this._offset+=3},c.prototype.endSequence=function(){var e=this._seq.pop(),t=e+3,r=this._offset-t;if(r<=127)this._shift(t,r,-2),this._buf[e]=r;else if(r<=255)this._shift(t,r,-1),this._buf[e]=129,this._buf[e+1]=r;else if(r<=65535)this._buf[e]=130,this._buf[e+1]=r>>8,this._buf[e+2]=r;else{if(!(r<=16777215))throw o("Sequence too long");this._shift(t,r,1),this._buf[e]=131,this._buf[e+1]=r>>16,this._buf[e+2]=r>>8,this._buf[e+3]=r}},c.prototype._shift=function(e,t,r){n.ok(void 0!==e),n.ok(void 0!==t),n.ok(r),this._buf.copy(this._buf,e+r,e,e+t),this._offset+=r},c.prototype._ensure=function(e){if(n.ok(e),this._size-this._offset<e){var t=this._size*this._options.growthFactor;t-this._offset<e&&(t+=e);var r=s.alloc(t);this._buf.copy(r,0,0,this._offset),this._buf=r,this._size=t}},e.exports=c},5896(e,t,r){var n=r(6322);e.exports={Ber:n,...void n.Reader,...void n.Writer}},3091(e,t,r){"use strict";var n=r(9463).lowlevel.crypto_hash,s=0,i=function(){this.S=[new Uint32Array([3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946]),new Uint32Array([1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055]),new Uint32Array([3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504]),new Uint32Array([976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462])],this.P=new Uint32Array([608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731])};function o(e,t,r){return(e[0][t[r+3]]+e[1][t[r+2]]^e[2][t[r+1]])+e[3][t[r]]}function a(e,t){var r,n=0;for(r=0;r<4;r++,s++)s>=t&&(s=0),n=n<<8|e[s];return n}function c(e,t,r){var n,s=new i,o=new Uint32Array(8),c=new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,105,116,101]);for(s.expandstate(t,64,e,64),n=0;n<64;n++)s.expand0state(t,64),s.expand0state(e,64);for(n=0;n<8;n++)o[n]=a(c,c.byteLength);for(n=0;n<64;n++)s.enc(o,o.byteLength/8);for(n=0;n<8;n++)r[4*n+3]=o[n]>>>24,r[4*n+2]=o[n]>>>16,r[4*n+1]=o[n]>>>8,r[4*n+0]=o[n]}i.prototype.encipher=function(e,t){void 0===t&&(t=new Uint8Array(e.buffer),0!==e.byteOffset&&(t=t.subarray(e.byteOffset))),e[0]^=this.P[0];for(var r=1;r<16;r+=2)e[1]^=o(this.S,t,0)^this.P[r],e[0]^=o(this.S,t,4)^this.P[r+1];var n=e[0];e[0]=e[1]^this.P[17],e[1]=n},i.prototype.decipher=function(e){var t=new Uint8Array(e.buffer);0!==e.byteOffset&&(t=t.subarray(e.byteOffset)),e[0]^=this.P[17];for(var r=16;r>0;r-=2)e[1]^=o(this.S,t,0)^this.P[r],e[0]^=o(this.S,t,4)^this.P[r-1];var n=e[0];e[0]=e[1]^this.P[0],e[1]=n},i.prototype.expand0state=function(e,t){var r,n,i=new Uint32Array(2),o=new Uint8Array(i.buffer);for(r=0,s=0;r<18;r++)this.P[r]^=a(e,t);for(s=0,r=0;r<18;r+=2)this.encipher(i,o),this.P[r]=i[0],this.P[r+1]=i[1];for(r=0;r<4;r++)for(n=0;n<256;n+=2)this.encipher(i,o),this.S[r][n]=i[0],this.S[r][n+1]=i[1]},i.prototype.expandstate=function(e,t,r,n){var i,o,c=new Uint32Array(2);for(i=0,s=0;i<18;i++)this.P[i]^=a(r,n);for(i=0,s=0;i<18;i+=2)c[0]^=a(e,t),c[1]^=a(e,t),this.encipher(c),this.P[i]=c[0],this.P[i+1]=c[1];for(i=0;i<4;i++)for(o=0;o<256;o+=2)c[0]^=a(e,t),c[1]^=a(e,t),this.encipher(c),this.S[i][o]=c[0],this.S[i][o+1]=c[1];s=0},i.prototype.enc=function(e,t){for(var r=0;r<t;r++)this.encipher(e.subarray(2*r))},i.prototype.dec=function(e,t){for(var r=0;r<t;r++)this.decipher(e.subarray(2*r))},e.exports={SF:function(e,t,r,s,i,o,a){var l,u,h,d,f,p,_=new Uint8Array(64),g=new Uint8Array(64),m=new Uint8Array(32),y=new Uint8Array(32),A=new Uint8Array(s+4),v=o;if(a<1)return-1;if(0===t||0===s||0===o||o>m.byteLength*m.byteLength||s>1<<20)return-1;for(d=Math.floor((o+m.byteLength-1)/m.byteLength),h=Math.floor((o+d-1)/d),l=0;l<s;l++)A[l]=r[l];for(n(_,e,t),p=1;o>0;p++){for(A[s+0]=p>>>24,A[s+1]=p>>>16,A[s+2]=p>>>8,A[s+3]=p,n(g,A,s+4),c(_,g,y),l=m.byteLength;l--;)m[l]=y[l];for(l=1;l<a;l++)for(n(g,y,y.byteLength),c(_,g,y),u=0;u<m.byteLength;u++)m[u]^=y[u];for(h=Math.min(h,o),l=0;l<h&&!((f=l*d+(p-1))>=v);l++)i[f]=m[l];o-=l}return 0}}},9886(e,t,r){e.exports=require(r.ab+"build/Release/cpufeatures.node")},2659(e,t,r){"use strict";const n=r(9886);e.exports=n.getCPUInfo},6714(e,t,r){"use strict";var n,s=r(181),i=s.Buffer,o={};for(n in s)s.hasOwnProperty(n)&&"SlowBuffer"!==n&&"Buffer"!==n&&(o[n]=s[n]);var a=o.Buffer={};for(n in i)i.hasOwnProperty(n)&&"allocUnsafe"!==n&&"allocUnsafeSlow"!==n&&(a[n]=i[n]);if(o.Buffer.prototype=i.prototype,a.from&&a.from!==Uint8Array.from||(a.from=function(e,t,r){if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type '+typeof e);if(e&&void 0===e.length)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);return i(e,t,r)}),a.alloc||(a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*(1<<30))throw new RangeError('The value "'+e+'" is invalid for option "size"');var n=i(e);return t&&0!==t.length?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n}),!o.kStringMaxLength)try{o.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}o.constants||(o.constants={MAX_LENGTH:o.kMaxLength},o.kStringMaxLength&&(o.constants.MAX_STRING_LENGTH=o.kStringMaxLength)),e.exports=o},634(e,t,r){"use strict";const{Duplex:n,Readable:s,Writable:i}=r(2203),{CHANNEL_EXTENDED_DATATYPE:{STDERR:o}}=r(4963),{bufferSlice:a}=r(4787),c=2097152,l=1048576;class u extends s{constructor(e,t){super(t),this._channel=e}_read(e){this._channel._waitChanDrain&&(this._channel._waitChanDrain=!1,this._channel.incoming.window<=l&&p(this._channel))}}class h extends i{constructor(e){super({highWaterMark:c}),this._channel=e}_write(e,t,r){const n=this._channel,s=n._client._protocol,i=n.outgoing,c=i.packetSize,l=i.id;let u=i.window;const h=e.length;let d=0;if("open"===i.state){for(;h-d>0&&u>0;){let t=h-d;t>u&&(t=u),t>c&&(t=c),0===d&&t===h?s.channelExtData(l,e,o):s.channelExtData(l,a(e,d,d+t),o),d+=t,u-=t}if(i.window=u,h-d>0)return 0===u&&(n._waitWindow=!0),n._chunkErr=d>0?a(e,d,h):e,void(n._chunkcbErr=r);r()}}}function d(){this.eof(),!this.server&&this.allowHalfOpen||this.close(),this.writable=!1}function f(){this.readable=!1}function p(e){if("closed"===e.outgoing.state)return;const t=c-e.incoming.window;t<=0||(e.incoming.window+=t,e._client._protocol.channelWindowAdjust(e.outgoing.id,t))}e.exports={Channel:class extends n{constructor(e,t,r){const n={highWaterMark:c,allowHalfOpen:!r||r&&!1!==r.allowHalfOpen,emitClose:!1};super(n),this.allowHalfOpen=n.allowHalfOpen;const s=!(!r||!r.server);this.server=s,this.type=t.type,this.subtype=void 0,this.incoming=t.incoming,this.outgoing=t.outgoing,this._callbacks=[],this._client=e,this._hasX11=!1,this._exit={code:void 0,signal:void 0,dump:void 0,desc:void 0},this.stdin=this.stdout=this,this.stderr=s?new h(this):new u(this,n),this._waitWindow=!1,this._waitChanDrain=!1,this._chunk=void 0,this._chunkcb=void 0,this._chunkErr=void 0,this._chunkcbErr=void 0,this.on("finish",d).on("prefinish",d),this.on("end",f).on("close",f)}_read(e){this._waitChanDrain&&(this._waitChanDrain=!1,this.incoming.window<=l&&p(this))}_write(e,t,r){const n=this._client._protocol,s=this.outgoing,i=s.packetSize,o=s.id;let c=s.window;const l=e.length;let u=0;if("open"===s.state){for(;l-u>0&&c>0;){let t=l-u;t>c&&(t=c),t>i&&(t=i),0===u&&t===l?n.channelData(o,e):n.channelData(o,a(e,u,u+t)),u+=t,c-=t}if(s.window=c,l-u>0)return 0===c&&(this._waitWindow=!0),this._chunk=u>0?a(e,u,l):e,void(this._chunkcb=r);r()}}eof(){"open"===this.outgoing.state&&(this.outgoing.state="eof",this._client._protocol.channelEOF(this.outgoing.id))}close(){"open"!==this.outgoing.state&&"eof"!==this.outgoing.state||(this.outgoing.state="closing",this._client._protocol.channelClose(this.outgoing.id))}destroy(){return this.end(),this.close(),this}setWindow(e,t,r,n){if(this.server)throw new Error("Client-only method called in server mode");"session"!==this.type||"shell"!==this.subtype&&"exec"!==this.subtype||!this.writable||"open"!==this.outgoing.state||this._client._protocol.windowChange(this.outgoing.id,e,t,r,n)}signal(e){if(this.server)throw new Error("Client-only method called in server mode");"session"===this.type&&this.writable&&"open"===this.outgoing.state&&this._client._protocol.signal(this.outgoing.id,e)}exit(e,t,r){if(!this.server)throw new Error("Server-only method called in client mode");"session"===this.type&&this.writable&&"open"===this.outgoing.state&&("number"==typeof e?this._client._protocol.exitStatus(this.outgoing.id,e):this._client._protocol.exitSignal(this.outgoing.id,e,t,r))}},MAX_WINDOW:c,PACKET_SIZE:32768,windowAdjust:p,WINDOW_THRESHOLD:l}},760(e,t,r){"use strict";const{Socket:n}=r(9278),{Duplex:s}=r(2203),{resolve:i}=r(6928),{readFile:o}=r(9896),{execFile:a,spawn:c}=r(5317),{isParsedKey:l,parseKey:u}=r(614),{makeBufferParser:h,readUInt32BE:d,writeUInt32BE:f,writeUInt32LE:p}=r(4787);function _(e){let t=!1;return(...r)=>{t||(t=!0,e(...r))}}function g(){}const m=Buffer.alloc(0),y=h();class A{getIdentities(e){e(new Error("Missing getIdentities() implementation"))}sign(e,t,r,n){"function"==typeof r&&(n=r),n(new Error("Missing sign() implementation"))}}class v extends A{constructor(e){super(),this.socketPath=e}getStream(e){e=_(e);const t=new n;function r(){try{t.destroy()}catch{}e(new Error("Failed to connect to agent"))}t.on("connect",()=>{e(null,t)}),t.on("close",r).on("end",r).on("error",r),t.connect(this.socketPath)}getIdentities(e){e=_(e),this.getStream((t,r)=>{function n(t){if(r)try{r.destroy()}catch{}t||(t=new Error("Failed to retrieve identities from agent")),e(t)}if(t)return n(t);const s=new S(!0);s.on("error",n),s.pipe(r).pipe(s),r.on("close",n).on("end",n).on("error",n),s.getIdentities((t,s)=>{if(t)return n(t);try{r.destroy()}catch{}e(null,s)})})}sign(e,t,r,n){"function"==typeof r?(n=r,r=void 0):"object"==typeof r&&null!==r||(r=void 0),n=_(n),this.getStream((s,i)=>{function o(e){if(i)try{i.destroy()}catch{}e||(e=new Error("Failed to sign data with agent")),n(e)}if(s)return o(s);const a=new S(!0);a.on("error",o),a.pipe(i).pipe(a),i.on("close",o).on("end",o).on("error",o),a.sign(e,t,r,(e,t)=>{if(e)return o(e);try{i.destroy()}catch{}n(null,t)})})}}const b=(()=>{const e=10,t=11,n=12,i=13,o=14,a=15,l=(r.ab,{[e]:new Error("Invalid pagent.exe arguments"),[t]:new Error("Pageant is not running"),[n]:new Error("pagent.exe could not create an mmap"),[i]:new Error("pagent.exe could not set mode for stdin"),[o]:new Error("pagent.exe could not set mode for stdout"),[a]:new Error("pagent.exe did not get expected input payload")});function u(e){e.buffer=null,e.proc&&(e.proc.kill(),e.proc=void 0)}class h extends s{constructor(){super(),this.proc=void 0,this.buffer=null}_read(e){}_write(e,t,n){if(null===this.buffer)this.buffer=e;else{const t=Buffer.allocUnsafe(this.buffer.length+e.length);this.buffer.copy(t,0),e.copy(t,this.buffer.length),this.buffer=t}if(this.buffer.length<4)return n();const s=d(this.buffer,0);if(this.buffer.length-4<s)return n();if(e=this.buffer.slice(0,4+s),this.buffer.length>4+s)return n(new Error("Unexpected multiple agent requests"));let i;this.buffer=null;const o=this.proc=c(r.ab+"pagent.exe",[e.length]);o.stdout.on("data",e=>{this.push(e)}),o.on("error",e=>{i=e,n(i)}),o.on("close",e=>{if(this.proc=void 0,!i){if(i=l[e])return n(i);n()}}),o.stdin.end(e)}_final(e){u(this),e()}_destroy(e,t){u(this),t()}}return class extends v{getStream(e){e(null,new h)}}})(),w=(()=>{const e=/^!<socket >(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/;return class extends v{getStream(t){t=_(t);let r=this.socketPath,s=!1;o(r,function i(c,l){if(c)return s?t(new Error("Invalid cygwin unix socket path")):void a("cygpath",["-w",r],(e,n,a)=>{if(e||0===n.length)return t(new Error("Invalid cygwin unix socket path"));s=!0,r=n.toString().replace(/[\r\n]/g,""),o(r,i)});const u=e.exec(l.toString("ascii"));if(!u)return t(new Error("Malformed cygwin unix socket file"));let h,f=0,_=!1;const g=[];let m,y=Buffer.alloc(12);const A=parseInt(u[1],10),v=u[2].replace(/-/g,""),b=Buffer.allocUnsafe(16);for(let e=0,t=0;t<32;++e,t+=2)b[e]=parseInt(v.substring(t,t+2),16);for(let e=0;e<16;e+=4)p(b,d(b,e),e);function w(){f=0,h="secret",m.write(b)}function E(e){if(f+=e.length,"secret"!==h){if("creds"===h&&(_||g.push(e),12===f)){if(m.removeListener("connect",w),m.removeListener("data",E),m.removeListener("error",I),m.removeListener("end",I),m.removeListener("close",I),_)return t(null,m);_=!0,y=Buffer.concat(g),p(y,process.pid,0),m.on("error",()=>{}),m.destroy(),S()}}else 16===f&&(f=0,h="creds",m.write(y))}function I(){t(new Error("Problem negotiating cygwin unix socket security"))}function S(){m=new n,m.on("connect",w),m.on("data",E),m.on("error",I),m.on("end",I),m.on("close",I),m.connect(A)}S()})}}})(),E=/^[/\\][/\\]\.[/\\]pipe[/\\].+/;function I(e){return"win32"!==process.platform||E.test(e)?new v(e):"pageant"===e?new b:new w(e)}const S=(()=>{const e=Symbol("Inbound Request Type"),t=Symbol("Inbound Request Response"),r=Symbol("Inbound Request Context");class n{constructor(n,s){this[e]=n,this[t]=void 0,this[r]=s}hasResponded(){return void 0!==this[t]}getType(){return this[e]}getContext(){return this[r]}}function i(e,r,n){return r[t]=n,function(e){let r;for(;e[h].length;){const n=e[h][0][t];if(void 0===n)break;e[h].shift(),r=e.push(n)}return r}(e)}function o(e){if(e[_]=null,0===e[p]){const t=e[h];if(t&&t.length){e[h]=[];for(const e of t)e.cb(new Error("No reply from server"))}}try{e.end()}catch{}setImmediate(()=>{e[b]||e.emit("end"),e[v]||e.emit("close")})}function a(){this[v]=!0}function c(){this[b]=!0}const h=Symbol("Requests"),p=Symbol("Agent Protocol Role"),_=Symbol("Agent Protocol Buffer"),A=Symbol("Agent Protocol Current Message Length"),v=Symbol("Agent Protocol Closed"),b=Symbol("Agent Protocol Ended");return class extends s{constructor(e){super({autoDestroy:!0,emitClose:!1}),this[p]=e?0:1,this[h]=[],this[_]=null,this[A]=-1,this.once("end",c),this.once("close",a)}_read(e){}_write(e,t,r){null===this[_]?this[_]=e:this[_]=function(e,t){const r=Buffer.allocUnsafe(e.length+t.length);return e.copy(r,0),t.copy(r,e.length),r}(this[_],e);let s=this[_],i=s.length,o=0;for(;o<i&&!(i<5)&&(-1===this[A]&&(this[A]=d(s,o)),!(i<4+this[A]));){const e=s[o+=4];if(++o,0===this[p]){if(0===this[h].length)return r(new Error("Received unexpected message from server"));const t=this[h].shift();switch(e){case 5:t.cb(new Error("Agent responded with failure"));break;case 12:{if(11!==t.type)return r(new Error("Agent responded with wrong message type"));y.init(s,o);const e=y.readUInt32BE();if(void 0===e)return y.clear(),r(new Error("Malformed agent response"));const n=[];for(let t=0;t<e;++t){let e=y.readString();if(void 0===e)return y.clear(),r(new Error("Malformed agent response"));const t=y.readString(!0);if(void 0===t)return y.clear(),r(new Error("Malformed agent response"));e=u(e),e instanceof Error||(e.comment=e.comment||t,n.push(e))}o=y.pos(),y.clear(),t.cb(null,n);break}case 14:{if(13!==t.type)return r(new Error("Agent responded with wrong message type"));y.init(s,o);let e=y.readString();if(o=y.pos(),y.clear(),void 0===e)return r(new Error("Malformed agent response"));if(y.init(e,0),y.readString(!0),e=y.readString(),y.clear(),void 0===e)return r(new Error("Malformed OpenSSH signature format"));t.cb(null,e);break}default:return r(new Error("Agent responded with unsupported message type"))}}else switch(e){case 11:{const t=new n(e);this[h].push(t),this.emit("identities",t);break}case 13:{y.init(s,o);let t=y.readString();const r=y.readString(),i=y.readUInt32BE();if(o=y.pos(),y.clear(),void 0===i){const t=new n(e);return this[h].push(t),this.failureReply(t)}if(t=u(t),t instanceof Error){const t=new n(e);return this[h].push(t),this.failureReply(t)}const a={hash:void 0};let c;"ssh-rsa"===t.type&&(2&i?(c="rsa-sha2-256",a.hash="sha256"):4&i&&(c="rsa-sha2-512",a.hash="sha512")),void 0===c&&(c=t.type);const l=new n(e,c);this[h].push(l),this.emit("sign",l,t,r,a);break}default:{const t=new n(e);this[h].push(t),this.failureReply(t)}}if(this[A]=-1,o===i){this[_]=null;break}this[_]=s=s.slice(o),i=s.length,o=0}r()}_destroy(e,t){o(this),t()}_final(e){o(this),e()}sign(e,t,r,n){if(0!==this[p])throw new Error("Client-only method called with server role");"function"==typeof r?(n=r,r=void 0):"object"==typeof r&&null!==r||(r=void 0);let s=0;if((e=u(e))instanceof Error)throw new Error("Invalid public key argument");if("ssh-rsa"===e.type&&r)switch(r.hash){case"sha256":s=2;break;case"sha512":s=4}const i=(e=e.getPublicSSH()).length,o=t.length;let a=0;const c=Buffer.allocUnsafe(9+i+4+o+4);return f(c,c.length-4,a),c[a+=4]=13,f(c,i,++a),e.copy(c,a+=4),f(c,o,a+=i),t.copy(c,a+=4),f(c,s,a+=o),"function"!=typeof n&&(n=g),this[h].push({type:13,cb:n}),this.push(c)}getIdentities(e){if(0!==this[p])throw new Error("Client-only method called with server role");let t=0;const r=Buffer.allocUnsafe(5);return f(r,r.length-4,t),r[t+=4]=11,"function"!=typeof e&&(e=g),this[h].push({type:11,cb:e}),this.push(r)}failureReply(e){if(1!==this[p])throw new Error("Server-only method called with client role");if(!(e instanceof n))throw new Error("Wrong request argument");if(e.hasResponded())return!0;let t=0;const r=Buffer.allocUnsafe(5);return f(r,r.length-4,t),r[t+=4]=5,i(this,e,r)}getIdentitiesReply(e,t){if(1!==this[p])throw new Error("Server-only method called with client role");if(!(e instanceof n))throw new Error("Wrong request argument");if(e.hasResponded())return!0;if(11!==e.getType())throw new Error("Invalid response to request");if(!Array.isArray(t))throw new Error("Keys argument must be an array");let r=4;const s=[];for(let e=0;e<t.length;++e){const n=t[e];if("object"!=typeof n||null===n)throw new Error(`Invalid key entry: ${n}`);let i,o;if(l(n))i=n;else if(l(n.pubKey))i=n.pubKey;else{if("object"!=typeof n.pubKey||null===n.pubKey)continue;if(({pubKey:i,comment:o}=n.pubKey),i=u(i),i instanceof Error)continue}o=i.comment||o,i=i.getPublicSSH(),r+=4+i.length,o&&"string"==typeof o?o=Buffer.from(o):Buffer.isBuffer(o)||(o=m),r+=4+o.length,s.push({pubKey:i,comment:o})}let o=0;const a=Buffer.allocUnsafe(5+r);f(a,a.length-4,o),a[o+=4]=12,f(a,s.length,++o),o+=4;for(let e=0;e<s.length;++e){const{pubKey:t,comment:r}=s[e];f(a,t.length,o),t.copy(a,o+=4),f(a,r.length,o+=t.length),o+=4,r.length&&(r.copy(a,o),o+=r.length)}return i(this,e,a)}signReply(e,t){if(1!==this[p])throw new Error("Server-only method called with client role");if(!(e instanceof n))throw new Error("Wrong request argument");if(e.hasResponded())return!0;if(13!==e.getType())throw new Error("Invalid response to request");if(!Buffer.isBuffer(t))throw new Error("Signature argument must be a Buffer");if(0===t.length)throw new Error("Signature argument must be non-empty");let r=0;const s=e.getContext(),o=Buffer.byteLength(s),a=Buffer.allocUnsafe(13+o+4+t.length);return f(a,a.length-4,r),a[r+=4]=14,f(a,4+o+4+t.length,++r),f(a,o,r+=4),a.utf8Write(s,r+=4,o),f(a,t.length,r+=o),t.copy(a,r+=4),i(this,e,a)}}})(),P=Symbol("Agent"),k=Symbol("Agent Keys"),O=Symbol("Agent Keys Index"),C=Symbol("Agent Init Callbacks");function R(e){return e instanceof A}e.exports={AgentContext:class{constructor(e){if("string"==typeof e)e=I(e);else if(!R(e))throw new Error("Invalid agent argument");this[P]=e,this[k]=null,this[O]=-1,this[C]=null}init(e){if("function"!=typeof e&&(e=g),null===this[k])if(null===this[C]){this[C]=[e];const t=(...e)=>{process.nextTick(()=>{const t=this[C];this[C]=null;for(const r of t)r(...e)})};this[P].getIdentities(_((e,r)=>{if(e)return t(e);if(!Array.isArray(r))return t(new Error("Agent implementation failed to provide keys"));const n=[];for(let e of r)e=u(e),e instanceof Error||n.push(e);this[k]=n,this[O]=-1,t()}))}else this[C].push(e);else process.nextTick(e)}nextKey(){return!(null===this[k]||++this[O]>=this[k].length)&&this[k][this[O]]}currentKey(){return null===this[k]||this[O]>=this[k].length?null:this[k][this[O]]}pos(){return null===this[k]||this[O]>=this[k].length?-1:this[O]}reset(){this[O]=-1}sign(...e){this[P].sign(...e)}},AgentProtocol:S,BaseAgent:A,createAgent:I,CygwinAgent:w,isAgent:R,OpenSSHAgent:v,PageantAgent:b}},9374(e,t,r){"use strict";const{createHash:n,getHashes:s,randomFillSync:i}=r(6982),{Socket:o}=r(9278),{lookup:a}=r(2250),c=r(4434),l=s(),{COMPAT:u,CHANNEL_EXTENDED_DATATYPE:{STDERR:h},CHANNEL_OPEN_FAILURE:d,DEFAULT_CIPHER:f,DEFAULT_COMPRESSION:p,DEFAULT_KEX:_,DEFAULT_MAC:g,DEFAULT_SERVER_HOST_KEY:m,DISCONNECT_REASON:y,DISCONNECT_REASON_BY_VALUE:A,SUPPORTED_CIPHER:v,SUPPORTED_COMPRESSION:b,SUPPORTED_KEX:w,SUPPORTED_MAC:E,SUPPORTED_SERVER_HOST_KEY:I}=r(4963),{init:S}=r(2597),P=r(7020),{parseKey:k}=r(614),{SFTP:O}=r(5473),{bufferCopy:C,makeBufferParser:R,makeError:B,readUInt32BE:x,sigSSHToASN1:T,writeUInt32BE:N}=r(4787),{AgentContext:F,createAgent:M,isAgent:L}=r(760),{Channel:U,MAX_WINDOW:D,PACKET_SIZE:$,windowAdjust:j,WINDOW_THRESHOLD:H}=r(634),{ChannelManager:G,generateAlgorithmList:Q,isWritable:q,onChannelOpenFailure:W,onCHANNEL_CLOSE:K}=r(3952),X=R(),z=R(),Y=/^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/,J=e=>{};function V(e,t,r,n){const s=D,i=$;"function"==typeof r&&(n=r,r={});const o=(e,t)=>{n(e,t)};o.type=t;const a=e._chanMgr.add(o);if(-1!==a)switch(t){case"session":case"sftp":e._protocol.session(a,s,i);break;case"direct-tcpip":e._protocol.directTcpip(a,s,i,r);break;case"direct-streamlocal@openssh.com":e._protocol.openssh_directStreamLocal(a,s,i,r);break;default:throw new Error(`Unsupported channel type: ${t}`)}else n(new Error("No free channels available"))}function Z(e,t,r){const n={single:!1,protocol:"MIT-MAGIC-COOKIE-1",cookie:void 0,screen:0};"function"==typeof t?r=t:"object"==typeof t&&null!==t&&("boolean"==typeof t.single&&(n.single=t.single),"number"==typeof t.screen&&(n.screen=t.screen),"string"==typeof t.protocol&&(n.protocol=t.protocol),"string"==typeof t.cookie?n.cookie=t.cookie:Buffer.isBuffer(t.cookie)&&(n.cookie=t.cookie.hexSlice(0,t.cookie.length))),void 0===n.cookie&&(n.cookie=se());const s="function"==typeof r;"open"===e.outgoing.state?(s&&e._callbacks.push(t=>{t?r(!0!==t?t:new Error("Unable to request X11")):(e._hasX11=!0,++e._client._acceptX11,e.once("close",()=>{e._client._acceptX11&&--e._client._acceptX11}),r())}),e._client._protocol.x11Forward(e.outgoing.id,n,s)):s&&r(new Error("Channel is not open"))}function ee(e,t,r){let n=24,s=80,i=640,o=480,a="vt100",c=null;"function"==typeof t?r=t:"object"==typeof t&&null!==t&&("number"==typeof t.rows&&(n=t.rows),"number"==typeof t.cols&&(s=t.cols),"number"==typeof t.width&&(i=t.width),"number"==typeof t.height&&(o=t.height),"string"==typeof t.term&&(a=t.term),"object"==typeof t.modes&&(c=t.modes));const l="function"==typeof r;"open"===e.outgoing.state?(l&&e._callbacks.push(e=>{e?r(!0!==e?e:new Error("Unable to request a pseudo-terminal")):r()}),e._client._protocol.pty(e.outgoing.id,n,s,o,i,a,c,l)):l&&r(new Error("Channel is not open"))}function te(e,t){const r="function"==typeof t;"open"===e.outgoing.state?e._client._agentFwdEnabled?r&&t(!1):(e._client._agentFwdEnabled=!0,e._callbacks.push(n=>{if(n)return e._client._agentFwdEnabled=!1,void(r&&t(!0!==n?n:new Error("Unable to request agent forwarding")));r&&t()}),e._client._protocol.openssh_agentForward(e.outgoing.id,!0)):r&&t(new Error("Channel is not open"))}function re(e,t,r){const n="function"==typeof r;if("open"!==e.outgoing.state)return void(n&&r(new Error("Channel is not open")));n&&e._callbacks.push(e=>{e?r(!0!==e?e:new Error("Unable to set environment")):r()});const s=Object.keys(t||{});for(let r=0;r<s.length;++r){const i=s[r],o=t[i];e._client._protocol.env(e.outgoing.id,i,o,n)}}function ne(e,t,r){"open"===e.outgoing.state?(e._callbacks.push(n=>{n?r(!0!==n?n:new Error(`Unable to start subsystem: ${t}`)):(e.subtype="subsystem",r(void 0,e))}),e._client._protocol.subsystem(e.outgoing.id,t,!0)):r(new Error("Channel is not open"))}const se=(()=>{const e=Buffer.allocUnsafe(16);return()=>(i(e,0,16),e.hexSlice(0,16))})();function ie(e){if(!Array.isArray(e))throw new Error("authList must be an array");let t=0;return(r,n,s)=>t!==e.length&&e[t++]}function oe(e,t,r){if("ssh-rsa"===t.type){if(e._protocol._compatFlags&u.IMPLY_RSA_SHA2_SIGALGS&&(r=Array.isArray(r)?["rsa-sha2-256","rsa-sha2-512",...r]:["rsa-sha2-256","rsa-sha2-512"]),Array.isArray(r)){if(-1!==r.indexOf("rsa-sha2-256"))return[["rsa-sha2-256","sha256"]];if(-1!==r.indexOf("rsa-sha2-512"))return[["rsa-sha2-512","sha512"]];if(-1===r.indexOf("ssh-rsa"))return[]}return[["ssh-rsa","sha1"]]}}e.exports=class extends c{constructor(){super(),this.config={host:void 0,port:void 0,localAddress:void 0,localPort:void 0,forceIPv4:void 0,forceIPv6:void 0,keepaliveCountMax:void 0,keepaliveInterval:void 0,readyTimeout:void 0,ident:void 0,username:void 0,password:void 0,privateKey:void 0,tryKeyboard:void 0,agent:void 0,allowAgentFwd:void 0,authHandler:void 0,hostHashAlgo:void 0,hostHashCb:void 0,strictVendor:void 0,debug:void 0},this._agent=void 0,this._readyTimeout=void 0,this._chanMgr=void 0,this._callbacks=void 0,this._forwarding=void 0,this._forwardingUnix=void 0,this._acceptX11=void 0,this._agentFwdEnabled=void 0,this._remoteVer=void 0,this._protocol=void 0,this._sock=void 0,this._resetKA=void 0}connect(e){if(this._sock&&q(this._sock))return this.once("close",()=>{this.connect(e)}),this.end(),this;this.config.host=e.hostname||e.host||"localhost",this.config.port=e.port||22,this.config.localAddress="string"==typeof e.localAddress?e.localAddress:void 0,this.config.localPort="string"==typeof e.localPort||"number"==typeof e.localPort?e.localPort:void 0,this.config.forceIPv4=e.forceIPv4||!1,this.config.forceIPv6=e.forceIPv6||!1,this.config.keepaliveCountMax="number"==typeof e.keepaliveCountMax&&e.keepaliveCountMax>=0?e.keepaliveCountMax:3,this.config.keepaliveInterval="number"==typeof e.keepaliveInterval&&e.keepaliveInterval>0?e.keepaliveInterval:0,this.config.readyTimeout="number"==typeof e.readyTimeout&&e.readyTimeout>=0?e.readyTimeout:2e4,this.config.ident="string"==typeof e.ident||Buffer.isBuffer(e.ident)?e.ident:void 0;const t={kex:void 0,serverHostKey:void 0,cs:{cipher:void 0,mac:void 0,compress:void 0,lang:[]},sc:void 0};let r=!0;if("object"==typeof e.algorithms&&null!==e.algorithms&&(t.kex=Q(e.algorithms.kex,_,w),t.kex!==_&&(r=!1),t.serverHostKey=Q(e.algorithms.serverHostKey,m,I),t.serverHostKey!==m&&(r=!1),t.cs.cipher=Q(e.algorithms.cipher,f,v),t.cs.cipher!==f&&(r=!1),t.cs.mac=Q(e.algorithms.hmac,g,E),t.cs.mac!==g&&(r=!1),t.cs.compress=Q(e.algorithms.compress,p,b),t.cs.compress!==p&&(r=!1),r||(t.sc=t.cs)),"string"==typeof e.username)this.config.username=e.username;else{if("string"!=typeof e.user)throw new Error("Invalid username");this.config.username=e.user}this.config.password="string"==typeof e.password?e.password:void 0,this.config.privateKey="string"==typeof e.privateKey||Buffer.isBuffer(e.privateKey)?e.privateKey:void 0,this.config.localHostname="string"==typeof e.localHostname?e.localHostname:void 0,this.config.localUsername="string"==typeof e.localUsername?e.localUsername:void 0,this.config.tryKeyboard=!0===e.tryKeyboard,"string"==typeof e.agent&&e.agent.length?this.config.agent=M(e.agent):L(e.agent)?this.config.agent=e.agent:this.config.agent=void 0,this.config.allowAgentFwd=!0===e.agentForward&&void 0!==this.config.agent;let s=this.config.authHandler="function"==typeof e.authHandler||Array.isArray(e.authHandler)?e.authHandler:void 0;this.config.strictVendor="boolean"!=typeof e.strictVendor||e.strictVendor;const i=this.config.debug="function"==typeof e.debug?e.debug:void 0;if(!0===e.agentForward&&!this.config.allowAgentFwd)throw new Error("You must set a valid agent path to allow agent forwarding");let c,u,R=this._callbacks=[];if(this._chanMgr=new G(this),this._forwarding={},this._forwardingUnix={},this._acceptX11=0,this._agentFwdEnabled=!1,this._agent=this.config.agent?this.config.agent:void 0,this._remoteVer=void 0,this.config.privateKey){if(c=k(this.config.privateKey,e.passphrase),c instanceof Error)throw new Error(`Cannot parse privateKey: ${c.message}`);if(Array.isArray(c)&&(c=c[0]),null===c.getPrivatePEM())throw new Error("privateKey value does not contain a (valid) private key")}if("function"==typeof e.hostVerifier){const t=e.hostVerifier;let r;-1!==l.indexOf(e.hostHash)&&(r=e.hostHash),u=(e,s)=>{r&&(e=n(r).update(e).digest("hex"));const i=t(e,s);void 0!==i&&s(i)}}const x=this._sock=e.sock||new o;let V=!1,Z=!1;this._protocol&&this._protocol.cleanup();const ee=i?(e,t,r)=>{i(`Debug output from server: ${JSON.stringify(r)}`)}:void 0;let te;const re=this._protocol=new P({ident:this.config.ident,offer:r?void 0:t,onWrite:e=>{q(x)&&x.write(e)},onError:e=>{"handshake"===e.level&&clearTimeout(this._readyTimeout),re._destruct||x.removeAllListeners("data"),this.emit("error",e);try{x.end()}catch{}},onHeader:e=>{Z=!0,this._remoteVer=e.versions.software,e.greeting&&this.emit("greeting",e.greeting)},onHandshakeComplete:e=>{this.emit("handshake",e),V||(V=!0,re.service("ssh-userauth"))},debug:i,hostVerifier:u,messageHandlers:{DEBUG:ee,DISCONNECT:(e,t,r)=>{if(t!==y.BY_APPLICATION){r||void 0===(r=A[t])&&(r=`Unexpected disconnection reason: ${t}`);const e=new Error(r);e.code=t,this.emit("error",e)}x.end()},SERVICE_ACCEPT:(e,t)=>{"ssh-userauth"===t&&be()},EXT_INFO:(e,t)=>{if(void 0===te){for(const e of t)if("server-sig-algs"===e.name)return void(te=e.algs);te=null}},USERAUTH_BANNER:(e,t)=>{this.emit("banner",t)},USERAUTH_SUCCESS:e=>{ue(),clearTimeout(this._readyTimeout),this.emit("ready")},USERAUTH_FAILURE:(e,t,r)=>{if(fe.keyAlgos){const e=fe.keyAlgos[0][0];if(i&&i(`Client: ${fe.type} (${e}) auth failed`),fe.keyAlgos.shift(),fe.keyAlgos.length){const[e,t]=fe.keyAlgos[0];switch(fe.type){case"agent":return void re.authPK(fe.username,fe.agentCtx.currentKey(),e);case"publickey":return void re.authPK(fe.username,fe.key,e);case"hostbased":return void re.authHostbased(fe.username,fe.key,fe.localHostname,fe.localUsername,e,(e,r)=>{const n=fe.key.sign(e,t);if(n instanceof Error)return n.message=`Error while signing with key: ${n.message}`,n.level="client-authentication",this.emit("error",n),be();r(n)})}}else fe.keyAlgos=void 0}if("agent"===fe.type){const e=fe.agentCtx.pos();return i&&i(`Client: Agent key #${e+1} failed`),we()}i&&i(`Client: ${fe.type} auth failed`),_e=r,ge=t,be()},USERAUTH_PASSWD_CHANGEREQ:(e,t)=>{"password"===fe.type&&this.emit("change password",t,e=>{re.authPassword(this.config.username,this.config.password,e)})},USERAUTH_PK_OK:e=>{let t,r;if(fe.keyAlgos&&([t,r]=fe.keyAlgos[0]),"agent"===fe.type){const e=fe.agentCtx.currentKey();re.authPK(fe.username,e,t,(t,n)=>{const s={hash:r};fe.agentCtx.sign(e,t,s,(e,t)=>{if(!e)return n(t);e.level="agent",this.emit("error",e),we()})})}else"publickey"===fe.type&&re.authPK(fe.username,fe.key,t,(e,t)=>{const n=fe.key.sign(e,r);if(n instanceof Error)return n.message=`Error signing data with key: ${n.message}`,n.level="client-authentication",this.emit("error",n),be();t(n)})},USERAUTH_INFO_REQUEST:(e,t,r,n)=>{if("keyboard-interactive"===fe.type){if(0===(Array.isArray(n)?n.length:0))return i&&i("Client: Sending automatic USERAUTH_INFO_RESPONSE"),void re.authInfoRes();fe.prompt(t,r,"",n,e=>{re.authInfoRes(e)})}},REQUEST_SUCCESS:(e,t)=>{R.length&&R.shift()(!1,t)},REQUEST_FAILURE:e=>{R.length&&R.shift()(!0)},GLOBAL_REQUEST:(e,t,r,n)=>{"hostkeys-00@openssh.com"===t?(!function(e,t,r){if(!e._sock||!q(e._sock))return;if("function"!=typeof r&&(r=J),!Array.isArray(t))throw new TypeError("Invalid keys argument type");const n=[];for(const e of t){const t=k(e);if(t instanceof Error)throw t;n.push(t)}if(!e.config.strictVendor||e.config.strictVendor&&Y.test(e._remoteVer))return e._callbacks.push((t,s)=>{if(t)return void r(!0!==t?t:new Error("Server failed to prove supplied keys"));const i=[];let o=0;for(X.init(s,0);X.avail()&&o!==n.length;){const t=n[o++],r=t.getPublicSSH(),s=X.readString();z.init(s,0);const a=z.readString(!0);let c,l=z.readString();if(a!==t.type){if("ssh-rsa"!==t.type)continue;switch(a){case"rsa-sha2-256":c="sha256";break;case"rsa-sha2-512":c="sha512";break;default:continue}}const u=e._protocol._kex.sessionID,h=Buffer.allocUnsafe(37+u.length+4+r.length);let d=0;N(h,29,d),h.utf8Write("hostkeys-prove-00@openssh.com",d+=4,29),N(h,u.length,d+=29),C(u,h,0,u.length,d+=4),N(h,r.length,d+=u.length),C(r,h,0,r.length,d+=4),(l=T(l,a))&&!0===t.verify(h,l,c)&&i.push(t)}z.clear(),X.clear(),r(null,i)}),void e._protocol.openssh_hostKeysProve(n);process.nextTick(r,new Error("strictVendor enabled and server is not OpenSSH or compatible version"))}(this,n,(e,t)=>{e||this.emit("hostkeys",t)}),r&&re.requestSuccess()):r&&re.requestFailure()},CHANNEL_OPEN:(e,t)=>{!function(e,t){let r,n=-1;const s=()=>{const r={type:t.type,incoming:{id:n,window:D,packetSize:$,state:"open"},outgoing:{id:t.sender,window:t.window,packetSize:t.packetSize,state:"open"}},s=new U(e,r);return e._chanMgr.update(n,s),e._protocol.channelOpenConfirm(t.sender,n,D,$),s},i=()=>{void 0===r&&(r=-1===n?d.RESOURCE_SHORTAGE:d.CONNECT_FAILED),-1!==n&&e._chanMgr.remove(n),e._protocol.channelOpenFail(t.sender,r,"")},o=()=>(n=e._chanMgr.add(),-1===n&&(r=d.RESOURCE_SHORTAGE,e.config.debug&&e.config.debug("Client: Automatic rejection of incoming channel open: no channels available")),-1!==n),a=t.data;switch(t.type){case"forwarded-tcpip":{const t=e._forwarding[`${a.destIP}:${a.destPort}`];if(void 0!==t&&o())return 0===a.destPort&&(a.destPort=t),void e.emit("tcp connection",a,s,i);break}case"forwarded-streamlocal@openssh.com":if(void 0!==e._forwardingUnix[a.socketPath]&&o())return void e.emit("unix connection",a,s,i);break;case"auth-agent@openssh.com":if(e._agentFwdEnabled&&"function"==typeof e._agent.getStream&&o())return void e._agent.getStream((e,t)=>{if(e)return i();const r=s();r.pipe(t).pipe(r)});break;case"x11":if(0!==e._acceptX11&&o())return void e.emit("x11",a,s,i);break;default:r=d.UNKNOWN_CHANNEL_TYPE,e.config.debug&&e.config.debug(`Client: Automatic rejection of unsupported incoming channel open type: ${t.type}`)}void 0===r&&(r=d.ADMINISTRATIVELY_PROHIBITED,e.config.debug&&e.config.debug("Client: Automatic rejection of unexpected incoming channel open for: "+t.type)),i()}(this,t)},CHANNEL_OPEN_CONFIRMATION:(e,t)=>{const r=this._chanMgr.get(t.recipient);if("function"!=typeof r)return;const n="sftp"===r.type,s={type:n?"session":r.type,incoming:{id:t.recipient,window:D,packetSize:$,state:"open"},outgoing:{id:t.sender,window:t.window,packetSize:t.packetSize,state:"open"}},o=n?new O(this,s,{debug:i}):new U(this,s);this._chanMgr.update(t.recipient,o),r(void 0,o)},CHANNEL_OPEN_FAILURE:(e,t,r,n)=>{const s=this._chanMgr.get(t);"function"==typeof s&&W(this,t,{reason:r,description:n},s)},CHANNEL_DATA:(e,t,r)=>{const n=this._chanMgr.get(t);"object"==typeof n&&null!==n&&0!==n.incoming.window&&(n.incoming.window-=r.length,!1!==n.push(r)?n.incoming.window<=H&&j(n):n._waitChanDrain=!0)},CHANNEL_EXTENDED_DATA:(e,t,r,n)=>{if(n!==h)return;const s=this._chanMgr.get(t);"object"==typeof s&&null!==s&&0!==s.incoming.window&&(s.incoming.window-=r.length,s.stderr.push(r)?s.incoming.window<=H&&j(s):s._waitChanDrain=!0)},CHANNEL_WINDOW_ADJUST:(e,t,r)=>{const n=this._chanMgr.get(t);"object"==typeof n&&null!==n&&(n.outgoing.window+=r,n._waitWindow&&(n._waitWindow=!1,n._chunk?n._write(n._chunk,null,n._chunkcb):n._chunkcb?n._chunkcb():n._chunkErr?n.stderr._write(n._chunkErr,null,n._chunkcbErr):n._chunkcbErr&&n._chunkcbErr()))},CHANNEL_SUCCESS:(e,t)=>{const r=this._chanMgr.get(t);"object"==typeof r&&null!==r&&(this._resetKA(),r._callbacks.length&&r._callbacks.shift()(!1))},CHANNEL_FAILURE:(e,t)=>{const r=this._chanMgr.get(t);"object"==typeof r&&null!==r&&(this._resetKA(),r._callbacks.length&&r._callbacks.shift()(!0))},CHANNEL_REQUEST:(e,t,r,n,s)=>{const i=this._chanMgr.get(t);if("object"!=typeof i||null===i)return;const o=i._exit;if(void 0===o.code){switch(r){case"exit-status":return void i.emit("exit",o.code=s);case"exit-signal":return void i.emit("exit",o.code=null,o.signal=`SIG${s.signal}`,o.dump=s.coreDumped,o.desc=s.errorMessage)}n&&e.channelFailure(i.outgoing.id)}},CHANNEL_EOF:(e,t)=>{const r=this._chanMgr.get(t);"object"==typeof r&&null!==r&&"open"===r.incoming.state&&(r.incoming.state="eof",r.readable&&r.push(null),r.stderr.readable&&r.stderr.push(null))},CHANNEL_CLOSE:(e,t)=>{K(this,t,this._chanMgr.get(t))}}});x.pause();const ne=this.config.keepaliveInterval,se=this.config.keepaliveCountMax;let ae,ce=0;const le=()=>{if(++ce>se){if(clearInterval(ae),x.readable){const e=new Error("Keepalive timeout");e.level="client-timeout",this.emit("error",e),x.destroy()}}else q(x)?(R.push(ue),re.ping()):clearInterval(ae)};function ue(){ne>0&&(ce=0,clearInterval(ae),q(x)&&(ae=setInterval(le,ne)))}this._resetKA=ue;const he=(()=>{let e=!1;return()=>{if(!e&&(e=!0,pe&&!Z)){const e=B("Connection lost before handshake","protocol",!0);this.emit("error",e)}}})(),de=(()=>{let e=!1;return()=>{e||(e=!0,pe=!0,i&&i("Socket connected"),this.emit("connect"),S.then(()=>{re.start(),x.on("data",e=>{try{re.parse(e,0,e.length)}catch(e){this.emit("error",e);try{q(x)&&x.end()}catch{}}}),x.stderr&&"function"==typeof x.stderr.resume&&x.stderr.resume(),x.resume()}).catch(e=>{this.emit("error",e);try{q(x)&&x.end()}catch{}}))}})();let fe,pe=!1;x.on("connect",de).on("timeout",()=>{this.emit("timeout")}).on("error",e=>{i&&i(`Socket error: ${e.message}`),clearTimeout(this._readyTimeout),e.level="client-socket",this.emit("error",e)}).on("end",()=>{i&&i("Socket ended"),he(),re.cleanup(),clearTimeout(this._readyTimeout),clearInterval(ae),this.emit("end")}).on("close",()=>{i&&i("Socket closed"),he(),re.cleanup(),clearTimeout(this._readyTimeout),clearInterval(ae),this.emit("close");const e=R;R=this._callbacks=[];const t=new Error("No response from server");for(let r=0;r<e.length;++r)e[r](t);this._chanMgr.cleanup(t)});let _e=null,ge=null;const me=["none"];void 0!==this.config.password&&me.push("password"),void 0!==c&&me.push("publickey"),void 0!==this._agent&&me.push("agent"),this.config.tryKeyboard&&me.push("keyboard-interactive"),void 0!==c&&void 0!==this.config.localHostname&&void 0!==this.config.localUsername&&me.push("hostbased"),Array.isArray(s)?s=ie(s):"function"!=typeof s&&(s=ie(me));let ye=!1;const Ae=e=>{if(!ye){if(ye=!0,!1===e){const e=new Error("All configured authentication methods failed");return e.level="client-authentication",this.emit("error",e),void this.end()}if("string"==typeof e){const t=e;if(-1===me.indexOf(t))return ve(`Authentication method not allowed: ${t}`);const r=this.config.username;switch(t){case"password":e={type:t,username:r,password:this.config.password};break;case"publickey":e={type:t,username:r,key:c};break;case"hostbased":e={type:t,username:r,key:c,localHostname:this.config.localHostname,localUsername:this.config.localUsername};break;case"agent":e={type:t,username:r,agentCtx:new F(this._agent)};break;case"keyboard-interactive":e={type:t,username:r,prompt:(...e)=>this.emit("keyboard-interactive",...e)};break;case"none":e={type:t,username:r};break;default:return ve(`Skipping unsupported authentication method: ${e}`)}}else{if("object"!=typeof e||null===e)return ve(`Skipping invalid authentication attempt: ${e}`);{const t=e.username;if("string"!=typeof t)return ve(`Skipping invalid authentication attempt: ${e}`);const r=e.type;switch(r){case"password":{const{password:n}=e;if("string"!=typeof n&&!Buffer.isBuffer(n))return ve("Skipping invalid password auth attempt");e={type:r,username:t,password:n};break}case"publickey":{const n=k(e.key,e.passphrase);if(n instanceof Error)return ve("Skipping invalid key auth attempt");if(!n.isPrivateKey())return ve("Skipping non-private key");e={type:r,username:t,key:n};break}case"hostbased":{const{localHostname:n,localUsername:s}=e,i=k(e.key,e.passphrase);if(i instanceof Error||"string"!=typeof n||"string"!=typeof s)return ve("Skipping invalid hostbased auth attempt");if(!i.isPrivateKey())return ve("Skipping non-private key");e={type:r,username:t,key:i,localHostname:n,localUsername:s};break}case"agent":{let n=e.agent;if("string"==typeof n&&n.length)n=M(n);else if(!L(n))return ve(`Skipping invalid agent: ${e.agent}`);e={type:r,username:t,agentCtx:new F(n)};break}case"keyboard-interactive":{const{prompt:n}=e;if("function"!=typeof n)return ve("Skipping invalid keyboard-interactive auth attempt");e={type:r,username:t,prompt:n};break}case"none":e={type:r,username:t};break;default:return ve(`Skipping unsupported authentication method: ${e}`)}}}fe=e;try{const e=fe.username;switch(fe.type){case"password":re.authPassword(e,fe.password);break;case"publickey":{let t;if(fe.keyAlgos=oe(this,fe.key,te),fe.keyAlgos){if(!fe.keyAlgos.length)return ve("Skipping key authentication (no mutual hash algorithm)");t=fe.keyAlgos[0][0]}re.authPK(e,fe.key,t);break}case"hostbased":{let t,r;if(fe.keyAlgos=oe(this,fe.key,te),fe.keyAlgos){if(!fe.keyAlgos.length)return ve("Skipping hostbased authentication (no mutual hash algorithm)");[t,r]=fe.keyAlgos[0]}re.authHostbased(e,fe.key,fe.localHostname,fe.localUsername,t,(e,t)=>{const n=fe.key.sign(e,r);if(n instanceof Error)return n.message=`Error while signing with key: ${n.message}`,n.level="client-authentication",this.emit("error",n),be();t(n)});break}case"agent":fe.agentCtx.init(e=>{if(e)return e.level="agent",this.emit("error",e),be();we()});break;case"keyboard-interactive":re.authKeyboard(e);break;case"none":re.authNone(e)}}finally{ye=!1}}};function ve(e){i&&i(e),process.nextTick(be)}function be(){ye=!1;const e=s(ge,_e,Ae);ye||void 0===e||Ae(e)}const we=()=>{if("agent"===fe.type){const e=fe.agentCtx.nextKey();if(!1===e)i&&i("Agent: No more keys left to try"),i&&i("Client: agent auth failed"),be();else{const t=fe.agentCtx.pos();let r;if(fe.keyAlgos=oe(this,e,te),fe.keyAlgos){if(!fe.keyAlgos.length)return i&&i(`Agent: Skipping key #${t+1} (no mutual hash algorithm)`),void we();r=fe.keyAlgos[0][0]}i&&i(`Agent: Trying key #${t+1}`),re.authPK(fe.username,e,r)}}},Ee=()=>{this.config.readyTimeout>0&&(this._readyTimeout=setTimeout(()=>{const e=new Error("Timed out while waiting for handshake");e.level="client-timeout",this.emit("error",e),x.destroy()},this.config.readyTimeout))};if(e.sock)Ee(),"boolean"==typeof x.connecting&&x.connecting||de();else{let t=this.config.host;const r=this.config.forceIPv4,n=this.config.forceIPv6;i&&i(`Client: Trying ${t} on port ${this.config.port} ...`);const s=()=>{Ee(),x.connect({host:t,port:this.config.port,localAddress:this.config.localAddress,localPort:this.config.localPort}),x.setMaxListeners(0),x.setTimeout("number"==typeof e.timeout?e.timeout:0)};!r&&!n||r&&n?s():a(t,r?4:6,(e,n,i)=>{if(e){const n=new Error(`Error while looking up ${r?"IPv4":"IPv6"} address for '${t}': ${e}`);return clearTimeout(this._readyTimeout),n.level="client-dns",this.emit("error",n),void this.emit("close")}t=n,s()})}return this}end(){return this._sock&&q(this._sock)&&(this._protocol.disconnect(y.BY_APPLICATION),this._sock.end()),this}destroy(){return this._sock&&q(this._sock)&&this._sock.destroy(),this}exec(e,t,r){if(!this._sock||!q(this._sock))throw new Error("Not connected");return"function"==typeof t&&(r=t,t={}),V(this,"session",{allowHalfOpen:!1!==t.allowHalfOpen},(n,s)=>{if(n)return void r(n);const i=[];function o(e){if(e)return s.close(),void r(e);i.length&&i.shift()()}(!0===this.config.allowAgentFwd||t&&!0===t.agentForward&&void 0!==this._agent)&&i.push(()=>te(s,o)),"object"==typeof t&&null!==t&&("object"==typeof t.env&&null!==t.env&&re(s,t.env),("object"==typeof t.pty&&null!==t.pty||!0===t.pty)&&i.push(()=>ee(s,t.pty,o)),("object"==typeof t.x11&&null!==t.x11||"number"===t.x11||!0===t.x11)&&i.push(()=>Z(s,t.x11,o))),i.push(()=>function(e,t,r,n){"open"===e.outgoing.state?(e._callbacks.push(t=>{t?n(!0!==t?t:new Error("Unable to exec")):(e.subtype="exec",e.allowHalfOpen=!1!==r.allowHalfOpen,n(void 0,e))}),e._client._protocol.exec(e.outgoing.id,t,!0)):n(new Error("Channel is not open"))}(s,e,t,r)),i.shift()()}),this}shell(e,t,r){if(!this._sock||!q(this._sock))throw new Error("Not connected");return"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),!e||void 0===e.x11&&void 0===e.env||(t=e,e=void 0),V(this,"session",(n,s)=>{if(n)return void r(n);const i=[];function o(e){if(e)return s.close(),void r(e);i.length&&i.shift()()}(!0===this.config.allowAgentFwd||t&&!0===t.agentForward&&void 0!==this._agent)&&i.push(()=>te(s,o)),!1!==e&&i.push(()=>ee(s,e,o)),"object"==typeof t&&null!==t&&("object"==typeof t.env&&null!==t.env&&re(s,t.env),("object"==typeof t.x11&&null!==t.x11||"number"===t.x11||!0===t.x11)&&i.push(()=>Z(s,t.x11,o))),i.push(()=>function(e,t){"open"===e.outgoing.state?(e._callbacks.push(r=>{r?t(!0!==r?r:new Error("Unable to open shell")):(e.subtype="shell",t(void 0,e))}),e._client._protocol.shell(e.outgoing.id,!0)):t(new Error("Channel is not open"))}(s,r)),i.shift()()}),this}subsys(e,t){if(!this._sock||!q(this._sock))throw new Error("Not connected");return V(this,"session",(r,n)=>{r?t(r):ne(n,e,(e,r)=>{e?t(e):t(void 0,r)})}),this}forwardIn(e,t,r){if(!this._sock||!q(this._sock))throw new Error("Not connected");const n="function"==typeof r;return n&&this._callbacks.push((n,s)=>{if(n)return void r(!0!==n?n:new Error(`Unable to bind to ${e}:${t}`));let i=t;0===t&&s&&s.length>=4&&(i=x(s,0),this._protocol._compatFlags&u.DYN_RPORT_BUG||(t=i)),this._forwarding[`${e}:${t}`]=i,r(void 0,i)}),this._protocol.tcpipForward(e,t,n),this}unforwardIn(e,t,r){if(!this._sock||!q(this._sock))throw new Error("Not connected");const n="function"==typeof r;return n&&this._callbacks.push(n=>{n?r(!0!==n?n:new Error(`Unable to unbind from ${e}:${t}`)):(delete this._forwarding[`${e}:${t}`],r())}),this._protocol.cancelTcpipForward(e,t,n),this}forwardOut(e,t,r,n,s){if(!this._sock||!q(this._sock))throw new Error("Not connected");return"function"!=typeof s&&(s=J),V(this,"direct-tcpip",{srcIP:e,srcPort:t,dstIP:r,dstPort:n},s),this}openssh_noMoreSessions(e){if(!this._sock||!q(this._sock))throw new Error("Not connected");const t="function"==typeof e;return!this.config.strictVendor||this.config.strictVendor&&Y.test(this._remoteVer)?(t&&this._callbacks.push(t=>{t?e(!0!==t?t:new Error("Unable to disable future sessions")):e()}),this._protocol.openssh_noMoreSessions(t),this):t?(process.nextTick(e,new Error("strictVendor enabled and server is not OpenSSH or compatible version")),this):this}openssh_forwardInStreamLocal(e,t){if(!this._sock||!q(this._sock))throw new Error("Not connected");const r="function"==typeof t;return!this.config.strictVendor||this.config.strictVendor&&Y.test(this._remoteVer)?(r&&this._callbacks.push(r=>{r?t(!0!==r?r:new Error(`Unable to bind to ${e}`)):(this._forwardingUnix[e]=!0,t())}),this._protocol.openssh_streamLocalForward(e,r),this):r?(process.nextTick(t,new Error("strictVendor enabled and server is not OpenSSH or compatible version")),this):this}openssh_unforwardInStreamLocal(e,t){if(!this._sock||!q(this._sock))throw new Error("Not connected");const r="function"==typeof t;return!this.config.strictVendor||this.config.strictVendor&&Y.test(this._remoteVer)?(r&&this._callbacks.push(r=>{r?t(!0!==r?r:new Error(`Unable to unbind from ${e}`)):(delete this._forwardingUnix[e],t())}),this._protocol.openssh_cancelStreamLocalForward(e,r),this):r?(process.nextTick(t,new Error("strictVendor enabled and server is not OpenSSH or compatible version")),this):this}openssh_forwardOutStreamLocal(e,t){if(!this._sock||!q(this._sock))throw new Error("Not connected");return"function"!=typeof t&&(t=J),!this.config.strictVendor||this.config.strictVendor&&Y.test(this._remoteVer)?(V(this,"direct-streamlocal@openssh.com",{socketPath:e},t),this):(process.nextTick(t,new Error("strictVendor enabled and server is not OpenSSH or compatible version")),this)}sftp(e,t){if(!this._sock||!q(this._sock))throw new Error("Not connected");return"function"==typeof e&&(t=e,e=void 0),V(this,"sftp",(r,n)=>{if(r)return void t(r);const s=(e,r)=>{function s(){n.removeListener("ready",i),n.removeListener("error",o),n.removeListener("exit",a),n.removeListener("close",a)}function i(){s(),t(void 0,n)}function o(e){s(),t(e)}function a(e,r){let n;s(),n="number"==typeof e?`Received exit code ${e} while establishing SFTP session`:void 0!==r?`Received signal ${r} while establishing SFTP session`:"Received unexpected SFTP session termination";const i=new Error(n);i.code=e,i.signal=r,t(i)}e?t(e):(n.on("ready",i).on("error",o).on("exit",a).on("close",a),n._init())};"object"==typeof e&&null!==e?re(n,e,e=>{e?t(e):ne(n,"sftp",s)}):ne(n,"sftp",s)}),this}setNoDelay(e){return this._sock&&"function"==typeof this._sock.setNoDelay&&this._sock.setNoDelay(e),this}}},1200(e,t,r){"use strict";const{Agent:n}=r(8611),{Agent:s}=r(5692),{connect:i}=r(4756);let o;for(const e of[n,s]){class s extends e{constructor(e,t){super(t),this._connectCfg=e,this._defaultSrcIP=t&&t.srcIP||"localhost"}createConnection(t,n){const s=t&&t.localAddress||this._defaultSrcIP,i=t&&t.localPort||0,a=t.host,l=t.port;void 0===o&&(o=r(9374));const u=new o;let h=!1;u.on("ready",()=>{u.forwardOut(s,i,a,l,(r,s)=>{if(h=!0,r)return u.end(),n(r);s.once("close",()=>u.end()),n(null,c(s,e,t))})}).on("error",n).on("close",()=>{h||n(new Error("Unexpected connection close"))}).connect(this._connectCfg)}}t[e===n?"SSHTTPAgent":"SSHTTPSAgent"]=s}function a(){}function c(e,t,r){if(t===n)return e.setKeepAlive=a,e.setNoDelay=a,e.setTimeout=a,e.ref=a,e.unref=a,e.destroySoon=e.destroy,e;r.socket=e;const s=i(r),o=(()=>{let t=!1;return()=>{t||(t=!0,e.isPaused()&&e.resume())}})();return s.on("end",o).on("close",o),s}},3365(e,t,r){"use strict";const{AgentProtocol:n,BaseAgent:s,createAgent:i,CygwinAgent:o,OpenSSHAgent:a,PageantAgent:c}=r(760),{SSHTTPAgent:l,SSHTTPSAgent:u}=r(1200),{parseKey:h}=r(614),{flagsToString:d,OPEN_MODE:f,STATUS_CODE:p,stringToFlags:_}=r(5473);e.exports={Client:r(9374),...void r(2490),...void r(5366)}},5366(e,t,r){"use strict";const{createCipheriv:n,generateKeyPair:s,generateKeyPairSync:i,getCurves:o,randomBytes:a}=r(6982),{Ber:c}=r(5896),l=r(3091).SF,{CIPHER_INFO:u}=r(2597),h=o(),d=new Map(Object.entries(u));function f(e,t){if("string"!=typeof e)throw new TypeError("Key type must be a string");const r={type:"spki",format:"der"},n={type:"pkcs8",format:"der"};switch(e.toLowerCase()){case"rsa":{if("object"!=typeof t||null===t)throw new TypeError("Missing options object for RSA key");const e=t.bits;if(!Number.isInteger(e))throw new TypeError("RSA bits must be an integer");if(e<=0||e>16384)throw new RangeError("RSA bits must be non-zero and <= 16384");return["rsa",{modulusLength:e,publicKeyEncoding:r,privateKeyEncoding:n}]}case"ecdsa":{if("object"!=typeof t||null===t)throw new TypeError("Missing options object for ECDSA key");if(!Number.isInteger(t.bits))throw new TypeError("ECDSA bits must be an integer");let e;switch(t.bits){case 256:e="prime256v1";break;case 384:e="secp384r1";break;case 521:e="secp521r1";break;default:throw new Error("ECDSA bits must be 256, 384, or 521")}if(!h.includes(e))throw new Error("Unsupported ECDSA bits value");return["ec",{namedCurve:e,publicKeyEncoding:r,privateKeyEncoding:n}]}case"ed25519":return["ed25519",{publicKeyEncoding:r,privateKeyEncoding:n}];default:throw new Error(`Unsupported key type: ${e}`)}}function p(e,t,r,s){let i,o="new",u="";if("object"==typeof s&&null!==s&&("string"==typeof s.comment&&s.comment&&(u=s.comment),"string"==typeof s.format&&s.format&&(o=s.format),s.passphrase)){let e;if("string"==typeof s.passphrase)e=Buffer.from(s.passphrase);else{if(!Buffer.isBuffer(s.passphrase))throw new Error("Invalid passphrase");e=s.passphrase}if(void 0===s.cipher)throw new Error("Missing cipher name");const t=d.get(s.cipher);if(void 0===t)throw new Error("Invalid cipher name");if("new"===o){let r=16;if(void 0!==s.rounds){if(!Number.isInteger(s.rounds))throw new TypeError("rounds must be an integer");s.rounds>0&&(r=s.rounds)}const n=Buffer.allocUnsafe(t.keyLen+t.ivLen),o=a(16);if(0!==l(e,e.length,o,o.length,n,n.length,r))return new Error("Failed to generate information to encrypt key");const c=Buffer.allocUnsafe(4+o.length+4);{let e=0;c.writeUInt32BE(o.length,e+=0),c.set(o,e+=4),c.writeUInt32BE(r,e+=o.length)}i={cipher:t,cipherName:s.cipher,kdfName:"bcrypt",kdfOptions:c,key:n.slice(0,t.keyLen),iv:n.slice(t.keyLen)}}}if("new"===o){let s,o="-----BEGIN OPENSSH PRIVATE KEY-----\n";const l=Buffer.from(i?i.cipherName:"none"),h=Buffer.from(i?i.kdfName:"none"),d=i?i.kdfOptions:Buffer.alloc(0),f=i?i.cipher.blockLen:8,p=function(e,t,r){switch(e){case"rsa":{let e=new c.Reader(r);if(e.readSequence(),0!==e.readInt())throw new Error("Unsupported version in RSA private key");if(e.readSequence(),"1.2.840.113549.1.1.1"!==e.readOID())throw new Error("Bad RSA private OID");if(e.readByte()!==c.Null)throw new Error("Malformed RSA private key (expected null)");if(0!==e.readByte())throw new Error("Malformed RSA private key (expected zero-length null)");if(e=new c.Reader(e.readString(c.OctetString,!0)),e.readSequence(),0!==e.readInt())throw new Error("Unsupported version in RSA private key");const t=e.readString(c.Integer,!0),n=e.readString(c.Integer,!0),s=e.readString(c.Integer,!0),i=e.readString(c.Integer,!0),o=e.readString(c.Integer,!0);e.readString(c.Integer,!0),e.readString(c.Integer,!0);const a=e.readString(c.Integer,!0),l=Buffer.from("ssh-rsa"),u=Buffer.allocUnsafe(4+l.length+4+t.length+4+n.length+4+s.length+4+a.length+4+i.length+4+o.length);let h=0;u.writeUInt32BE(l.length,h+=0),u.set(l,h+=4),u.writeUInt32BE(t.length,h+=l.length),u.set(t,h+=4),u.writeUInt32BE(n.length,h+=t.length),u.set(n,h+=4),u.writeUInt32BE(s.length,h+=n.length),u.set(s,h+=4),u.writeUInt32BE(a.length,h+=s.length),u.set(a,h+=4),u.writeUInt32BE(i.length,h+=a.length),u.set(i,h+=4),u.writeUInt32BE(o.length,h+=i.length),u.set(o,h+=4);const d=Buffer.allocUnsafe(4+l.length+4+n.length+4+t.length);return h=0,d.writeUInt32BE(l.length,h+=0),d.set(l,h+=4),d.writeUInt32BE(n.length,h+=l.length),d.set(n,h+=4),d.writeUInt32BE(t.length,h+=n.length),d.set(t,h+=4),{sshName:l.toString(),priv:u,pub:d}}case"ec":{let e=new c.Reader(t);if(e.readSequence(),e.readSequence(),"1.2.840.10045.2.1"!==e.readOID())throw new Error("Bad ECDSA public OID");e.readOID();let n,s=e.readString(c.BitString,!0);{let e=0;for(;e<s.length&&0===s[e];++e);e>0&&(s=s.slice(e))}if(e=new c.Reader(r),e.readSequence(),0!==e.readInt())throw new Error("Unsupported version in ECDSA private key");if(e.readSequence(),"1.2.840.10045.2.1"!==e.readOID())throw new Error("Bad ECDSA private OID");switch(e.readOID()){case"1.2.840.10045.3.1.7":n="nistp256";break;case"1.3.132.0.34":n="nistp384";break;case"1.3.132.0.35":n="nistp521";break;default:throw new Error("Unsupported curve in ECDSA private key")}if(e=new c.Reader(e.readString(c.OctetString,!0)),e.readSequence(),1!==e.readInt())throw new Error("Unsupported version in ECDSA private key");const i=Buffer.concat([Buffer.from([0]),e.readString(c.OctetString,!0)]),o=Buffer.from(`ecdsa-sha2-${n}`);n=Buffer.from(n);const a=Buffer.allocUnsafe(4+o.length+4+n.length+4+s.length+4+i.length);let l=0;a.writeUInt32BE(o.length,l+=0),a.set(o,l+=4),a.writeUInt32BE(n.length,l+=o.length),a.set(n,l+=4),a.writeUInt32BE(s.length,l+=n.length),a.set(s,l+=4),a.writeUInt32BE(i.length,l+=s.length),a.set(i,l+=4);const u=Buffer.allocUnsafe(4+o.length+4+n.length+4+s.length);return l=0,u.writeUInt32BE(o.length,l+=0),u.set(o,l+=4),u.writeUInt32BE(n.length,l+=o.length),u.set(n,l+=4),u.writeUInt32BE(s.length,l+=n.length),u.set(s,l+=4),{sshName:o.toString(),priv:a,pub:u}}case"ed25519":{let e=new c.Reader(t);if(e.readSequence(),e.readSequence(),"1.3.101.112"!==e.readOID())throw new Error("Bad ED25519 public OID");let n=e.readString(c.BitString,!0);{let e=0;for(;e<n.length&&0===n[e];++e);e>0&&(n=n.slice(e))}if(e=new c.Reader(r),e.readSequence(),0!==e.readInt())throw new Error("Unsupported version in ED25519 private key");if(e.readSequence(),"1.3.101.112"!==e.readOID())throw new Error("Bad ED25519 private OID");e=new c.Reader(e.readString(c.OctetString,!0));const s=e.readString(c.OctetString,!0),i=Buffer.from("ssh-ed25519"),o=Buffer.allocUnsafe(4+i.length+4+n.length+4+(s.length+n.length));let a=0;o.writeUInt32BE(i.length,a+=0),o.set(i,a+=4),o.writeUInt32BE(n.length,a+=i.length),o.set(n,a+=4),o.writeUInt32BE(s.length+n.length,a+=n.length),o.set(s,a+=4),o.set(n,a+=s.length);const l=Buffer.allocUnsafe(4+i.length+4+n.length);return a=0,l.writeUInt32BE(i.length,a+=0),l.set(i,a+=4),l.writeUInt32BE(n.length,a+=i.length),l.set(n,a+=4),{sshName:i.toString(),priv:o,pub:l}}}}(e,t,r),_=a(4),g=Buffer.from(u),m=8+p.priv.length+4+g.length;let y=[];for(let e=1;(m+y.length)%f;++e)y.push(255&e);y=Buffer.from(y);let A,v=Buffer.allocUnsafe(m+y.length);{let e=0;v.set(_,e+=0),v.set(_,e+=4),v.set(p.priv,e+=4),v.writeUInt32BE(g.length,e+=p.priv.length),v.set(g,e+=4),v.set(y,e+=g.length)}if(i){const e={authTagLength:i.cipher.authLen},t=n(i.cipher.sslName,i.key,i.iv,e);t.setAutoPadding(!1),v=Buffer.concat([t.update(v),t.final()]),A=i.cipher.authLen>0?t.getAuthTag():Buffer.alloc(0),i.key.fill(0),i.iv.fill(0)}else A=Buffer.alloc(0);const b=Buffer.from("openssh-key-v1\0"),w=Buffer.allocUnsafe(b.length+4+l.length+4+h.length+4+d.length+4+4+p.pub.length+4+v.length+A.length);{let e=0;w.set(b,e+=0),w.writeUInt32BE(l.length,e+=b.length),w.set(l,e+=4),w.writeUInt32BE(h.length,e+=l.length),w.set(h,e+=4),w.writeUInt32BE(d.length,e+=h.length),w.set(d,e+=4),w.writeUInt32BE(1,e+=d.length),w.writeUInt32BE(p.pub.length,e+=4),w.set(p.pub,e+=4),w.writeUInt32BE(v.length,e+=p.pub.length),w.set(v,e+=4),w.set(A,e+=v.length)}{const e=w.base64Slice(0,w.length);let t=e.replace(/.{64}/g,"$&\n");63&e.length&&(t+="\n"),o+=t}{const e=p.pub.base64Slice(0,p.pub.length);s=`${p.sshName} ${e}${u?` ${u}`:""}`}return o+="-----END OPENSSH PRIVATE KEY-----\n",{private:o,public:s}}throw new Error("Invalid output key format")}function _(){}e.exports={generateKeyPair:(e,t,r)=>{"function"==typeof t&&(r=t,t=void 0),"function"!=typeof r&&(r=_);const n=f(e,t);s(...n,(e,s,i)=>{if(e)return r(e);let o;try{o=p(n[0],s,i,t)}catch(e){return r(e)}r(null,o)})},generateKeyPairSync:(e,t)=>{const r=f(e,t),{publicKey:n,privateKey:s}=i(...r);return p(r[0],n,s,t)}}},7020(e,t,r){"use strict";const{inspect:n}=r(9023),{bindingAvailable:s,NullCipher:i,NullDecipher:o}=r(2597),{COMPAT_CHECKS:a,DISCONNECT_REASON:c,eddsaSupported:l,MESSAGE:u,SIGNALS:h,TERMINAL_MODE:d}=r(4963),{DEFAULT_KEXINIT_CLIENT:f,DEFAULT_KEXINIT_SERVER:p,KexInit:_,kexinit:g,onKEXPayload:m}=r(7198),{parseKey:y}=r(614),A=r(2917),{bufferCopy:v,bufferFill:b,bufferSlice:w,convertSignature:E,sendPacket:I,writeUInt32BE:S}=r(4787),{PacketReader:P,PacketWriter:k,ZlibPacketReader:O,ZlibPacketWriter:C}=r(2797),R=r(8342).rE,B=new Map(Object.values(c).map(e=>[e,1])),x=Buffer.from(`SSH-2.0-ssh2js${R}`),T=Buffer.from(`${x}\r\n`),N=Buffer.from([u.GLOBAL_REQUEST,0,0,0,21,107,101,101,112,97,108,105,118,101,64,111,112,101,110,115,115,104,46,99,111,109,1]),F=Buffer.from([d.TTY_OP_END]);function M(){}const L=/^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/;function U(e,t,r){let s,i;this._buffer?(s=Buffer.allocUnsafe(this._buffer.length+(r-t)),s.set(this._buffer,0),0===t?s.set(e,this._buffer.length):s.set(new Uint8Array(e.buffer,e.byteOffset+t,r-t),this._buffer.length),i=this._buffer.length,t=0):(s=e,i=0);const a=t;let c=t,l=t,u=!1,h=0,d=0;for(;t<s.length;++t){const e=s[t];if(13!==e){if(10===e){if(l>c&&l-c>4&&83===s[c]&&83===s[c+1]&&72===s[c+2]&&45===s[c+3]){const e=s.latin1Slice(a,l+1),u=c===a?e:e.slice(c-a),h=L.exec(u);if(!h)throw new Error("Invalid identification string");const d={greeting:c===a?"":e.slice(0,c-a),identRaw:u,versions:{protocol:h[1],software:h[2]},comments:h[3]};return this._remoteIdentRaw=Buffer.from(u),this._debug&&this._debug(`Remote ident: ${n(u)}`),this._compatFlags=j(d),this._buffer=void 0,this._decipher=new o(0,m.bind(this,{firstPacket:!0})),this._parse=D,this._onHeader(d),this._destruct?(g(this),t+1-i):r}if(this._server)throw new Error("Greetings from clients not permitted");if(++d>1024)throw new Error("Max greeting lines exceeded");u=!1,c=t+1,h=0}else{if(u)throw new Error("Invalid header: expected newline");if(++h>=8192)throw new Error("Header line too long")}l=t}else u=!0}return this._buffer||(this._buffer=w(s,a)),t-i}function D(e,t,r){return this._decipher.decrypt(e,t,r)}function $(e){if(this._onPacket(),0===e.length)return void(this._debug&&this._debug("Inbound: Skipping empty packet payload"));const t=(e=this._packetRW.read.read(e))[0];t!==u.USERAUTH_SUCCESS||this._server||this._authenticated||(this._authenticated=!0,"zlib@openssh.com"===this._kex.negotiated.cs.compress&&(this._packetRW.write=new C(this)),"zlib@openssh.com"===this._kex.negotiated.sc.compress&&(this._packetRW.read=new O));const r=A[t];if(void 0!==r)return r(this,e);this._debug&&this._debug(`Inbound: Unsupported message type: ${t}`)}function j(e){const t=e.versions.software;let r=0;for(const e of a)"string"==typeof e[0]?t===e[0]&&(r|=e[1]):e[0].test(t)&&(r|=e[1]);return r}e.exports=class{constructor(e){const t=e.onWrite;if("function"!=typeof t)throw new Error("Missing onWrite function");this._onWrite=e=>{t(e)};const r=e.onError;if("function"!=typeof r)throw new Error("Missing onError function");this._onError=e=>{r(e)};const o=e.debug;this._debug="function"==typeof o?e=>{o(e)}:void 0;const a=e.onHeader;this._onHeader="function"==typeof a?(...e)=>{a(...e)}:M;const c=e.onPacket;this._onPacket="function"==typeof c?()=>{c()}:M;let h,d=e.onHandshakeComplete;"function"!=typeof d&&(d=M),this._onHandshakeComplete=(...e)=>{this._debug&&this._debug("Handshake completed"),h=void 0===h;const t=this._queue;if(t){this._queue=void 0,this._debug&&this._debug(`Draining outbound queue (${t.length}) ...`);for(let e=0;e<t.length;++e){const r=t[e];let n=this._packetRW.write.finalize(r);if(n===r){const e=this._cipher.allocPacket(r.length);e.set(r,5),n=e}I(this,n)}this._debug&&this._debug("... finished draining outbound queue")}h&&this._server&&this._kex.remoteExtInfoEnabled&&function(e){let t="ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss";l&&(t=`ssh-ed25519,${t}`);const r=Buffer.byteLength(t);let n=e._packetRW.write.allocStart;const s=e._packetRW.write.alloc(28+r);s[n]=u.EXT_INFO,S(s,1,++n),S(s,15,n+=4),s.utf8Write("server-sig-algs",n+=4,15),S(s,r,n+=15),s.utf8Write(t,n+=4,r),e._debug&&e._debug("Outbound: Sending EXT_INFO"),I(e,e._packetRW.write.finalize(s))}(this),d(...e)},this._queue=void 0;const g=e.messageHandlers;let m;if(this._handlers="object"==typeof g&&null!==g?g:{},this._onPayload=$.bind(this),this._server=!!e.server,this._banner=void 0,this._server){if("object"!=typeof e.hostKeys||null===e.hostKeys)throw new Error("Missing server host key(s)");this._hostKeys=e.hostKeys,"string"==typeof e.greeting&&e.greeting.length&&(m="\r\n"===e.greeting.slice(-2)?e.greeting:`${e.greeting}\r\n`),"string"==typeof e.banner&&e.banner.length&&(this._banner="\r\n"===e.banner.slice(-2)?e.banner:`${e.banner}\r\n`)}else this._hostKeys=void 0;let y,A=e.offer;if("object"!=typeof A||null===A?A=this._server?p:f:A.constructor!==_&&(this._server?A.kex=A.kex.concat(["kex-strict-s-v00@openssh.com"]):A.kex=A.kex.concat(["ext-info-c","kex-strict-c-v00@openssh.com"]),A=new _(A)),this._kex=void 0,this._strictMode=void 0,this._kexinit=void 0,this._offer=A,this._cipher=new i(0,this._onWrite),this._decipher=void 0,this._skipNextInboundPacket=!1,this._packetRW={read:new P,write:new k(this)},this._hostVerifier=this._server||"function"!=typeof e.hostVerifier?void 0:e.hostVerifier,this._parse=U,this._buffer=void 0,this._authsQueue=[],this._authenticated=!1,this._remoteIdentRaw=void 0,"string"==typeof e.ident)this._identRaw=Buffer.from(`SSH-2.0-${e.ident}`),y=Buffer.allocUnsafe(this._identRaw.length+2),y.set(this._identRaw,0),y[y.length-2]=13,y[y.length-1]=10;else if(Buffer.isBuffer(e.ident)){const t=Buffer.allocUnsafe(8+e.ident.length);t.latin1Write("SSH-2.0-",0,8),t.set(e.ident,8),this._identRaw=t,y=Buffer.allocUnsafe(t.length+2),y.set(t,0),y[y.length-2]=13,y[y.length-1]=10}else this._identRaw=x,y=T;this._compatFlags=0,this._debug&&(s?this._debug("Custom crypto binding available"):this._debug("Custom crypto binding not available")),this._debug&&this._debug(`Local ident: ${n(this._identRaw.toString())}`),this.start=()=>{this.start=void 0,m&&this._onWrite(m),this._onWrite(y)}}_destruct(e){this._packetRW.read.cleanup(),this._packetRW.write.cleanup(),this._cipher&&this._cipher.free(),this._decipher&&this._decipher.free(),"string"==typeof e&&0!==e.length||(e="fatal error"),this.parse=()=>{throw new Error(`Instance unusable after ${e}`)},this._onWrite=()=>{throw new Error(`Instance unusable after ${e}`)},this._destruct=void 0}cleanup(){this._destruct&&this._destruct()}parse(e,t,r){for(;t<r;)t=this._parse(e,t,r)}disconnect(e){let t=this._packetRW.write.allocStartKEX;const r=this._packetRW.write.alloc(13,!0),n=t+13;B.has(e)||(e=c.PROTOCOL_ERROR),r[t]=u.DISCONNECT,S(r,e,++t),r.fill(0,t+=4,n),this._debug&&this._debug(`Outbound: Sending DISCONNECT (${e})`),I(this,this._packetRW.write.finalize(r,!0),!0)}ping(){const e=this._packetRW.write.allocStart,t=this._packetRW.write.alloc(N.length);t.set(N,e),this._debug&&this._debug("Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)"),I(this,this._packetRW.write.finalize(t))}rekey(){void 0===this._kexinit?(this._debug&&this._debug("Outbound: Initiated explicit rekey"),this._queue=[],g(this)):this._debug&&this._debug("Outbound: Ignoring rekey during handshake")}requestSuccess(e){let t,r=this._packetRW.write.allocStart;Buffer.isBuffer(e)?(t=this._packetRW.write.alloc(1+e.length),t[r]=u.REQUEST_SUCCESS,t.set(e,++r)):(t=this._packetRW.write.alloc(1),t[r]=u.REQUEST_SUCCESS),this._debug&&this._debug("Outbound: Sending REQUEST_SUCCESS"),I(this,this._packetRW.write.finalize(t))}requestFailure(){const e=this._packetRW.write.allocStart,t=this._packetRW.write.alloc(1);t[e]=u.REQUEST_FAILURE,this._debug&&this._debug("Outbound: Sending REQUEST_FAILURE"),I(this,this._packetRW.write.finalize(t))}channelSuccess(e){let t=this._packetRW.write.allocStart;const r=this._packetRW.write.alloc(5);r[t]=u.CHANNEL_SUCCESS,S(r,e,++t),this._debug&&this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${e})`),I(this,this._packetRW.write.finalize(r))}channelFailure(e){let t=this._packetRW.write.allocStart;const r=this._packetRW.write.alloc(5);r[t]=u.CHANNEL_FAILURE,S(r,e,++t),this._debug&&this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${e})`),I(this,this._packetRW.write.finalize(r))}channelEOF(e){let t=this._packetRW.write.allocStart;const r=this._packetRW.write.alloc(5);r[t]=u.CHANNEL_EOF,S(r,e,++t),this._debug&&this._debug(`Outbound: Sending CHANNEL_EOF (r:${e})`),I(this,this._packetRW.write.finalize(r))}channelClose(e){let t=this._packetRW.write.allocStart;const r=this._packetRW.write.alloc(5);r[t]=u.CHANNEL_CLOSE,S(r,e,++t),this._debug&&this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${e})`),I(this,this._packetRW.write.finalize(r))}channelWindowAdjust(e,t){let r=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(9);n[r]=u.CHANNEL_WINDOW_ADJUST,S(n,e,++r),S(n,t,r+=4),this._debug&&this._debug(`Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${e}, ${t})`),I(this,this._packetRW.write.finalize(n))}channelData(e,t){const r=Buffer.isBuffer(t),n=r?t.length:Buffer.byteLength(t);let s=this._packetRW.write.allocStart;const i=this._packetRW.write.alloc(9+n);i[s]=u.CHANNEL_DATA,S(i,e,++s),S(i,n,s+=4),r?i.set(t,s+=4):i.utf8Write(t,s+=4,n),this._debug&&this._debug(`Outbound: Sending CHANNEL_DATA (r:${e}, ${n})`),I(this,this._packetRW.write.finalize(i))}channelExtData(e,t,r){const n=Buffer.isBuffer(t),s=n?t.length:Buffer.byteLength(t);let i=this._packetRW.write.allocStart;const o=this._packetRW.write.alloc(13+s);o[i]=u.CHANNEL_EXTENDED_DATA,S(o,e,++i),S(o,r,i+=4),S(o,s,i+=4),n?o.set(t,i+=4):o.utf8Write(t,i+=4,s),this._debug&&this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${e})`),I(this,this._packetRW.write.finalize(o))}channelOpenConfirm(e,t,r,n){let s=this._packetRW.write.allocStart;const i=this._packetRW.write.alloc(17);i[s]=u.CHANNEL_OPEN_CONFIRMATION,S(i,e,++s),S(i,t,s+=4),S(i,r,s+=4),S(i,n,s+=4),this._debug&&this._debug(`Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${e}, l:${t})`),I(this,this._packetRW.write.finalize(i))}channelOpenFail(e,t,r){"string"!=typeof r&&(r="");const n=Buffer.byteLength(r);let s=this._packetRW.write.allocStart;const i=this._packetRW.write.alloc(13+n+4);i[s]=u.CHANNEL_OPEN_FAILURE,S(i,e,++s),S(i,t,s+=4),S(i,n,s+=4),s+=4,n&&(i.utf8Write(r,s,n),s+=n),S(i,0,s),this._debug&&this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${e})`),I(this,this._packetRW.write.finalize(i))}service(e){if(this._server)throw new Error("Client-only method called in server mode");const t=Buffer.byteLength(e);let r=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(5+t);n[r]=u.SERVICE_REQUEST,S(n,t,++r),n.utf8Write(e,r+=4,t),this._debug&&this._debug(`Outbound: Sending SERVICE_REQUEST (${e})`),I(this,this._packetRW.write.finalize(n))}authPassword(e,t,r){if(this._server)throw new Error("Client-only method called in server mode");const n=Buffer.byteLength(e),s=Buffer.byteLength(t),i=r?Buffer.byteLength(r):0;let o=this._packetRW.write.allocStart;const a=this._packetRW.write.alloc(5+n+4+14+4+8+1+4+s+(r?4+i:0));a[o]=u.USERAUTH_REQUEST,S(a,n,++o),a.utf8Write(e,o+=4,n),S(a,14,o+=n),a.utf8Write("ssh-connection",o+=4,14),S(a,8,o+=14),a.utf8Write("password",o+=4,8),a[o+=8]=r?1:0,S(a,s,++o),Buffer.isBuffer(t)?v(t,a,0,s,o+=4):a.utf8Write(t,o+=4,s),r?(S(a,i,o+=s),Buffer.isBuffer(r)?v(r,a,0,i,o+=4):a.utf8Write(r,o+=4,i),this._debug&&this._debug("Outbound: Sending USERAUTH_REQUEST (changed password)")):this._debug&&this._debug("Outbound: Sending USERAUTH_REQUEST (password)"),this._authsQueue.push("password"),I(this,this._packetRW.write.finalize(a))}authPK(e,t,r,n){if(this._server)throw new Error("Client-only method called in server mode");if((t=y(t))instanceof Error)throw new Error("Invalid key");const s=t.type;t=t.getPublicSSH(),"function"==typeof r&&(n=r,r=void 0),r||(r=s);const i=Buffer.byteLength(e),o=Buffer.byteLength(r),a=t.length,c=this._kex.sessionID,l=c.length,h=(n?4+l:0)+1+4+i+4+14+4+9+1+4+o+4+a;let d,f;if(n?(d=Buffer.allocUnsafe(h),f=0,S(d,l,f),d.set(c,f+=4),f+=l):(d=this._packetRW.write.alloc(h),f=this._packetRW.write.allocStart),d[f]=u.USERAUTH_REQUEST,S(d,i,++f),d.utf8Write(e,f+=4,i),S(d,14,f+=i),d.utf8Write("ssh-connection",f+=4,14),S(d,9,f+=14),d.utf8Write("publickey",f+=4,9),d[f+=9]=n?1:0,S(d,o,++f),d.utf8Write(r,f+=4,o),S(d,a,f+=o),d.set(t,f+=4),!n)return this._authsQueue.push("publickey"),this._debug&&this._debug("Outbound: Sending USERAUTH_REQUEST (publickey -- check)"),void I(this,this._packetRW.write.finalize(d));n(d,n=>{if(!1===(n=E(n,s)))throw new Error("Error while converting handshake signature");const c=n.length;f=this._packetRW.write.allocStart,d=this._packetRW.write.alloc(5+i+4+14+4+9+1+4+o+4+a+4+4+o+4+c),d[f]=u.USERAUTH_REQUEST,S(d,i,++f),d.utf8Write(e,f+=4,i),S(d,14,f+=i),d.utf8Write("ssh-connection",f+=4,14),S(d,9,f+=14),d.utf8Write("publickey",f+=4,9),d[f+=9]=1,S(d,o,++f),d.utf8Write(r,f+=4,o),S(d,a,f+=o),d.set(t,f+=4),S(d,4+o+4+c,f+=a),S(d,o,f+=4),d.utf8Write(r,f+=4,o),S(d,c,f+=o),d.set(n,f+=4),this._authsQueue.push("publickey"),this._debug&&this._debug("Outbound: Sending USERAUTH_REQUEST (publickey)"),I(this,this._packetRW.write.finalize(d))})}authHostbased(e,t,r,n,s,i){if(this._server)throw new Error("Client-only method called in server mode");if((t=y(t))instanceof Error)throw new Error("Invalid key");const o=t.type;t=t.getPublicSSH(),"function"==typeof s&&(i=s,s=void 0),s||(s=o);const a=Buffer.byteLength(e),c=Buffer.byteLength(s),l=t.length,h=this._kex.sessionID,d=h.length,f=Buffer.byteLength(r),p=Buffer.byteLength(n),_=Buffer.allocUnsafe(4+d+1+4+a+4+14+4+9+4+c+4+l+4+f+4+p);let g=0;S(_,d,g),_.set(h,g+=4),_[g+=d]=u.USERAUTH_REQUEST,S(_,a,++g),_.utf8Write(e,g+=4,a),S(_,14,g+=a),_.utf8Write("ssh-connection",g+=4,14),S(_,9,g+=14),_.utf8Write("hostbased",g+=4,9),S(_,c,g+=9),_.utf8Write(s,g+=4,c),S(_,l,g+=c),_.set(t,g+=4),S(_,f,g+=l),_.utf8Write(r,g+=4,f),S(_,p,g+=f),_.utf8Write(n,g+=4,p),i(_,e=>{if(!(e=E(e,o)))throw new Error("Error while converting handshake signature");const t=e.length,r=_.length-d-4;g=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(r+4+4+c+4+t);v(_,n,4+d,_.length,g),S(n,4+c+4+t,g+=r),S(n,c,g+=4),n.utf8Write(s,g+=4,c),S(n,t,g+=c),n.set(e,g+=4),this._authsQueue.push("hostbased"),this._debug&&this._debug("Outbound: Sending USERAUTH_REQUEST (hostbased)"),I(this,this._packetRW.write.finalize(n))})}authKeyboard(e){if(this._server)throw new Error("Client-only method called in server mode");const t=Buffer.byteLength(e);let r=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(5+t+4+14+4+20+4+4);n[r]=u.USERAUTH_REQUEST,S(n,t,++r),n.utf8Write(e,r+=4,t),S(n,14,r+=t),n.utf8Write("ssh-connection",r+=4,14),S(n,20,r+=14),n.utf8Write("keyboard-interactive",r+=4,20),S(n,0,r+=20),S(n,0,r+=4),this._authsQueue.push("keyboard-interactive"),this._debug&&this._debug("Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)"),I(this,this._packetRW.write.finalize(n))}authNone(e){if(this._server)throw new Error("Client-only method called in server mode");const t=Buffer.byteLength(e);let r=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(5+t+4+14+4+4);n[r]=u.USERAUTH_REQUEST,S(n,t,++r),n.utf8Write(e,r+=4,t),S(n,14,r+=t),n.utf8Write("ssh-connection",r+=4,14),S(n,4,r+=14),n.utf8Write("none",r+=4,4),this._authsQueue.push("none"),this._debug&&this._debug("Outbound: Sending USERAUTH_REQUEST (none)"),I(this,this._packetRW.write.finalize(n))}authInfoRes(e){if(this._server)throw new Error("Client-only method called in server mode");let t,r=0;if(e){t=new Array(e.length);for(let n=0;n<e.length;++n){const s=Buffer.byteLength(e[n]);t[n]=s,r+=4+s}}let n=this._packetRW.write.allocStart;const s=this._packetRW.write.alloc(5+r);if(s[n]=u.USERAUTH_INFO_RESPONSE,e){S(s,e.length,++n),n+=4;for(let r=0;r<e.length;++r){const i=t[r];S(s,i,n),n+=4,i&&(s.utf8Write(e[r],n,i),n+=i)}}else S(s,0,++n);this._debug&&this._debug("Outbound: Sending USERAUTH_INFO_RESPONSE"),I(this,this._packetRW.write.finalize(s))}tcpipForward(e,t,r){if(this._server)throw new Error("Client-only method called in server mode");const n=Buffer.byteLength(e);let s=this._packetRW.write.allocStart;const i=this._packetRW.write.alloc(23+n+4);i[s]=u.GLOBAL_REQUEST,S(i,13,++s),i.utf8Write("tcpip-forward",s+=4,13),i[s+=13]=void 0===r||!0===r?1:0,S(i,n,++s),i.utf8Write(e,s+=4,n),S(i,t,s+=n),this._debug&&this._debug("Outbound: Sending GLOBAL_REQUEST (tcpip-forward)"),I(this,this._packetRW.write.finalize(i))}cancelTcpipForward(e,t,r){if(this._server)throw new Error("Client-only method called in server mode");const n=Buffer.byteLength(e);let s=this._packetRW.write.allocStart;const i=this._packetRW.write.alloc(30+n+4);i[s]=u.GLOBAL_REQUEST,S(i,20,++s),i.utf8Write("cancel-tcpip-forward",s+=4,20),i[s+=20]=void 0===r||!0===r?1:0,S(i,n,++s),i.utf8Write(e,s+=4,n),S(i,t,s+=n),this._debug&&this._debug("Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)"),I(this,this._packetRW.write.finalize(i))}openssh_streamLocalForward(e,t){if(this._server)throw new Error("Client-only method called in server mode");const r=Buffer.byteLength(e);let n=this._packetRW.write.allocStart;const s=this._packetRW.write.alloc(41+r);s[n]=u.GLOBAL_REQUEST,S(s,31,++n),s.utf8Write("streamlocal-forward@openssh.com",n+=4,31),s[n+=31]=void 0===t||!0===t?1:0,S(s,r,++n),s.utf8Write(e,n+=4,r),this._debug&&this._debug("Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)"),I(this,this._packetRW.write.finalize(s))}openssh_cancelStreamLocalForward(e,t){if(this._server)throw new Error("Client-only method called in server mode");const r=Buffer.byteLength(e);let n=this._packetRW.write.allocStart;const s=this._packetRW.write.alloc(48+r);s[n]=u.GLOBAL_REQUEST,S(s,38,++n),s.utf8Write("cancel-streamlocal-forward@openssh.com",n+=4,38),s[n+=38]=void 0===t||!0===t?1:0,S(s,r,++n),s.utf8Write(e,n+=4,r),this._debug&&this._debug("Outbound: Sending GLOBAL_REQUEST (cancel-streamlocal-forward@openssh.com)"),I(this,this._packetRW.write.finalize(s))}directTcpip(e,t,r,n){if(this._server)throw new Error("Client-only method called in server mode");const s=Buffer.byteLength(n.srcIP),i=Buffer.byteLength(n.dstIP);let o=this._packetRW.write.allocStart;const a=this._packetRW.write.alloc(33+s+4+4+i+4);a[o]=u.CHANNEL_OPEN,S(a,12,++o),a.utf8Write("direct-tcpip",o+=4,12),S(a,e,o+=12),S(a,t,o+=4),S(a,r,o+=4),S(a,i,o+=4),a.utf8Write(n.dstIP,o+=4,i),S(a,n.dstPort,o+=i),S(a,s,o+=4),a.utf8Write(n.srcIP,o+=4,s),S(a,n.srcPort,o+=s),this._debug&&this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, direct-tcpip)`),I(this,this._packetRW.write.finalize(a))}openssh_directStreamLocal(e,t,r,n){if(this._server)throw new Error("Client-only method called in server mode");const s=Buffer.byteLength(n.socketPath);let i=this._packetRW.write.allocStart;const o=this._packetRW.write.alloc(51+s+4+4);o[i]=u.CHANNEL_OPEN,S(o,30,++i),o.utf8Write("direct-streamlocal@openssh.com",i+=4,30),S(o,e,i+=30),S(o,t,i+=4),S(o,r,i+=4),S(o,s,i+=4),o.utf8Write(n.socketPath,i+=4,s),b(o,0,i+=s,i+8),this._debug&&this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, direct-streamlocal@openssh.com)`),I(this,this._packetRW.write.finalize(o))}openssh_noMoreSessions(e){if(this._server)throw new Error("Client-only method called in server mode");let t=this._packetRW.write.allocStart;const r=this._packetRW.write.alloc(34);r[t]=u.GLOBAL_REQUEST,S(r,28,++t),r.utf8Write("no-more-sessions@openssh.com",t+=4,28),r[t+=28]=void 0===e||!0===e?1:0,this._debug&&this._debug("Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)"),I(this,this._packetRW.write.finalize(r))}session(e,t,r){if(this._server)throw new Error("Client-only method called in server mode");let n=this._packetRW.write.allocStart;const s=this._packetRW.write.alloc(24);s[n]=u.CHANNEL_OPEN,S(s,7,++n),s.utf8Write("session",n+=4,7),S(s,e,n+=7),S(s,t,n+=4),S(s,r,n+=4),this._debug&&this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, session)`),I(this,this._packetRW.write.finalize(s))}windowChange(e,t,r,n,s){if(this._server)throw new Error("Client-only method called in server mode");let i=this._packetRW.write.allocStart;const o=this._packetRW.write.alloc(39);o[i]=u.CHANNEL_REQUEST,S(o,e,++i),S(o,13,i+=4),o.utf8Write("window-change",i+=4,13),o[i+=13]=0,S(o,r,++i),S(o,t,i+=4),S(o,s,i+=4),S(o,n,i+=4),this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, window-change)`),I(this,this._packetRW.write.finalize(o))}pty(e,t,r,n,s,i,o,a){if(this._server)throw new Error("Client-only method called in server mode");i&&i.length||(i="vt100"),!o||Buffer.isBuffer(o)||Array.isArray(o)||"object"!=typeof o||null===o||(o=function(e){const t=Object.keys(e),r=Buffer.allocUnsafe(5*t.length+1);let n=0;for(let s=0;s<t.length;++s){const i=t[s];if("TTY_OP_END"===i)continue;const o=d[i];if(void 0===o)continue;const a=e[i];"number"==typeof a&&isFinite(a)&&(r[n++]=o,r[n++]=a>>>24,r[n++]=a>>>16,r[n++]=a>>>8,r[n++]=a)}return r[n++]=d.TTY_OP_END,n<r.length?w(r,0,n):r}(o)),o&&o.length||(o=F);const c=i.length,l=o.length;let h=this._packetRW.write.allocStart;const f=this._packetRW.write.alloc(21+c+4+4+4+4+4+l);if(f[h]=u.CHANNEL_REQUEST,S(f,e,++h),S(f,7,h+=4),f.utf8Write("pty-req",h+=4,7),f[h+=7]=void 0===a||!0===a?1:0,S(f,c,++h),f.utf8Write(i,h+=4,c),S(f,r,h+=c),S(f,t,h+=4),S(f,s,h+=4),S(f,n,h+=4),S(f,l,h+=4),h+=4,Array.isArray(o))for(let e=0;e<l;++e)f[h++]=o[e];else Buffer.isBuffer(o)&&f.set(o,h);this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, pty-req)`),I(this,this._packetRW.write.finalize(f))}shell(e,t){if(this._server)throw new Error("Client-only method called in server mode");let r=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(15);n[r]=u.CHANNEL_REQUEST,S(n,e,++r),S(n,5,r+=4),n.utf8Write("shell",r+=4,5),n[r+=5]=void 0===t||!0===t?1:0,this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, shell)`),I(this,this._packetRW.write.finalize(n))}exec(e,t,r){if(this._server)throw new Error("Client-only method called in server mode");const n=Buffer.isBuffer(t),s=n?t.length:Buffer.byteLength(t);let i=this._packetRW.write.allocStart;const o=this._packetRW.write.alloc(18+s);o[i]=u.CHANNEL_REQUEST,S(o,e,++i),S(o,4,i+=4),o.utf8Write("exec",i+=4,4),o[i+=4]=void 0===r||!0===r?1:0,S(o,s,++i),n?o.set(t,i+=4):o.utf8Write(t,i+=4,s),this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, exec: ${t})`),I(this,this._packetRW.write.finalize(o))}signal(e,t){if(this._server)throw new Error("Client-only method called in server mode");const r=t;if("SIG"===(t=t.toUpperCase()).slice(0,3)&&(t=t.slice(3)),1!==h[t])throw new Error(`Invalid signal: ${r}`);const n=t.length;let s=this._packetRW.write.allocStart;const i=this._packetRW.write.alloc(20+n);i[s]=u.CHANNEL_REQUEST,S(i,e,++s),S(i,6,s+=4),i.utf8Write("signal",s+=4,6),i[s+=6]=0,S(i,n,++s),i.utf8Write(t,s+=4,n),this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, signal: ${t})`),I(this,this._packetRW.write.finalize(i))}env(e,t,r,n){if(this._server)throw new Error("Client-only method called in server mode");const s=Buffer.byteLength(t),i=Buffer.isBuffer(r),o=i?r.length:Buffer.byteLength(r);let a=this._packetRW.write.allocStart;const c=this._packetRW.write.alloc(17+s+4+o);c[a]=u.CHANNEL_REQUEST,S(c,e,++a),S(c,3,a+=4),c.utf8Write("env",a+=4,3),c[a+=3]=void 0===n||!0===n?1:0,S(c,s,++a),c.utf8Write(t,a+=4,s),S(c,o,a+=s),i?c.set(r,a+=4):c.utf8Write(r,a+=4,o),this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, env: ${t}=${r})`),I(this,this._packetRW.write.finalize(c))}x11Forward(e,t,r){if(this._server)throw new Error("Client-only method called in server mode");const n=t.protocol,s=t.cookie,i=Buffer.isBuffer(n),o=i?n.length:Buffer.byteLength(n),a=Buffer.isBuffer(s),c=a?s.length:Buffer.byteLength(s);let l=this._packetRW.write.allocStart;const h=this._packetRW.write.alloc(22+o+4+c+4);h[l]=u.CHANNEL_REQUEST,S(h,e,++l),S(h,7,l+=4),h.utf8Write("x11-req",l+=4,7),h[l+=7]=void 0===r||!0===r?1:0,h[++l]=t.single?1:0,S(h,o,++l),i?h.set(n,l+=4):h.utf8Write(n,l+=4,o),S(h,c,l+=o),a?h.set(s,l+=4):h.latin1Write(s,l+=4,c),S(h,t.screen||0,l+=c),this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, x11-req)`),I(this,this._packetRW.write.finalize(h))}subsystem(e,t,r){if(this._server)throw new Error("Client-only method called in server mode");const n=Buffer.byteLength(t);let s=this._packetRW.write.allocStart;const i=this._packetRW.write.alloc(23+n);i[s]=u.CHANNEL_REQUEST,S(i,e,++s),S(i,9,s+=4),i.utf8Write("subsystem",s+=4,9),i[s+=9]=void 0===r||!0===r?1:0,S(i,n,++s),i.utf8Write(t,s+=4,n),this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, subsystem: ${t})`),I(this,this._packetRW.write.finalize(i))}openssh_agentForward(e,t){if(this._server)throw new Error("Client-only method called in server mode");let r=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(36);n[r]=u.CHANNEL_REQUEST,S(n,e,++r),S(n,26,r+=4),n.utf8Write("auth-agent-req@openssh.com",r+=4,26),n[r+=26]=void 0===t||!0===t?1:0,this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, auth-agent-req@openssh.com)`),I(this,this._packetRW.write.finalize(n))}openssh_hostKeysProve(e){if(this._server)throw new Error("Client-only method called in server mode");let t=0;const r=[];for(const n of e){const e=n.getPublicSSH();t+=4+e.length,r.push(e)}let n=this._packetRW.write.allocStart;const s=this._packetRW.write.alloc(35+t);s[n]=u.GLOBAL_REQUEST,S(s,29,++n),s.utf8Write("hostkeys-prove-00@openssh.com",n+=4,29),s[n+=29]=1,++n;for(const e of r)S(s,e.length,n),v(e,s,0,e.length,n+=4),n+=e.length;this._debug&&this._debug("Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)"),I(this,this._packetRW.write.finalize(s))}serviceAccept(e){if(!this._server)throw new Error("Server-only method called in client mode");const t=Buffer.byteLength(e);let r=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(5+t);if(n[r]=u.SERVICE_ACCEPT,S(n,t,++r),n.utf8Write(e,r+=4,t),this._debug&&this._debug(`Outbound: Sending SERVICE_ACCEPT (${e})`),I(this,this._packetRW.write.finalize(n)),this._server&&this._banner&&"ssh-userauth"===e){const e=this._banner;this._banner=void 0;const t=Buffer.byteLength(e);r=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(5+t+4);n[r]=u.USERAUTH_BANNER,S(n,t,++r),n.utf8Write(e,r+=4,t),S(n,0,r+=t),this._debug&&this._debug("Outbound: Sending USERAUTH_BANNER"),I(this,this._packetRW.write.finalize(n))}}forwardedTcpip(e,t,r,n){if(!this._server)throw new Error("Server-only method called in client mode");const s=Buffer.byteLength(n.boundAddr),i=Buffer.byteLength(n.remoteAddr);let o=this._packetRW.write.allocStart;const a=this._packetRW.write.alloc(36+s+4+4+i+4);a[o]=u.CHANNEL_OPEN,S(a,15,++o),a.utf8Write("forwarded-tcpip",o+=4,15),S(a,e,o+=15),S(a,t,o+=4),S(a,r,o+=4),S(a,s,o+=4),a.utf8Write(n.boundAddr,o+=4,s),S(a,n.boundPort,o+=s),S(a,i,o+=4),a.utf8Write(n.remoteAddr,o+=4,i),S(a,n.remotePort,o+=i),this._debug&&this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, forwarded-tcpip)`),I(this,this._packetRW.write.finalize(a))}x11(e,t,r,n){if(!this._server)throw new Error("Server-only method called in client mode");const s=Buffer.byteLength(n.originAddr);let i=this._packetRW.write.allocStart;const o=this._packetRW.write.alloc(24+s+4);o[i]=u.CHANNEL_OPEN,S(o,3,++i),o.utf8Write("x11",i+=4,3),S(o,e,i+=3),S(o,t,i+=4),S(o,r,i+=4),S(o,s,i+=4),o.utf8Write(n.originAddr,i+=4,s),S(o,n.originPort,i+=s),this._debug&&this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, x11)`),I(this,this._packetRW.write.finalize(o))}openssh_authAgent(e,t,r){if(!this._server)throw new Error("Server-only method called in client mode");let n=this._packetRW.write.allocStart;const s=this._packetRW.write.alloc(39);s[n]=u.CHANNEL_OPEN,S(s,22,++n),s.utf8Write("auth-agent@openssh.com",n+=4,22),S(s,e,n+=22),S(s,t,n+=4),S(s,r,n+=4),this._debug&&this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, auth-agent@openssh.com)`),I(this,this._packetRW.write.finalize(s))}openssh_forwardedStreamLocal(e,t,r,n){if(!this._server)throw new Error("Server-only method called in client mode");const s=Buffer.byteLength(n.socketPath);let i=this._packetRW.write.allocStart;const o=this._packetRW.write.alloc(54+s+4);o[i]=u.CHANNEL_OPEN,S(o,33,++i),o.utf8Write("forwarded-streamlocal@openssh.com",i+=4,33),S(o,e,i+=33),S(o,t,i+=4),S(o,r,i+=4),S(o,s,i+=4),o.utf8Write(n.socketPath,i+=4,s),S(o,0,i+=s),this._debug&&this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, forwarded-streamlocal@openssh.com)`),I(this,this._packetRW.write.finalize(o))}exitStatus(e,t){if(!this._server)throw new Error("Server-only method called in client mode");let r=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(25);n[r]=u.CHANNEL_REQUEST,S(n,e,++r),S(n,11,r+=4),n.utf8Write("exit-status",r+=4,11),n[r+=11]=0,S(n,t,++r),this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, exit-status: ${t})`),I(this,this._packetRW.write.finalize(n))}exitSignal(e,t,r,n){if(!this._server)throw new Error("Server-only method called in client mode");const s=t;if("string"!=typeof s||!s)throw new Error(`Invalid signal: ${s}`);let i=t.toUpperCase();if("SIG"===i.slice(0,3)&&(i=i.slice(3)),1!==h[i])throw new Error(`Invalid signal: ${s}`);const o=Buffer.byteLength(i),a=n?Buffer.byteLength(n):0;let c=this._packetRW.write.allocStart;const l=this._packetRW.write.alloc(25+o+1+4+a+4);l[c]=u.CHANNEL_REQUEST,S(l,e,++c),S(l,11,c+=4),l.utf8Write("exit-signal",c+=4,11),l[c+=11]=0,S(l,o,++c),l.utf8Write(i,c+=4,o),l[c+=o]=r?1:0,S(l,a,++c),c+=4,a&&(l.utf8Write(n,c,a),c+=a),S(l,0,c),this._debug&&this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, exit-signal: ${t})`),I(this,this._packetRW.write.finalize(l))}authFailure(e,t){if(!this._server)throw new Error("Server-only method called in client mode");if(0===this._authsQueue.length)throw new Error("No auth in progress");let r;if("boolean"==typeof e&&(t=e,e=void 0),e){r=[];for(let t=0;t<e.length;++t)"none"!==e[t].toLowerCase()&&r.push(e[t]);r=r.join(",")}else r="";const n=r.length;let s=this._packetRW.write.allocStart;const i=this._packetRW.write.alloc(5+n+1);i[s]=u.USERAUTH_FAILURE,S(i,n,++s),i.utf8Write(r,s+=4,n),i[s+=n]=!0===t?1:0,this._authsQueue.shift(),this._debug&&this._debug("Outbound: Sending USERAUTH_FAILURE"),I(this,this._packetRW.write.finalize(i))}authSuccess(){if(!this._server)throw new Error("Server-only method called in client mode");if(0===this._authsQueue.length)throw new Error("No auth in progress");const e=this._packetRW.write.allocStart,t=this._packetRW.write.alloc(1);t[e]=u.USERAUTH_SUCCESS,this._authsQueue.shift(),this._authenticated=!0,this._debug&&this._debug("Outbound: Sending USERAUTH_SUCCESS"),I(this,this._packetRW.write.finalize(t)),"zlib@openssh.com"===this._kex.negotiated.cs.compress&&(this._packetRW.read=new O),"zlib@openssh.com"===this._kex.negotiated.sc.compress&&(this._packetRW.write=new C(this))}authPKOK(e,t){if(!this._server)throw new Error("Server-only method called in client mode");if(0===this._authsQueue.length||"publickey"!==this._authsQueue[0])throw new Error('"publickey" auth not in progress');const r=Buffer.byteLength(e),n=t.length;let s=this._packetRW.write.allocStart;const i=this._packetRW.write.alloc(5+r+4+n);i[s]=u.USERAUTH_PK_OK,S(i,r,++s),i.utf8Write(e,s+=4,r),S(i,n,s+=r),i.set(t,s+=4),this._authsQueue.shift(),this._debug&&this._debug("Outbound: Sending USERAUTH_PK_OK"),I(this,this._packetRW.write.finalize(i))}authPasswdChg(e){if(!this._server)throw new Error("Server-only method called in client mode");const t=Buffer.byteLength(e);let r=this._packetRW.write.allocStart;const n=this._packetRW.write.alloc(5+t+4);n[r]=u.USERAUTH_PASSWD_CHANGEREQ,S(n,t,++r),n.utf8Write(e,r+=4,t),S(n,0,r+=t),this._debug&&this._debug("Outbound: Sending USERAUTH_PASSWD_CHANGEREQ"),I(this,this._packetRW.write.finalize(n))}authInfoReq(e,t,r){if(!this._server)throw new Error("Server-only method called in client mode");let n=0;const s=e?Buffer.byteLength(e):0,i=t?Buffer.byteLength(t):0;for(let e=0;e<r.length;++e)n+=4+Buffer.byteLength(r[e].prompt)+1;let o=this._packetRW.write.allocStart;const a=this._packetRW.write.alloc(5+s+4+i+4+4+n);a[o]=u.USERAUTH_INFO_REQUEST,S(a,s,++o),o+=4,e&&(a.utf8Write(e,o,s),o+=s),S(a,i,o),o+=4,t&&(a.utf8Write(t,o,i),o+=i),S(a,0,o),S(a,r.length,o+=4),o+=4;for(let e=0;e<r.length;++e){const t=r[e],n=Buffer.byteLength(t.prompt);S(a,n,o),o+=4,n&&(a.utf8Write(t.prompt,o,n),o+=n),a[o++]=t.echo?1:0}this._debug&&this._debug("Outbound: Sending USERAUTH_INFO_REQUEST"),I(this,this._packetRW.write.finalize(a))}}},5473(e,t,r){"use strict";const n=r(4434),s=r(9896),{constants:i}=s,{Readable:o,Writable:a}=r(2203),{inherits:c,types:{isDate:l}}=r(9023),u=Buffer[Symbol.species],{bufferCopy:h,bufferSlice:d,makeBufferParser:f,writeUInt32BE:p}=r(4787),_=Buffer.alloc(28),g={OK:0,EOF:1,NO_SUCH_FILE:2,PERMISSION_DENIED:3,FAILURE:4,BAD_MESSAGE:5,NO_CONNECTION:6,CONNECTION_LOST:7,OP_UNSUPPORTED:8},m=new Map(Object.values(g).map(e=>[e,1])),y={[g.OK]:"No error",[g.EOF]:"End of file",[g.NO_SUCH_FILE]:"No such file or directory",[g.PERMISSION_DENIED]:"Permission denied",[g.FAILURE]:"Failure",[g.BAD_MESSAGE]:"Bad message",[g.NO_CONNECTION]:"No connection",[g.CONNECTION_LOST]:"Connection lost",[g.OP_UNSUPPORTED]:"Operation unsupported"},A=1,v=3,b=4,w=5,E=6,I=7,S=8,P=9,k=10,O=11,C=12,R=13,B=14,x=15,T=16,N=17,F=18,M=19,L=20,U=200,D=2,$=101,j=102,H=103,G=104,Q=105,q=201,W={READ:1,WRITE:2,APPEND:4,CREAT:8,TRUNC:16,EXCL:32},K=2**32-1,X=Buffer.from([0,0,0,5,1,0,0,0,3]),z=Buffer.from([0,0,0,5,2,0,0,0,3]),Y=/^SSH-2.0-(?:OpenSSH|dropbear)/,J=262144,V=f(),Z={readable:!1,writable:!1,push:e=>{},once:()=>{},on:()=>{},emit:()=>{},end:()=>{}};function ee(){}function te(e,t,r,n,s,i,o,a){const c=e._maxReadLen,l=Math.max(s-c,0);l&&(s=c);const u=t.length;let h=9,f=i;const _=Buffer.allocUnsafe(13+u+8+4);p(_,_.length-4,0),_[4]=5;const m=e._writeReqid=e._writeReqid+1&K;p(_,m,5),p(_,u,h),_.set(t,h+=4),h+=u;for(let e=7;e>=0;--e)_[h+e]=255&f,f/=256;p(_,s,h+=8),"function"!=typeof o&&(o=ee);const y=a||{nb:0,position:i,off:n,origOff:n,len:void 0,overflow:void 0,cb:(n,s,i)=>{const a=y.len,c=y.overflow;if(n){if(o._wantEOFError||n.code!==g.EOF)return o(n)}else{if(i>a)return o(new Error("Received more data than requested"));if(i===a&&c)return y.nb+=i,y.position+=i,y.off+=i,void te(e,t,r,y.off,c,y.position,o,y)}i=i||0,s=0===y.origOff&&r.length===y.nb?r:d(r,y.origOff,y.origOff+y.nb+i),o(void 0,y.nb+i,s,y.position)},buffer:void 0};y.len=s,y.overflow=l,y.buffer=d(r,n,n+s),e._requests[m]=y;const A=de(e,_);e._debug&&e._debug(`SFTP: Outbound: ${A?"Buffered":"Sending"} READ`)}function re(e,t,r,n,i,o){let a,c,l,u,h=64,d=32768;"function"==typeof i?o=i:"object"==typeof i&&null!==i&&("number"==typeof i.concurrency&&i.concurrency>0&&!isNaN(i.concurrency)&&(h=i.concurrency),"number"==typeof i.chunkSize&&i.chunkSize>0&&!isNaN(i.chunkSize)&&(d=i.chunkSize),"number"==typeof i.fileSize&&i.fileSize>0&&!isNaN(i.fileSize)&&(l=i.fileSize),"function"==typeof i.step&&(a=i.step),"string"!=typeof i.mode&&"number"!=typeof i.mode||(c=ae(i.mode)));let f,p,_,g=0,m=0,y=!1,A=d*h;function v(r){if(y)return;y=!0;let n,i=0;f||p?(n=()=>{0===--i&&o(r)},!f||e!==s&&"open"!==e.outgoing.state||++i,!p||t!==s&&"open"!==t.outgoing.state||++i,!f||e!==s&&"open"!==e.outgoing.state||e.close(f,n),!p||t!==s&&"open"!==t.outgoing.state||t.close(p,n)):o(r)}e.open(r,"r",(i,y)=>{if(i)return v(i);function b(i,l){if(i)return e!==s?void e.stat(r,(e,t)=>{if(e)return v(i);b(null,t)}):v(i);u=l.size,t.open(n,"w",(r,s)=>{if(r)return v(r);if(p=s,u<=0)return v();for(;A>u;){if(1===h){A=u;break}A-=d,--h}if(_=function(e){try{return Buffer.allocUnsafe(e)}catch(e){return e}}(A),_ instanceof Error)return v(_);function i(r,n,s,i,c,h){if(r)return v(r);c=c||0,t.write(p,_,c,n,i,function(r){if(r)return v(r);if(m+=n,a&&a(m,n,u),n<h)return l(c,i+n,h-n);if(m===u)return void t.close(p,t=>{if(p=void 0,t)return v(t);e.close(f,e=>{if(f=void 0,e)return v(e);o()})});if(g>=u)return;const s=g+d>u?u-g:d;l(c,g,s),g+=s})}function l(t,r,n){e.read(f,_,t,n,r,function(e,t,r){return(n,s,o)=>{i(n,s,0,t,e,r)}}(t,r,n))}function y(){let e=0,t=0;for(;g<u&&e<h;){const r=g+d>u?u-g:d;l(t,g,r),t+=r,g+=r,++e}}void 0!==c?t.fchmod(p,c,function e(r){r?t.chmod(n,c,t=>e()):y()}):y()})}f=y,void 0===l?e.fstat(f,b):b(null,{size:l})})}function ne(e,t,r,n,s,i,o){const a="function"==typeof o?o:void 0;e.write(t,r,n,s,i,(o,c)=>{if(o)return e.close(t,()=>{a&&a(o)});c===s?e.close(t,a):ne(e,t,r,n+=c,s-=c,i+=c,a)})}class se{constructor(e){this.mode=e&&e.mode,this.uid=e&&e.uid,this.gid=e&&e.gid,this.size=e&&e.size,this.atime=e&&e.atime,this.mtime=e&&e.mtime,this.extended=e&&e.extended}isDirectory(){return(this.mode&i.S_IFMT)===i.S_IFDIR}isFile(){return(this.mode&i.S_IFMT)===i.S_IFREG}isBlockDevice(){return(this.mode&i.S_IFMT)===i.S_IFBLK}isCharacterDevice(){return(this.mode&i.S_IFMT)===i.S_IFCHR}isSymbolicLink(){return(this.mode&i.S_IFMT)===i.S_IFLNK}isFIFO(){return(this.mode&i.S_IFMT)===i.S_IFIFO}isSocket(){return(this.mode&i.S_IFMT)===i.S_IFSOCK}}function ie(e){let t=0,r=0;if("object"==typeof e&&null!==e){if("number"==typeof e.size){t|=1;const n=e.size;_[r++]=n/72057594037927940,_[r++]=n/281474976710656,_[r++]=n/1099511627776,_[r++]=n/4294967296,_[r++]=n/16777216,_[r++]=n/65536,_[r++]=n/256,_[r++]=n}if("number"==typeof e.uid&&"number"==typeof e.gid){t|=2;const n=e.uid,s=e.gid;_[r++]=n>>>24,_[r++]=n>>>16,_[r++]=n>>>8,_[r++]=n,_[r++]=s>>>24,_[r++]=s>>>16,_[r++]=s>>>8,_[r++]=s}if("number"==typeof e.mode||"string"==typeof e.mode){const n=ae(e.mode);t|=4,_[r++]=n>>>24,_[r++]=n>>>16,_[r++]=n>>>8,_[r++]=n}if(("number"==typeof e.atime||l(e.atime))&&("number"==typeof e.mtime||l(e.mtime))){const n=oe(e.atime),s=oe(e.mtime);t|=8,_[r++]=n>>>24,_[r++]=n>>>16,_[r++]=n>>>8,_[r++]=n,_[r++]=s>>>24,_[r++]=s>>>16,_[r++]=s>>>8,_[r++]=s}}return{flags:t,nb:r}}function oe(e){if("number"==typeof e&&e==e)return e;if(l(e))return parseInt(e.getTime()/1e3,10);throw new Error(`Cannot parse time: ${e}`)}function ae(e){if("number"==typeof e&&e==e)return e;if("string"==typeof e)return ae(parseInt(e,8));throw new Error(`Cannot parse mode: ${e}`)}const ce={r:W.READ,"r+":W.READ|W.WRITE,w:W.TRUNC|W.CREAT|W.WRITE,wx:W.TRUNC|W.CREAT|W.WRITE|W.EXCL,xw:W.TRUNC|W.CREAT|W.WRITE|W.EXCL,"w+":W.TRUNC|W.CREAT|W.READ|W.WRITE,"wx+":W.TRUNC|W.CREAT|W.READ|W.WRITE|W.EXCL,"xw+":W.TRUNC|W.CREAT|W.READ|W.WRITE|W.EXCL,a:W.APPEND|W.CREAT|W.WRITE,ax:W.APPEND|W.CREAT|W.WRITE|W.EXCL,xa:W.APPEND|W.CREAT|W.WRITE|W.EXCL,"a+":W.APPEND|W.CREAT|W.READ|W.WRITE,"ax+":W.APPEND|W.CREAT|W.READ|W.WRITE|W.EXCL,"xa+":W.APPEND|W.CREAT|W.READ|W.WRITE|W.EXCL};function le(e){const t=ce[e];return void 0!==t?t:null}const ue=(()=>{const e=Object.keys(ce);return t=>{for(let r=0;r<e.length;++r){const n=e[r];if(ce[n]===t)return n}return null}})();function he(e){const t=V.readUInt32BE();if(void 0===t)return;const r=new se;if(1&t){const t=V.readUInt64BE(e);if(void 0===t)return;r.size=t}if(2&t){const e=V.readUInt32BE(),t=V.readUInt32BE();if(void 0===t)return;r.uid=e,r.gid=t}if(4&t){const e=V.readUInt32BE();if(void 0===e)return;r.mode=e}if(8&t){const e=V.readUInt32BE(),t=V.readUInt32BE();if(void 0===t)return;r.atime=e,r.mtime=t}if(2147483648&t){const e=V.readUInt32BE();if(void 0===e)return;const t={};for(let r=0;r<e;++r){const e=V.readString(!0),r=V.readString();if(void 0===r)return;t[e]=r}r.extended=t}return r}function de(e,t){const r=fe(e,t);return void 0===r||(e._buffer.push(r),!1)}function fe(e,t){const r=e.outgoing;if("open"!==r.state)return;if(0===r.window)return e._waitWindow=!0,e._chunkcb=pe,t;let n;const s=t.length;let i=0;for(;s-i>0&&r.window>0;){const n=Math.min(s-i,r.window,r.packetSize);r.window-=n,0===r.window&&(e._waitWindow=!0,e._chunkcb=pe),0===i&&n===s?e._protocol.channelData(e.outgoing.id,t):e._protocol.channelData(e.outgoing.id,d(t,i,i+n)),i+=n}return s-i>0&&(n=i>0?d(t,i,s):t),n}function pe(){this._chunkcb=void 0;const e=this._buffer;let t=0;for(;t<e.length;){const r=e[t],n=fe(this,r);if(void 0!==n)return n!==r&&(e[t]=n),void(t>0&&(this._buffer=e.slice(t)));++t}t>0&&(this._buffer=[])}function _e(e,t,r){const n=new Error(t);return n.level="sftp-protocol",!r&&e._debug&&e._debug(`SFTP: Inbound: ${t}`),e.emit("error",n),e.destroy(),ge(e),!1}function ge(e){const t=Object.keys(e._requests);if(0===t.length)return;const r=e._requests;e._requests={};const n=new Error("No response from server");for(let e=0;e<t.length;++e){const s=r[t[e]];"function"==typeof s.cb&&s.cb(n)}}const me={[D]:(e,t)=>{if(-1!==e._version)return _e(e,"Duplicate VERSION packet");const r={};V.init(t,1);let n=V.readUInt32BE();for(;V.avail();){const e=V.readString(!0),t=V.readString(!0);if(void 0===t){n=void 0;break}r[e]=t}if(V.clear(),void 0===n)return _e(e,"Malformed VERSION packet");if(e._debug){const t=Object.keys(r);t.length?e._debug(`SFTP: Inbound: Received VERSION (v${n}, exts:${t})`):e._debug(`SFTP: Inbound: Received VERSION (v${n})`)}if(e._version=n,e._extensions=r,"1"===r["limits@openssh.com"])return function(e,t){let r=9;const n=Buffer.allocUnsafe(31);p(n,n.length-4,0),n[4]=U;const s=e._writeReqid=e._writeReqid+1&K;p(n,s,5),p(n,18,r),n.utf8Write("limits@openssh.com",r+=4,18),e._requests[s]={extended:"limits@openssh.com",cb:t};const i=de(e,n);if(e._debug){const t=i?"Buffered":"Sending";e._debug(`SFTP: Outbound: ${t} limits@openssh.com`)}}(e,(t,r)=>{t||(r.maxPktLen>0&&(e._maxOutPktLen=r.maxPktLen),r.maxReadLen>0&&(e._maxReadLen=r.maxReadLen),r.maxWriteLen>0&&(e._maxWriteLen=r.maxWriteLen),e.maxOpenHandles=r.maxOpenHandles>0?r.maxOpenHandles:1/0),e.emit("ready")});e.emit("ready")},[$]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readUInt32BE(),s=V.readString(!0);if(V.clear(),e._debug){const t=JSON.stringify(s);e._debug(`SFTP: Inbound: Received STATUS (id:${r}, ${n}, ${t})`)}const i=e._requests[r];if(delete e._requests[r],i&&"function"==typeof i.cb){if(n===g.OK)return void i.cb();const e=new Error(s||y[n]||"Unknown status");e.code=n,i.cb(e)}},[j]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString();if(V.clear(),void 0===n)return void 0!==r&&delete e._requests[r],_e(e,"Malformed HANDLE packet");e._debug&&e._debug(`SFTP: Inbound: Received HANDLE (id:${r})`);const s=e._requests[r];delete e._requests[r],s&&"function"==typeof s.cb&&s.cb(void 0,n)},[H]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE();let n;if(void 0!==r&&(n=e._requests[r],delete e._requests[r]),n&&"function"==typeof n.cb)if(n.buffer){const t=V.readString(n.buffer);if(V.clear(),void 0!==t)return e._debug&&e._debug(`SFTP: Inbound: Received DATA (id:${r}, ${t})`),void n.cb(void 0,n.buffer,t)}else{const t=V.readString();if(V.clear(),void 0!==t)return e._debug&&e._debug(`SFTP: Inbound: Received DATA (id:${r}, ${t.length})`),void n.cb(void 0,t)}else{const t=V.skipString();if(V.clear(),void 0!==t)return void(e._debug&&e._debug(`SFTP: Inbound: Received DATA (id:${r}, ${t})`))}return _e(e,"Malformed DATA packet")},[G]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE();let n;void 0!==r&&(n=e._requests[r],delete e._requests[r]);const s=V.readUInt32BE();if(void 0!==s){let t=[];for(let r=0;r<s;++r){const r=V.readString(!0),n=V.readString(!0),s=he(e._biOpt);if(void 0===s){t=void 0;break}t.push({filename:r,longname:n,attrs:s})}if(void 0!==t)return e._debug&&e._debug(`SFTP: Inbound: Received NAME (id:${r}, ${t.length})`),V.clear(),void(n&&"function"==typeof n.cb&&n.cb(void 0,t))}return V.clear(),_e(e,"Malformed NAME packet")},[Q]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE();let n;void 0!==r&&(n=e._requests[r],delete e._requests[r]);const s=he(e._biOpt);return V.clear(),void 0!==s?(e._debug&&e._debug(`SFTP: Inbound: Received ATTRS (id:${r})`),void(n&&"function"==typeof n.cb&&n.cb(void 0,s))):_e(e,"Malformed ATTRS packet")},[q]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE();if(void 0!==r){const t=e._requests[r];if(!t)return e._debug&&e._debug(`SFTP: Inbound: Received EXTENDED_REPLY (id:${r}, ???)`),void V.clear();switch(delete e._requests[r],t.extended){case"statvfs@openssh.com":case"fstatvfs@openssh.com":{const n=e._biOpt,s={f_bsize:V.readUInt64BE(n),f_frsize:V.readUInt64BE(n),f_blocks:V.readUInt64BE(n),f_bfree:V.readUInt64BE(n),f_bavail:V.readUInt64BE(n),f_files:V.readUInt64BE(n),f_ffree:V.readUInt64BE(n),f_favail:V.readUInt64BE(n),f_sid:V.readUInt64BE(n),f_flag:V.readUInt64BE(n),f_namemax:V.readUInt64BE(n)};if(void 0===s.f_namemax)break;return e._debug&&e._debug(`SFTP: Inbound: Received EXTENDED_REPLY (id:${r}, ${t.extended})`),V.clear(),void("function"==typeof t.cb&&t.cb(void 0,s))}case"limits@openssh.com":{const n={maxPktLen:V.readUInt64BE(),maxReadLen:V.readUInt64BE(),maxWriteLen:V.readUInt64BE(),maxOpenHandles:V.readUInt64BE()};if(void 0===n.maxOpenHandles)break;return e._debug&&e._debug(`SFTP: Inbound: Received EXTENDED_REPLY (id:${r}, ${t.extended})`),V.clear(),void("function"==typeof t.cb&&t.cb(void 0,n))}case"users-groups-by-id@openssh.com":{const n=V.readUInt32BE();if(void 0===n)break;const s=new Array(n);for(let e=0;e<s.length;++e)s[e]=V.readString(!0);const i=V.readUInt32BE();if(void 0===i)break;const o=new Array(i);for(let e=0;e<o.length;++e)o[e]=V.readString(!0);if(o.length>0&&void 0===o[o.length-1])break;return e._debug&&e._debug(`SFTP: Inbound: Received EXTENDED_REPLY (id:${r}, ${t.extended})`),V.clear(),void("function"==typeof t.cb&&t.cb(void 0,s,o))}default:return e._debug&&e._debug(`SFTP: Inbound: Received EXTENDED_REPLY (id:${r}, ???)`),V.clear(),void("function"==typeof t.cb&&t.cb())}}return V.clear(),_e(e,"Malformed EXTENDED_REPLY packet")}},ye={[A]:(e,t)=>{if(-1!==e._version)return _e(e,"Duplicate INIT packet");const r={};V.init(t,1);let n=V.readUInt32BE();for(;V.avail();){const e=V.readString(!0),t=V.readString(!0);if(void 0===t){n=void 0;break}r[e]=t}if(V.clear(),void 0===n)return _e(e,"Malformed INIT packet");if(e._debug){const t=Object.keys(r);t.length?e._debug(`SFTP: Inbound: Received INIT (v${n}, exts:${t})`):e._debug(`SFTP: Inbound: Received INIT (v${n})`)}de(e,z),e._version=n,e._extensions=r,e.emit("ready")},[v]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0),s=V.readUInt32BE(),i=he(e._biOpt);if(V.clear(),void 0===i)return _e(e,"Malformed OPEN packet");e._debug&&e._debug(`SFTP: Inbound: Received OPEN (id:${r})`),e.emit("OPEN",r,n,s,i)||e.status(r,g.OP_UNSUPPORTED)},[b]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString();if(V.clear(),void 0===n||n.length>256)return _e(e,"Malformed CLOSE packet");e._debug&&e._debug(`SFTP: Inbound: Received CLOSE (id:${r})`),e.emit("CLOSE",r,n)||e.status(r,g.OP_UNSUPPORTED)},[w]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(),s=V.readUInt64BE(e._biOpt),i=V.readUInt32BE();if(V.clear(),void 0===i||n.length>256)return _e(e,"Malformed READ packet");e._debug&&e._debug(`SFTP: Inbound: Received READ (id:${r})`),e.emit("READ",r,n,s,i)||e.status(r,g.OP_UNSUPPORTED)},[E]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(),s=V.readUInt64BE(e._biOpt),i=V.readString();if(V.clear(),void 0===i||n.length>256)return _e(e,"Malformed WRITE packet");e._debug&&e._debug(`SFTP: Inbound: Received WRITE (id:${r})`),e.emit("WRITE",r,n,s,i)||e.status(r,g.OP_UNSUPPORTED)},[I]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0);if(V.clear(),void 0===n)return _e(e,"Malformed LSTAT packet");e._debug&&e._debug(`SFTP: Inbound: Received LSTAT (id:${r})`),e.emit("LSTAT",r,n)||e.status(r,g.OP_UNSUPPORTED)},[S]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString();if(V.clear(),void 0===n||n.length>256)return _e(e,"Malformed FSTAT packet");e._debug&&e._debug(`SFTP: Inbound: Received FSTAT (id:${r})`),e.emit("FSTAT",r,n)||e.status(r,g.OP_UNSUPPORTED)},[P]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0),s=he(e._biOpt);if(V.clear(),void 0===s)return _e(e,"Malformed SETSTAT packet");e._debug&&e._debug(`SFTP: Inbound: Received SETSTAT (id:${r})`),e.emit("SETSTAT",r,n,s)||e.status(r,g.OP_UNSUPPORTED)},[k]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(),s=he(e._biOpt);if(V.clear(),void 0===s||n.length>256)return _e(e,"Malformed FSETSTAT packet");e._debug&&e._debug(`SFTP: Inbound: Received FSETSTAT (id:${r})`),e.emit("FSETSTAT",r,n,s)||e.status(r,g.OP_UNSUPPORTED)},[O]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0);if(V.clear(),void 0===n)return _e(e,"Malformed OPENDIR packet");e._debug&&e._debug(`SFTP: Inbound: Received OPENDIR (id:${r})`),e.emit("OPENDIR",r,n)||e.status(r,g.OP_UNSUPPORTED)},[C]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString();if(V.clear(),void 0===n||n.length>256)return _e(e,"Malformed READDIR packet");e._debug&&e._debug(`SFTP: Inbound: Received READDIR (id:${r})`),e.emit("READDIR",r,n)||e.status(r,g.OP_UNSUPPORTED)},[R]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0);if(V.clear(),void 0===n)return _e(e,"Malformed REMOVE packet");e._debug&&e._debug(`SFTP: Inbound: Received REMOVE (id:${r})`),e.emit("REMOVE",r,n)||e.status(r,g.OP_UNSUPPORTED)},[B]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0),s=he(e._biOpt);if(V.clear(),void 0===s)return _e(e,"Malformed MKDIR packet");e._debug&&e._debug(`SFTP: Inbound: Received MKDIR (id:${r})`),e.emit("MKDIR",r,n,s)||e.status(r,g.OP_UNSUPPORTED)},[x]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0);if(V.clear(),void 0===n)return _e(e,"Malformed RMDIR packet");e._debug&&e._debug(`SFTP: Inbound: Received RMDIR (id:${r})`),e.emit("RMDIR",r,n)||e.status(r,g.OP_UNSUPPORTED)},[T]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0);if(V.clear(),void 0===n)return _e(e,"Malformed REALPATH packet");e._debug&&e._debug(`SFTP: Inbound: Received REALPATH (id:${r})`),e.emit("REALPATH",r,n)||e.status(r,g.OP_UNSUPPORTED)},[N]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0);if(V.clear(),void 0===n)return _e(e,"Malformed STAT packet");e._debug&&e._debug(`SFTP: Inbound: Received STAT (id:${r})`),e.emit("STAT",r,n)||e.status(r,g.OP_UNSUPPORTED)},[F]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0),s=V.readString(!0);if(V.clear(),void 0===s)return _e(e,"Malformed RENAME packet");e._debug&&e._debug(`SFTP: Inbound: Received RENAME (id:${r})`),e.emit("RENAME",r,n,s)||e.status(r,g.OP_UNSUPPORTED)},[M]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0);if(V.clear(),void 0===n)return _e(e,"Malformed READLINK packet");e._debug&&e._debug(`SFTP: Inbound: Received READLINK (id:${r})`),e.emit("READLINK",r,n)||e.status(r,g.OP_UNSUPPORTED)},[L]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0),s=V.readString(!0);if(V.clear(),void 0===s)return _e(e,"Malformed SYMLINK packet");let i;e._debug&&e._debug(`SFTP: Inbound: Received SYMLINK (id:${r})`),i=e._isOpenSSH?e.emit("SYMLINK",r,s,n):e.emit("SYMLINK",r,n,s),i||e.status(r,g.OP_UNSUPPORTED)},[U]:(e,t)=>{V.init(t,1);const r=V.readUInt32BE(),n=V.readString(!0);if(void 0===n)return V.clear(),_e(e,"Malformed EXTENDED packet");let s;V.avail()&&(s=V.readRaw()),V.clear(),e._debug&&e._debug(`SFTP: Inbound: Received EXTENDED (id:${r})`),e.emit("EXTENDED",r,n,s)||e.status(r,g.OP_UNSUPPORTED)}},{ERR_INVALID_ARG_TYPE:Ae,ERR_OUT_OF_RANGE:ve,validateNumber:be}=r(4397);let we;const Ee=[];function Ie(e,t){if(!Number.isSafeInteger(e)){if(be(e,t),!Number.isInteger(e))throw new ve(t,"an integer",e);throw new ve(t,">= 0 and <= 2 ** 53 - 1",e)}if(e<0)throw new ve(t,">= 0 and <= 2 ** 53 - 1",e)}function Se(e){return e+7&-8}function Pe(e,t,r){if(void 0===r)r={};else if("string"==typeof r)r={encoding:r};else{if(null===r||"object"!=typeof r)throw new TypeError('"options" argument must be a string or an object');r=Object.create(r)}if(void 0===r.highWaterMark&&(r.highWaterMark=65536),r.emitClose=!1,r.autoDestroy=!1,o.call(this,r),this.path=t,this.flags=void 0===r.flags?"r":r.flags,this.mode=void 0===r.mode?438:r.mode,this.start=r.start,this.end=r.end,this.autoClose=void 0===r.autoClose||r.autoClose,this.pos=0,this.bytesRead=0,this.isClosed=!1,this.handle=void 0===r.handle?null:r.handle,this.sftp=e,this._opening=!1,void 0!==this.start&&(Ie(this.start,"start"),this.pos=this.start),void 0===this.end)this.end=1/0;else if(this.end!==1/0&&(Ie(this.end,"end"),void 0!==this.start&&this.start>this.end))throw new ve("start",`<= "end" (here: ${this.end})`,this.start);this.on("end",function(){this.autoClose&&this.destroy()}),Buffer.isBuffer(this.handle)||this.open()}function ke(e,t,r){if(!e.handle)return n();function n(n){t(n=n||r),e.isClosed=!0,n||e.emit("close")}e.sftp.close(e.handle,n)}function Oe(e,t,r){if(void 0===r)r={};else if("string"==typeof r)r={encoding:r};else{if(null===r||"object"!=typeof r)throw new TypeError('"options" argument must be a string or an object');r=Object.create(r)}r.emitClose=!1,r.autoDestroy=!1,a.call(this,r),this.path=t,this.flags=void 0===r.flags?"w":r.flags,this.mode=void 0===r.mode?438:r.mode,this.start=r.start,this.autoClose=void 0===r.autoClose||r.autoClose,this.pos=0,this.bytesWritten=0,this.isClosed=!1,this.handle=void 0===r.handle?null:r.handle,this.sftp=e,this._opening=!1,void 0!==this.start&&(Ie(this.start,"start"),this.pos=this.start),r.encoding&&this.setDefaultEncoding(r.encoding),this.on("finish",function(){this._writableState.finalCalled||this.autoClose&&this.destroy()}),Buffer.isBuffer(this.handle)||this.open()}c(Pe,o),Pe.prototype.open=function(){this._opening||(this._opening=!0,this.sftp.open(this.path,this.flags,this.mode,(e,t)=>{if(this._opening=!1,e)return this.emit("error",e),void(this.autoClose&&this.destroy());this.handle=t,this.emit("open",t),this.emit("ready"),this.read()}))},Pe.prototype._read=function(e){if(!Buffer.isBuffer(this.handle))return this.once("open",()=>this._read(e));if(this.destroyed)return;var t;(!we||we.length-we.used<128)&&(t=this.readableHighWaterMark||this._readableState.highWaterMark,we=Ee.length>0?Ee.pop():Buffer.allocUnsafe(t),we.used=0);const r=we;let n=Math.min(we.length-we.used,e);const s=we.used;if(void 0!==this.end&&(n=Math.min(this.end-this.pos+1,n)),n<=0)return this.push(null);this.sftp.read(this.handle,we,we.used,n,this.pos,(e,t)=>{if(e)return this.emit("error",e),void(this.autoClose&&this.destroy());let i=null;if(s+n===r.used&&r===we)r.used=Se(r.used+t-n);else{const e=s+n&-8,i=Se(s+t);e-i>=128&&Ee.push(r.slice(i,e))}t>0&&(this.bytesRead+=t,i=r.slice(s,s+t)),this.pos+=t,this.push(i)}),we.used=Se(we.used+n)},Pe.prototype._destroy=function(e,t){!this._opening||Buffer.isBuffer(this.handle)?(ke(this,t,e),this.handle=null,this._opening=!1):this.once("open",ke.bind(null,this,t,e))},Pe.prototype.close=function(e){this.destroy(null,e)},Object.defineProperty(Pe.prototype,"pending",{get(){return null===this.handle},configurable:!0}),c(Oe,a),Oe.prototype._final=function(e){this.autoClose&&this.destroy(),e()},Oe.prototype.open=function(){this._opening||(this._opening=!0,this.sftp.open(this.path,this.flags,this.mode,(e,t)=>{if(this._opening=!1,e)return this.emit("error",e),void(this.autoClose&&this.destroy());this.handle=t;const r=e=>{if(e)this.sftp.chmod(this.path,this.mode,e=>r());else{if("a"===this.flags[0]){const e=(r,n)=>{r?this.sftp.stat(this.path,(t,n)=>{if(t)return this.destroy(),void this.emit("error",r);e(null,n)}):(this.pos=n.size,this.emit("open",t),this.emit("ready"))};return void this.sftp.fstat(t,e)}this.emit("open",t),this.emit("ready")}};this.sftp.fchmod(t,this.mode,r)}))},Oe.prototype._write=function(e,t,r){if(!Buffer.isBuffer(e)){const t=new Ae("data","Buffer",e);return this.emit("error",t)}if(!Buffer.isBuffer(this.handle))return this.once("open",function(){this._write(e,t,r)});this.sftp.write(this.handle,e,0,e.length,this.pos,(e,t)=>{if(e)return this.autoClose&&this.destroy(),r(e);this.bytesWritten+=t,r()}),this.pos+=e.length},Oe.prototype._writev=function(e,t){if(!Buffer.isBuffer(this.handle))return this.once("open",function(){this._writev(e,t)});const r=this.sftp,n=this.handle;let s=e.length;const i=(e,r)=>{if(e)return this.destroy(),t(e);this.bytesWritten+=r,0===--s&&t()};for(let t=0;t<e.length;++t){const s=e[t].chunk;r.write(n,s,0,s.length,this.pos,i),this.pos+=s.length}},"function"!=typeof a.prototype.destroy&&(Oe.prototype.destroy=Pe.prototype.destroy),Oe.prototype._destroy=Pe.prototype._destroy,Oe.prototype.close=function(e){if(e){if(this.isClosed)return void process.nextTick(e);this.on("close",e)}this.autoClose||this.on("finish",this.destroy.bind(this)),this.end()},Oe.prototype.destroySoon=Oe.prototype.end,Object.defineProperty(Oe.prototype,"pending",{get(){return null===this.handle},configurable:!0}),e.exports={flagsToString:ue,OPEN_MODE:W,SFTP:class extends n{constructor(e,t,r){super(),"object"==typeof r&&r||(r={});const n=e._protocol._remoteIdentRaw;this.server=!!r.server,this._debug="function"==typeof r.debug?r.debug:void 0,this._isOpenSSH=n&&Y.test(n),this._version=-1,this._extensions={},this._biOpt=r.biOpt,this._pktLenBytes=0,this._pktLen=0,this._pktPos=0,this._pktType=0,this._pktData=void 0,this._writeReqid=-1,this._requests={},this._maxInPktLen=J,this._maxOutPktLen=34e3,this._maxReadLen=(this._isOpenSSH?J:34e3)-2048,this._maxWriteLen=(this._isOpenSSH?J:34e3)-2048,this.maxOpenHandles=void 0,this._client=e,this._protocol=e._protocol,this._callbacks=[],this._hasX11=!1,this._exit={code:void 0,signal:void 0,dump:void 0,desc:void 0},this._waitWindow=!1,this._chunkcb=void 0,this._buffer=[],this.type=t.type,this.subtype=void 0,this.incoming=t.incoming,this.outgoing=t.outgoing,this.stderr=Z,this.readable=!0}push(e){if(null===e){if(ge(this),!this.readable)return;return this.readable=!1,void this.emit("end")}let t=0;for(;t<e.length;){if(this._pktLenBytes<4){let r=Math.min(4-this._pktLenBytes,e.length-t);for(this._pktLenBytes+=r;r--;)this._pktLen=(this._pktLen<<8)+e[t++];if(this._pktLenBytes<4)return;if(0===this._pktLen)return _e(this,"Invalid packet length");if(this._pktLen>this._maxInPktLen){const e=this._maxInPktLen;return _e(this,`Packet length ${this._pktLen} exceeds max length of ${e}`)}if(t>=e.length)return}if(this._pktPos<this._pktLen){const r=Math.min(this._pktLen-this._pktPos,e.length-t);if(0!==t||r!==e.length?r===this._pktLen?this._pkt=new u(e.buffer,e.byteOffset+t,r):(this._pkt||(this._pkt=Buffer.allocUnsafe(this._pktLen)),this._pkt.set(new Uint8Array(e.buffer,e.byteOffset+t,r),this._pktPos)):r===this._pktLen?this._pkt=e:(this._pkt||(this._pkt=Buffer.allocUnsafe(this._pktLen)),this._pkt.set(e,this._pktPos)),t+=r,this._pktPos+=r,this._pktPos<this._pktLen)return}const r=this._pkt[0],n=this._pkt;this._pktLen=0,this._pktLenBytes=0,this._pkt=void 0,this._pktPos=0;const s=this.server?ye[r]:me[r];if(!s)return _e(this,`Unknown packet type ${r}`);if(-1===this._version)if(this.server){if(1!==r)return _e(this,`Expected INIT packet, got ${r}`)}else if(2!==r)return _e(this,`Expected VERSION packet, got ${r}`);if(!1===s(this,n))return}}end(){this.destroy()}destroy(){"open"!==this.outgoing.state&&"eof"!==this.outgoing.state||(this.outgoing.state="closing",this._protocol.channelClose(this.outgoing.id))}_init(){this._init=ee,this.server||de(this,X)}createReadStream(e,t){if(this.server)throw new Error("Client-only method called in server mode");return new Pe(this,e,t)}createWriteStream(e,t){if(this.server)throw new Error("Client-only method called in server mode");return new Oe(this,e,t)}open(e,t,r,n){if(this.server)throw new Error("Client-only method called in server mode");"function"==typeof r&&(n=r,r=void 0);const s="number"==typeof t?t:le(t);if(null===s)throw new Error(`Unknown flags string: ${t}`);let i=0,o=0;"string"!=typeof r&&"number"!=typeof r||(r={mode:r}),"object"==typeof r&&null!==r&&(i=(r=ie(r)).flags,o=r.nb);const a=Buffer.byteLength(e);let c=9;const l=Buffer.allocUnsafe(13+a+4+4+o);p(l,l.length-4,0),l[4]=3;const u=this._writeReqid=this._writeReqid+1&K;p(l,u,5),p(l,a,c),l.utf8Write(e,c+=4,a),p(l,s,c+=a),p(l,i,c+=4),o&&(c+=4,o===_.length?l.set(_,c):h(_,l,0,o,c),c+=o),this._requests[u]={cb:n};const d=de(this,l);this._debug&&this._debug(`SFTP: Outbound: ${d?"Buffered":"Sending"} OPEN`)}close(e,t){if(this.server)throw new Error("Client-only method called in server mode");if(!Buffer.isBuffer(e))throw new Error("handle is not a Buffer");const r=e.length;let n=9;const s=Buffer.allocUnsafe(13+r);p(s,s.length-4,0),s[4]=4;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,r,n),s.set(e,n+=4),this._requests[i]={cb:t};const o=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} CLOSE`)}read(e,t,r,n,s,i){if(this.server)throw new Error("Client-only method called in server mode");if(!Buffer.isBuffer(e))throw new Error("handle is not a Buffer");if(!Buffer.isBuffer(t))throw new Error("buffer is not a Buffer");if(r>=t.length)throw new Error("offset is out of bounds");if(r+n>t.length)throw new Error("length extends beyond buffer");if(null===s)throw new Error("null position currently unsupported");te(this,e,t,r,n,s,i)}readData(e,t,r,n,s,i){this.read(e,t,r,n,s,i)}write(e,t,r,n,s,i){if(this.server)throw new Error("Client-only method called in server mode");if(!Buffer.isBuffer(e))throw new Error("handle is not a Buffer");if(!Buffer.isBuffer(t))throw new Error("buffer is not a Buffer");if(r>t.length)throw new Error("offset is out of bounds");if(r+n>t.length)throw new Error("length extends beyond buffer");if(null===s)throw new Error("null position currently unsupported");if(!n)return void(i&&process.nextTick(i,void 0,0));const o=this._maxWriteLen,a=Math.max(n-o,0),c=s;a&&(n=o);const l=e.length;let u=9;const d=Buffer.allocUnsafe(13+l+8+4+n);p(d,d.length-4,0),d[4]=6;const f=this._writeReqid=this._writeReqid+1&K;p(d,f,5),p(d,l,u),d.set(e,u+=4),u+=l;for(let e=7;e>=0;--e)d[u+e]=255&s,s/=256;p(d,n,u+=8),h(t,d,r,r+n,u+=4),this._requests[f]={cb:s=>{s?"function"==typeof i&&i(s):a?this.write(e,t,r+n,a,c+n,i):"function"==typeof i&&i(void 0,r+n)}};const _=de(this,d);if(this._debug){const e=_?"Sent":"Buffered";this._debug(`SFTP: Outbound: ${e} WRITE (id:${f})`)}}writeData(e,t,r,n,s,i){this.write(e,t,r,n,s,i)}fastGet(e,t,r,n){if(this.server)throw new Error("Client-only method called in server mode");re(this,s,e,t,r,n)}fastPut(e,t,r,n){if(this.server)throw new Error("Client-only method called in server mode");re(s,this,e,t,r,n)}readFile(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");let n;if("function"==typeof r?n=r:"function"==typeof t&&(n=t,t=void 0),"string"==typeof t)t={encoding:t,flag:"r"};else if(t){if("object"!=typeof t)throw new TypeError("Bad arguments")}else t={encoding:null,flag:"r"};const s=t.encoding;if(s&&!Buffer.isEncoding(s))throw new Error(`Unknown encoding: ${s}`);let i,o,a,c,l=0,u=0;const h=t.flag||"r",f=()=>{0===i?(o=Buffer.allocUnsafe(8192),this.read(c,o,0,8192,u,p)):this.read(c,o,l,i-l,u,p)},p=(e,t)=>{let r;if(e){if(r=e.code===g.EOF,!r)return this.close(c,()=>n&&n(e))}else r=!1;if(r||0===i&&0===t)return _();u+=t,l+=t,0!==i?l===i?_():f():(a.push(d(o,0,t)),f())};p._wantEOFError=!0;const _=()=>{this.close(c,e=>(0===i?o=Buffer.concat(a,l):l<i&&(o=d(o,0,l)),s&&(o=o.toString(s)),n&&n(e,o)))};this.open(e,h,438,(t,r)=>{if(t)return n&&n(t);c=r;const s=(t,r)=>{if(t)this.stat(e,(e,r)=>{if(e)return this.close(c,()=>{n&&n(t)});s(null,r)});else{if(i=r.size||0,0===i)return a=[],f();o=Buffer.allocUnsafe(i),f()}};this.fstat(c,s)})}writeFile(e,t,r,n){if(this.server)throw new Error("Client-only method called in server mode");let s;if("function"==typeof n?s=n:"function"==typeof r&&(s=r,r=void 0),"string"==typeof r)r={encoding:r,mode:438,flag:"w"};else if(r){if("object"!=typeof r)throw new TypeError("Bad arguments")}else r={encoding:"utf8",mode:438,flag:"w"};if(r.encoding&&!Buffer.isEncoding(r.encoding))throw new Error(`Unknown encoding: ${r.encoding}`);const i=r.flag||"w";this.open(e,i,r.mode,(n,o)=>{if(n)s&&s(n);else{const n=Buffer.isBuffer(t)?t:Buffer.from(""+t,r.encoding||"utf8"),a=/a/.test(i)?null:0;if(null===a){const t=(r,i)=>{r?this.stat(e,(e,n)=>{if(e)return this.close(o,()=>{s&&s(r)});t(null,n)}):ne(this,o,n,0,n.length,i.size,s)};return void this.fstat(o,t)}ne(this,o,n,0,n.length,a,s)}})}appendFile(e,t,r,n){if(this.server)throw new Error("Client-only method called in server mode");let s;if("function"==typeof n?s=n:"function"==typeof r&&(s=r,r=void 0),"string"==typeof r)r={encoding:r,mode:438,flag:"a"};else if(r){if("object"!=typeof r)throw new TypeError("Bad arguments")}else r={encoding:"utf8",mode:438,flag:"a"};r.flag||(r=Object.assign({flag:"a"},r)),this.writeFile(e,t,r,s)}exists(e,t){if(this.server)throw new Error("Client-only method called in server mode");this.stat(e,e=>{t&&t(!e)})}unlink(e,t){if(this.server)throw new Error("Client-only method called in server mode");const r=Buffer.byteLength(e);let n=9;const s=Buffer.allocUnsafe(13+r);p(s,s.length-4,0),s[4]=13;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,r,n),s.utf8Write(e,n+=4,r),this._requests[i]={cb:t};const o=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} REMOVE`)}rename(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");const n=Buffer.byteLength(e),s=Buffer.byteLength(t);let i=9;const o=Buffer.allocUnsafe(13+n+4+s);p(o,o.length-4,0),o[4]=18;const a=this._writeReqid=this._writeReqid+1&K;p(o,a,5),p(o,n,i),o.utf8Write(e,i+=4,n),p(o,s,i+=n),o.utf8Write(t,i+=4,s),this._requests[a]={cb:r};const c=de(this,o);this._debug&&this._debug(`SFTP: Outbound: ${c?"Buffered":"Sending"} RENAME`)}mkdir(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");let n=0,s=0;"function"==typeof t&&(r=t,t=void 0),"object"==typeof t&&null!==t&&(n=(t=ie(t)).flags,s=t.nb);const i=Buffer.byteLength(e);let o=9;const a=Buffer.allocUnsafe(13+i+4+s);p(a,a.length-4,0),a[4]=14;const c=this._writeReqid=this._writeReqid+1&K;p(a,c,5),p(a,i,o),a.utf8Write(e,o+=4,i),p(a,n,o+=i),s&&(o+=4,s===_.length?a.set(_,o):h(_,a,0,s,o),o+=s),this._requests[c]={cb:r};const l=de(this,a);this._debug&&this._debug(`SFTP: Outbound: ${l?"Buffered":"Sending"} MKDIR`)}rmdir(e,t){if(this.server)throw new Error("Client-only method called in server mode");const r=Buffer.byteLength(e);let n=9;const s=Buffer.allocUnsafe(13+r);p(s,s.length-4,0),s[4]=15;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,r,n),s.utf8Write(e,n+=4,r),this._requests[i]={cb:t};const o=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} RMDIR`)}readdir(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");"function"==typeof t&&(r=t,t={}),"object"==typeof t&&null!==t||(t={});const n=!t||!t.full;if(!Buffer.isBuffer(e)&&"string"!=typeof e)throw new Error("missing directory handle or path");if("string"==typeof e){const n=[];let s=0;const i=(e,o)=>{if(e)return r(e);this.readdir(o,t,(e,t)=>{const a=e&&e.code===g.EOF;if(e&&!a)return this.close(o,()=>r(e));if(a)return this.close(o,e=>{if(e)return r(e);r(void 0,n)});for(let e=0;e<t.length;++e,++s)n[s]=t[e];i(void 0,o)})};return this.opendir(e,i)}const s=e.length;let i=9;const o=Buffer.allocUnsafe(13+s);p(o,o.length-4,0),o[4]=12;const a=this._writeReqid=this._writeReqid+1&K;p(o,a,5),p(o,s,i),o.set(e,i+=4),this._requests[a]={cb:n?(e,t)=>{if("function"==typeof r){if(e)return r(e);for(let e=t.length-1;e>=0;--e)"."!==t[e].filename&&".."!==t[e].filename||t.splice(e,1);r(void 0,t)}}:r};const c=de(this,o);this._debug&&this._debug(`SFTP: Outbound: ${c?"Buffered":"Sending"} READDIR`)}fstat(e,t){if(this.server)throw new Error("Client-only method called in server mode");if(!Buffer.isBuffer(e))throw new Error("handle is not a Buffer");const r=e.length;let n=9;const s=Buffer.allocUnsafe(13+r);p(s,s.length-4,0),s[4]=8;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,r,n),s.set(e,n+=4),this._requests[i]={cb:t};const o=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} FSTAT`)}stat(e,t){if(this.server)throw new Error("Client-only method called in server mode");const r=Buffer.byteLength(e);let n=9;const s=Buffer.allocUnsafe(13+r);p(s,s.length-4,0),s[4]=17;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,r,n),s.utf8Write(e,n+=4,r),this._requests[i]={cb:t};const o=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} STAT`)}lstat(e,t){if(this.server)throw new Error("Client-only method called in server mode");const r=Buffer.byteLength(e);let n=9;const s=Buffer.allocUnsafe(13+r);p(s,s.length-4,0),s[4]=7;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,r,n),s.utf8Write(e,n+=4,r),this._requests[i]={cb:t};const o=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} LSTAT`)}opendir(e,t){if(this.server)throw new Error("Client-only method called in server mode");const r=Buffer.byteLength(e);let n=9;const s=Buffer.allocUnsafe(13+r);p(s,s.length-4,0),s[4]=11;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,r,n),s.utf8Write(e,n+=4,r),this._requests[i]={cb:t};const o=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} OPENDIR`)}setstat(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");let n=0,s=0;"object"==typeof t&&null!==t?(n=(t=ie(t)).flags,s=t.nb):"function"==typeof t&&(r=t);const i=Buffer.byteLength(e);let o=9;const a=Buffer.allocUnsafe(13+i+4+s);p(a,a.length-4,0),a[4]=9;const c=this._writeReqid=this._writeReqid+1&K;p(a,c,5),p(a,i,o),a.utf8Write(e,o+=4,i),p(a,n,o+=i),s&&(o+=4,s===_.length?a.set(_,o):h(_,a,0,s,o),o+=s),this._requests[c]={cb:r};const l=de(this,a);this._debug&&this._debug(`SFTP: Outbound: ${l?"Buffered":"Sending"} SETSTAT`)}fsetstat(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");if(!Buffer.isBuffer(e))throw new Error("handle is not a Buffer");let n=0,s=0;"object"==typeof t&&null!==t?(n=(t=ie(t)).flags,s=t.nb):"function"==typeof t&&(r=t);const i=e.length;let o=9;const a=Buffer.allocUnsafe(13+i+4+s);p(a,a.length-4,0),a[4]=10;const c=this._writeReqid=this._writeReqid+1&K;p(a,c,5),p(a,i,o),a.set(e,o+=4),p(a,n,o+=i),s&&(o+=4,s===_.length?a.set(_,o):h(_,a,0,s,o),o+=s),this._requests[c]={cb:r};const l=de(this,a);this._debug&&this._debug(`SFTP: Outbound: ${l?"Buffered":"Sending"} FSETSTAT`)}futimes(e,t,r,n){return this.fsetstat(e,{atime:oe(t),mtime:oe(r)},n)}utimes(e,t,r,n){return this.setstat(e,{atime:oe(t),mtime:oe(r)},n)}fchown(e,t,r,n){return this.fsetstat(e,{uid:t,gid:r},n)}chown(e,t,r,n){return this.setstat(e,{uid:t,gid:r},n)}fchmod(e,t,r){return this.fsetstat(e,{mode:t},r)}chmod(e,t,r){return this.setstat(e,{mode:t},r)}readlink(e,t){if(this.server)throw new Error("Client-only method called in server mode");const r=Buffer.byteLength(e);let n=9;const s=Buffer.allocUnsafe(13+r);p(s,s.length-4,0),s[4]=19;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,r,n),s.utf8Write(e,n+=4,r),this._requests[i]={cb:(e,r)=>{if("function"==typeof t)return e?t(e):r&&r.length?void t(void 0,r[0].filename):t(new Error("Response missing link info"))}};const o=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} READLINK`)}symlink(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");const n=Buffer.byteLength(t),s=Buffer.byteLength(e);let i=9;const o=Buffer.allocUnsafe(13+n+4+s);p(o,o.length-4,0),o[4]=20;const a=this._writeReqid=this._writeReqid+1&K;p(o,a,5),this._isOpenSSH?(p(o,s,i),o.utf8Write(e,i+=4,s),p(o,n,i+=s),o.utf8Write(t,i+=4,n)):(p(o,n,i),o.utf8Write(t,i+=4,n),p(o,s,i+=n),o.utf8Write(e,i+=4,s)),this._requests[a]={cb:r};const c=de(this,o);this._debug&&this._debug(`SFTP: Outbound: ${c?"Buffered":"Sending"} SYMLINK`)}realpath(e,t){if(this.server)throw new Error("Client-only method called in server mode");const r=Buffer.byteLength(e);let n=9;const s=Buffer.allocUnsafe(13+r);p(s,s.length-4,0),s[4]=16;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,r,n),s.utf8Write(e,n+=4,r),this._requests[i]={cb:(e,r)=>{if("function"==typeof t)return e?t(e):r&&r.length?void t(void 0,r[0].filename):t(new Error("Response missing path info"))}};const o=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} REALPATH`)}ext_openssh_rename(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");const n=this._extensions["posix-rename@openssh.com"];if(!n||"1"!==n)throw new Error("Server does not support this extended request");const s=Buffer.byteLength(e),i=Buffer.byteLength(t);let o=9;const a=Buffer.allocUnsafe(41+s+4+i);p(a,a.length-4,0),a[4]=U;const c=this._writeReqid=this._writeReqid+1&K;p(a,c,5),p(a,24,o),a.utf8Write("posix-rename@openssh.com",o+=4,24),p(a,s,o+=24),a.utf8Write(e,o+=4,s),p(a,i,o+=s),a.utf8Write(t,o+=4,i),this._requests[c]={cb:r};const l=de(this,a);if(this._debug){const e=l?"Buffered":"Sending";this._debug(`SFTP: Outbound: ${e} posix-rename@openssh.com`)}}ext_openssh_statvfs(e,t){if(this.server)throw new Error("Client-only method called in server mode");const r=this._extensions["statvfs@openssh.com"];if(!r||"2"!==r)throw new Error("Server does not support this extended request");const n=Buffer.byteLength(e);let s=9;const i=Buffer.allocUnsafe(36+n);p(i,i.length-4,0),i[4]=U;const o=this._writeReqid=this._writeReqid+1&K;p(i,o,5),p(i,19,s),i.utf8Write("statvfs@openssh.com",s+=4,19),p(i,n,s+=19),i.utf8Write(e,s+=4,n),this._requests[o]={extended:"statvfs@openssh.com",cb:t};const a=de(this,i);if(this._debug){const e=a?"Buffered":"Sending";this._debug(`SFTP: Outbound: ${e} statvfs@openssh.com`)}}ext_openssh_fstatvfs(e,t){if(this.server)throw new Error("Client-only method called in server mode");const r=this._extensions["fstatvfs@openssh.com"];if(!r||"2"!==r)throw new Error("Server does not support this extended request");if(!Buffer.isBuffer(e))throw new Error("handle is not a Buffer");const n=e.length;let s=9;const i=Buffer.allocUnsafe(37+n);p(i,i.length-4,0),i[4]=U;const o=this._writeReqid=this._writeReqid+1&K;p(i,o,5),p(i,20,s),i.utf8Write("fstatvfs@openssh.com",s+=4,20),p(i,n,s+=20),i.set(e,s+=4),this._requests[o]={extended:"fstatvfs@openssh.com",cb:t};const a=de(this,i);if(this._debug){const e=a?"Buffered":"Sending";this._debug(`SFTP: Outbound: ${e} fstatvfs@openssh.com`)}}ext_openssh_hardlink(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");if("1"!==this._extensions["hardlink@openssh.com"])throw new Error("Server does not support this extended request");const n=Buffer.byteLength(e),s=Buffer.byteLength(t);let i=9;const o=Buffer.allocUnsafe(37+n+4+s);p(o,o.length-4,0),o[4]=U;const a=this._writeReqid=this._writeReqid+1&K;p(o,a,5),p(o,20,i),o.utf8Write("hardlink@openssh.com",i+=4,20),p(o,n,i+=20),o.utf8Write(e,i+=4,n),p(o,s,i+=n),o.utf8Write(t,i+=4,s),this._requests[a]={cb:r};const c=de(this,o);if(this._debug){const e=c?"Buffered":"Sending";this._debug(`SFTP: Outbound: ${e} hardlink@openssh.com`)}}ext_openssh_fsync(e,t){if(this.server)throw new Error("Client-only method called in server mode");if("1"!==this._extensions["fsync@openssh.com"])throw new Error("Server does not support this extended request");if(!Buffer.isBuffer(e))throw new Error("handle is not a Buffer");const r=e.length;let n=9;const s=Buffer.allocUnsafe(34+r);p(s,s.length-4,0),s[4]=U;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,17,n),s.utf8Write("fsync@openssh.com",n+=4,17),p(s,r,n+=17),s.set(e,n+=4),this._requests[i]={cb:t};const o=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} fsync@openssh.com`)}ext_openssh_lsetstat(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");if("1"!==this._extensions["lsetstat@openssh.com"])throw new Error("Server does not support this extended request");let n=0,s=0;"object"==typeof t&&null!==t?(n=(t=ie(t)).flags,s=t.nb):"function"==typeof t&&(r=t);const i=Buffer.byteLength(e);let o=9;const a=Buffer.allocUnsafe(37+i+4+s);p(a,a.length-4,0),a[4]=U;const c=this._writeReqid=this._writeReqid+1&K;p(a,c,5),p(a,20,o),a.utf8Write("lsetstat@openssh.com",o+=4,20),p(a,i,o+=20),a.utf8Write(e,o+=4,i),p(a,n,o+=i),s&&(o+=4,s===_.length?a.set(_,o):h(_,a,0,s,o),o+=s),this._requests[c]={cb:r};const l=de(this,a);if(this._debug){const e=l?"Buffered":"Sending";this._debug(`SFTP: Outbound: ${e} lsetstat@openssh.com`)}}ext_openssh_expandPath(e,t){if(this.server)throw new Error("Client-only method called in server mode");if("1"!==this._extensions["expand-path@openssh.com"])throw new Error("Server does not support this extended request");const r=Buffer.byteLength(e);let n=9;const s=Buffer.allocUnsafe(40+r);p(s,s.length-4,0),s[4]=U;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,5),p(s,23,n),s.utf8Write("expand-path@openssh.com",n+=4,23),p(s,r,n+=20),s.utf8Write(e,n+=4,r),this._requests[i]={cb:(e,r)=>{if("function"==typeof t)return e?t(e):r&&r.length?void t(void 0,r[0].filename):t(new Error("Response missing expanded path"))}};const o=de(this,s);if(this._debug){const e=o?"Buffered":"Sending";this._debug(`SFTP: Outbound: ${e} expand-path@openssh.com`)}}ext_copy_data(e,t,r,n,s,i){if(this.server)throw new Error("Client-only method called in server mode");if("1"!==this._extensions["copy-data"])throw new Error("Server does not support this extended request");if(!Buffer.isBuffer(e))throw new Error("Source handle is not a Buffer");if(!Buffer.isBuffer(n))throw new Error("Destination handle is not a Buffer");let o=0;const a=Buffer.allocUnsafe(26+e.length+8+8+4+n.length+8);p(a,a.length-4,o),o+=4,a[o]=U,++o;const c=this._writeReqid=this._writeReqid+1&K;p(a,c,o),o+=4,p(a,9,o),o+=4,a.utf8Write("copy-data",o,9),o+=9,p(a,e.length,o),o+=4,a.set(e,o),o+=e.length;for(let e=7;e>=0;--e)a[o+e]=255&t,t/=256;o+=8;for(let e=7;e>=0;--e)a[o+e]=255&r,r/=256;o+=8,p(a,n.length,o),o+=4,a.set(n,o),o+=n.length;for(let e=7;e>=0;--e)a[o+e]=255&s,s/=256;this._requests[c]={cb:i};const l=de(this,a);if(this._debug){const e=l?"Buffered":"Sending";this._debug(`SFTP: Outbound: ${e} copy-data`)}}ext_home_dir(e,t){if(this.server)throw new Error("Client-only method called in server mode");if("1"!==this._extensions["home-directory"])throw new Error("Server does not support this extended request");if("string"!=typeof e)throw new TypeError("username is not a string");let r=0;const n=Buffer.byteLength(e),s=Buffer.allocUnsafe(31+n);p(s,s.length-4,r),r+=4,s[r]=U,++r;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,r),r+=4,p(s,14,r),r+=4,s.utf8Write("home-directory",r,14),r+=14,p(s,n,r),r+=4,s.utf8Write(e,r,n),r+=n,this._requests[i]={cb:(e,r)=>{if("function"==typeof t)return e?t(e):r&&r.length?void t(void 0,r[0].filename):t(new Error("Response missing home directory"))}};const o=de(this,s);if(this._debug){const e=o?"Buffered":"Sending";this._debug(`SFTP: Outbound: ${e} home-directory`)}}ext_users_groups(e,t,r){if(this.server)throw new Error("Client-only method called in server mode");if("1"!==this._extensions["users-groups-by-id@openssh.com"])throw new Error("Server does not support this extended request");if(!Array.isArray(e))throw new TypeError("uids is not an array");for(const t of e)if(!Number.isInteger(t)||t<0||t>2**32-1)throw new Error("uid values must all be 32-bit unsigned integers");if(!Array.isArray(t))throw new TypeError("gids is not an array");for(const e of t)if(!Number.isInteger(e)||e<0||e>2**32-1)throw new Error("gid values must all be 32-bit unsigned integers");let n=0;const s=Buffer.allocUnsafe(47+4*e.length+4+4*t.length);p(s,s.length-4,n),n+=4,s[n]=U,++n;const i=this._writeReqid=this._writeReqid+1&K;p(s,i,n),n+=4,p(s,30,n),n+=4,s.utf8Write("users-groups-by-id@openssh.com",n,30),n+=30,p(s,4*e.length,n),n+=4;for(const t of e)p(s,t,n),n+=4;p(s,4*t.length,n),n+=4;for(const e of t)p(s,e,n),n+=4;this._requests[i]={extended:"users-groups-by-id@openssh.com",cb:r};const o=de(this,s);if(this._debug){const e=o?"Buffered":"Sending";this._debug(`SFTP: Outbound: ${e} users-groups-by-id@openssh.com`)}}handle(e,t){if(!this.server)throw new Error("Server-only method called in client mode");if(!Buffer.isBuffer(t))throw new Error("handle is not a Buffer");const r=t.length;if(r>256)throw new Error("handle too large (> 256 bytes)");let n=9;const s=Buffer.allocUnsafe(13+r);p(s,s.length-4,0),s[4]=102,p(s,e,5),p(s,r,n),r&&s.set(t,n+=4);const i=de(this,s);this._debug&&this._debug(`SFTP: Outbound: ${i?"Buffered":"Sending"} HANDLE`)}status(e,t,r){if(!this.server)throw new Error("Server-only method called in client mode");if(!m.has(t))throw new Error(`Bad status code: ${t}`);r||(r="");const n=Buffer.byteLength(r);let s=9;const i=Buffer.allocUnsafe(17+n+4);p(i,i.length-4,0),i[4]=101,p(i,e,5),p(i,t,s),p(i,n,s+=4),s+=4,n&&(i.utf8Write(r,s,n),s+=n),p(i,0,s);const o=de(this,i);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} STATUS`)}data(e,t,r){if(!this.server)throw new Error("Server-only method called in client mode");const n=Buffer.isBuffer(t);if(!n&&"string"!=typeof t)throw new Error("data is not a Buffer or string");let s;n||r||(r=void 0,s=!0);const i=n?t.length:Buffer.byteLength(t,r);let o=9;const a=Buffer.allocUnsafe(13+i);p(a,a.length-4,0),a[4]=103,p(a,e,5),p(a,i,o),i&&(n?a.set(t,o+=4):s?a.utf8Write(t,o+=4,i):a.write(t,o+=4,i,r));const c=de(this,a);this._debug&&this._debug(`SFTP: Outbound: ${c?"Buffered":"Sending"} DATA`)}name(e,t){if(!this.server)throw new Error("Server-only method called in client mode");if(!Array.isArray(t)){if("object"!=typeof t||null===t)throw new Error("names is not an object or array");t=[t]}const r=t.length;let n,s=0;const i=[];for(let e=0;e<r;++e){const r=t[e],o=r&&r.filename&&"string"==typeof r.filename?r.filename:"";s+=4+Buffer.byteLength(o);const a=r&&r.longname&&"string"==typeof r.longname?r.longname:"";if(s+=4+Buffer.byteLength(a),"object"==typeof r.attrs&&null!==r.attrs){if(n=ie(r.attrs),s+=4+n.nb,n.nb){let e;n.nb===_.length?e=new Uint8Array(_):(e=new Uint8Array(n.nb),h(_,e,0,n.nb,0)),n.bytes=e}i.push(n)}else s+=4,i.push(null)}let o=9;const a=Buffer.allocUnsafe(13+s);p(a,a.length-4,0),a[4]=104,p(a,e,5),p(a,r,o),o+=4;for(let e=0;e<r;++e){const r=t[e];{const e=r&&r.filename&&"string"==typeof r.filename?r.filename:"",t=Buffer.byteLength(e);p(a,t,o),o+=4,t&&(a.utf8Write(e,o,t),o+=t)}{const e=r&&r.longname&&"string"==typeof r.longname?r.longname:"",t=Buffer.byteLength(e);p(a,t,o),o+=4,t&&(a.utf8Write(e,o,t),o+=t)}const n=i[e];n?(p(a,n.flags,o),o+=4,n.flags&&n.bytes&&(a.set(n.bytes,o),o+=n.nb)):(p(a,0,o),o+=4)}const c=de(this,a);this._debug&&this._debug(`SFTP: Outbound: ${c?"Buffered":"Sending"} NAME`)}attrs(e,t){if(!this.server)throw new Error("Server-only method called in client mode");if("object"!=typeof t||null===t)throw new Error("attrs is not an object");const r=(t=ie(t)).flags,n=t.nb;let s=9;const i=Buffer.allocUnsafe(13+n);p(i,i.length-4,0),i[4]=105,p(i,e,5),p(i,r,s),n&&(s+=4,n===_.length?i.set(_,s):h(_,i,0,n,s),s+=n);const o=de(this,i);this._debug&&this._debug(`SFTP: Outbound: ${o?"Buffered":"Sending"} ATTRS`)}},STATUS_CODE:g,stringToFlags:le}},4963(e,t,r){"use strict";const n=r(6982);let s;try{s=r(2659)()}catch{}const{bindingAvailable:i,CIPHER_INFO:o,MAC_INFO:a}=r(2597),c=(()=>{if("function"==typeof n.sign&&"function"==typeof n.verify){const e="-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----",t=Buffer.from("a");let r,s;try{r=n.sign(null,t,e),s=n.verify(null,t,e,r)}catch{}return Buffer.isBuffer(r)&&64===r.length&&!0===s}return!1})(),l="function"==typeof n.diffieHellman&&"function"==typeof n.generateKeyPairSync&&"function"==typeof n.createPublicKey,u=["ecdh-sha2-nistp256","ecdh-sha2-nistp384","ecdh-sha2-nistp521","diffie-hellman-group-exchange-sha256","diffie-hellman-group14-sha256","diffie-hellman-group15-sha512","diffie-hellman-group16-sha512","diffie-hellman-group17-sha512","diffie-hellman-group18-sha512"];l&&(u.unshift("curve25519-sha256"),u.unshift("curve25519-sha256@libssh.org"));const h=u.concat(["diffie-hellman-group-exchange-sha1","diffie-hellman-group14-sha1","diffie-hellman-group1-sha1"]),d=["ecdsa-sha2-nistp256","ecdsa-sha2-nistp384","ecdsa-sha2-nistp521","rsa-sha2-512","rsa-sha2-256","ssh-rsa"];c&&d.unshift("ssh-ed25519");const f=d.concat(["ssh-dss"]),p=(()=>{const e=n.getCiphers();return t=>e.includes(o[t].sslName)})();let _=["aes128-gcm@openssh.com","aes256-gcm@openssh.com","aes128-ctr","aes192-ctr","aes256-ctr"];s&&s.flags&&!s.flags.aes?i?_.unshift("chacha20-poly1305@openssh.com"):_.push("chacha20-poly1305@openssh.com"):i&&s&&"x86"===s.arch?_.splice(4,0,"chacha20-poly1305@openssh.com"):_.push("chacha20-poly1305@openssh.com"),_=_.filter(p);const g=_.concat(["aes256-cbc","aes192-cbc","aes128-cbc","blowfish-cbc","3des-cbc","aes128-gcm","aes256-gcm","arcfour256","arcfour128","cast128-cbc","arcfour"].filter(p)),m=(()=>{const e=n.getHashes();return t=>e.includes(a[t].sslName)})(),y=["hmac-sha2-256-etm@openssh.com","hmac-sha2-512-etm@openssh.com","hmac-sha1-etm@openssh.com","hmac-sha2-256","hmac-sha2-512","hmac-sha1"].filter(m),A=y.concat(["hmac-md5","hmac-sha2-256-96","hmac-sha2-512-96","hmac-ripemd160","hmac-sha1-96","hmac-md5-96"].filter(m)),v=["none","zlib@openssh.com","zlib"],b=v.concat([]),w={BAD_DHGEX:1,OLD_EXIT:2,DYN_RPORT_BUG:4,BUG_DHGEX_LARGE:8,IMPLY_RSA_SHA2_SIGALGS:16};e.exports={MESSAGE:{DISCONNECT:1,IGNORE:2,UNIMPLEMENTED:3,DEBUG:4,SERVICE_REQUEST:5,SERVICE_ACCEPT:6,EXT_INFO:7,KEXINIT:20,NEWKEYS:21,KEXDH_INIT:30,KEXDH_REPLY:31,KEXDH_GEX_GROUP:31,KEXDH_GEX_INIT:32,KEXDH_GEX_REPLY:33,KEXDH_GEX_REQUEST:34,KEXECDH_INIT:30,KEXECDH_REPLY:31,USERAUTH_REQUEST:50,USERAUTH_FAILURE:51,USERAUTH_SUCCESS:52,USERAUTH_BANNER:53,USERAUTH_PASSWD_CHANGEREQ:60,USERAUTH_PK_OK:60,USERAUTH_INFO_REQUEST:60,USERAUTH_INFO_RESPONSE:61,GLOBAL_REQUEST:80,REQUEST_SUCCESS:81,REQUEST_FAILURE:82,CHANNEL_OPEN:90,CHANNEL_OPEN_CONFIRMATION:91,CHANNEL_OPEN_FAILURE:92,CHANNEL_WINDOW_ADJUST:93,CHANNEL_DATA:94,CHANNEL_EXTENDED_DATA:95,CHANNEL_EOF:96,CHANNEL_CLOSE:97,CHANNEL_REQUEST:98,CHANNEL_SUCCESS:99,CHANNEL_FAILURE:100},DISCONNECT_REASON:{HOST_NOT_ALLOWED_TO_CONNECT:1,PROTOCOL_ERROR:2,KEY_EXCHANGE_FAILED:3,RESERVED:4,MAC_ERROR:5,COMPRESSION_ERROR:6,SERVICE_NOT_AVAILABLE:7,PROTOCOL_VERSION_NOT_SUPPORTED:8,HOST_KEY_NOT_VERIFIABLE:9,CONNECTION_LOST:10,BY_APPLICATION:11,TOO_MANY_CONNECTIONS:12,AUTH_CANCELED_BY_USER:13,NO_MORE_AUTH_METHODS_AVAILABLE:14,ILLEGAL_USER_NAME:15},DISCONNECT_REASON_STR:void 0,CHANNEL_OPEN_FAILURE:{ADMINISTRATIVELY_PROHIBITED:1,CONNECT_FAILED:2,UNKNOWN_CHANNEL_TYPE:3,RESOURCE_SHORTAGE:4},TERMINAL_MODE:{TTY_OP_END:0,VINTR:1,VQUIT:2,VERASE:3,VKILL:4,VEOF:5,VEOL:6,VEOL2:7,VSTART:8,VSTOP:9,VSUSP:10,VDSUSP:11,VREPRINT:12,VWERASE:13,VLNEXT:14,VFLUSH:15,VSWTCH:16,VSTATUS:17,VDISCARD:18,IGNPAR:30,PARMRK:31,INPCK:32,ISTRIP:33,INLCR:34,IGNCR:35,ICRNL:36,IUCLC:37,IXON:38,IXANY:39,IXOFF:40,IMAXBEL:41,ISIG:50,ICANON:51,XCASE:52,ECHO:53,ECHOE:54,ECHOK:55,ECHONL:56,NOFLSH:57,TOSTOP:58,IEXTEN:59,ECHOCTL:60,ECHOKE:61,PENDIN:62,OPOST:70,OLCUC:71,ONLCR:72,OCRNL:73,ONOCR:74,ONLRET:75,CS7:90,CS8:91,PARENB:92,PARODD:93,TTY_OP_ISPEED:128,TTY_OP_OSPEED:129},CHANNEL_EXTENDED_DATATYPE:{STDERR:1},SIGNALS:["ABRT","ALRM","FPE","HUP","ILL","INT","QUIT","SEGV","TERM","USR1","USR2","KILL","PIPE"].reduce((e,t)=>({...e,[t]:1}),{}),COMPAT:w,COMPAT_CHECKS:[["Cisco-1.25",w.BAD_DHGEX],[/^Cisco-1[.]/,w.BUG_DHGEX_LARGE],[/^[0-9.]+$/,w.OLD_EXIT],[/^OpenSSH_5[.][0-9]+/,w.DYN_RPORT_BUG],[/^OpenSSH_7[.]4/,w.IMPLY_RSA_SHA2_SIGALGS]],DEFAULT_KEX:u,SUPPORTED_KEX:h,DEFAULT_SERVER_HOST_KEY:d,SUPPORTED_SERVER_HOST_KEY:f,DEFAULT_CIPHER:_,SUPPORTED_CIPHER:g,DEFAULT_MAC:y,SUPPORTED_MAC:A,DEFAULT_COMPRESSION:v,SUPPORTED_COMPRESSION:b,curve25519Supported:l,eddsaSupported:c},e.exports.DISCONNECT_REASON_BY_VALUE=Array.from(Object.entries(e.exports.DISCONNECT_REASON)).reduce((e,[t,r])=>({...e,[r]:t}),{})},2597(e,t,r){"use strict";const{createCipheriv:n,createDecipheriv:s,createHmac:i,randomFillSync:o,timingSafeEqual:a}=r(6982),{readUInt32BE:c,writeUInt32BE:l}=r(4787),u=Buffer[Symbol.species],h=2**32-1,d=Buffer.alloc(0),f=Buffer.alloc(4),p=new Map,_=35e3;let g,m,y,A,v,b,w;try{g=r(8701),({AESGCMCipher:m,ChaChaPolyCipher:y,GenericCipher:A,AESGCMDecipher:v,ChaChaPolyDecipher:b,GenericDecipher:w}=g)}catch{}const E=(()=>{function e(e,t,r,n,s,i,o){return{sslName:e,blockLen:t,keyLen:r,ivLen:0!==n||1&o?n:t,authLen:s,discardLen:i,stream:!!(1&o)}}return{"chacha20-poly1305@openssh.com":e("chacha20",8,64,0,16,0,1),"aes128-gcm":e("aes-128-gcm",16,16,12,16,0,1),"aes256-gcm":e("aes-256-gcm",16,32,12,16,0,1),"aes128-gcm@openssh.com":e("aes-128-gcm",16,16,12,16,0,1),"aes256-gcm@openssh.com":e("aes-256-gcm",16,32,12,16,0,1),"aes128-cbc":e("aes-128-cbc",16,16,0,0,0,0),"aes192-cbc":e("aes-192-cbc",16,24,0,0,0,0),"aes256-cbc":e("aes-256-cbc",16,32,0,0,0,0),"rijndael-cbc@lysator.liu.se":e("aes-256-cbc",16,32,0,0,0,0),"3des-cbc":e("des-ede3-cbc",8,24,0,0,0,0),"blowfish-cbc":e("bf-cbc",8,16,0,0,0,0),"idea-cbc":e("idea-cbc",8,16,0,0,0,0),"cast128-cbc":e("cast-cbc",8,16,0,0,0,0),"aes128-ctr":e("aes-128-ctr",16,16,16,0,0,1),"aes192-ctr":e("aes-192-ctr",16,24,16,0,0,1),"aes256-ctr":e("aes-256-ctr",16,32,16,0,0,1),"3des-ctr":e("des-ede3",8,24,8,0,0,1),"blowfish-ctr":e("bf-ecb",8,16,8,0,0,1),"cast128-ctr":e("cast5-ecb",8,16,8,0,0,1),arcfour:e("rc4",8,16,0,0,1536,1),arcfour128:e("rc4",8,16,0,0,1536,1),arcfour256:e("rc4",8,32,0,0,1536,1),arcfour512:e("rc4",8,64,0,0,1536,1)}})(),I=(()=>{function e(e,t,r,n){return{sslName:e,len:t,actualLen:r,isETM:n}}return{"hmac-md5":e("md5",16,16,!1),"hmac-md5-96":e("md5",16,12,!1),"hmac-ripemd160":e("ripemd160",20,20,!1),"hmac-sha1":e("sha1",20,20,!1),"hmac-sha1-etm@openssh.com":e("sha1",20,20,!0),"hmac-sha1-96":e("sha1",20,12,!1),"hmac-sha2-256":e("sha256",32,32,!1),"hmac-sha2-256-etm@openssh.com":e("sha256",32,32,!0),"hmac-sha2-256-96":e("sha256",32,12,!1),"hmac-sha2-512":e("sha512",64,64,!1),"hmac-sha2-512-etm@openssh.com":e("sha512",64,64,!0),"hmac-sha2-512-96":e("sha512",64,12,!1)}})(),S=Buffer.alloc(32),P=Buffer.alloc(16);let k,O,C;class R{constructor(e){const t=e.outbound;this.outSeqno=t.seqno,this._onWrite=t.onWrite,this._encKeyMain=t.cipherKey.slice(0,32),this._encKeyPktLen=t.cipherKey.slice(32),this._dead=!1}free(){this._dead=!0}allocPacket(e){let t=5+e,r=8-(t-4&7);r<4&&(r+=8),t+=r;const n=Buffer.allocUnsafe(t);return l(n,t-4,0),n[4]=r,o(n,5+e,r),n}encrypt(e){if(this._dead)return;P[0]=0,l(P,this.outSeqno,12);const t=n("chacha20",this._encKeyMain,P).update(S),r=n("chacha20",this._encKeyPktLen,P).update(e.slice(0,4));this._onWrite(r),P[0]=1;const s=n("chacha20",this._encKeyMain,P).update(e.slice(4));this._onWrite(s),C(O,r,r.length,s,s.length,t);const i=Buffer.allocUnsafe(16);i.set(new Uint8Array(k.HEAPU8.buffer,O,16),0),this._onWrite(i),this.outSeqno=this.outSeqno+1>>>0}}class B{constructor(e){const t=e.outbound;this.outSeqno=t.seqno,this._onWrite=t.onWrite,this._instance=new y(t.cipherKey),this._dead=!1}free(){this._dead=!0,this._instance.free()}allocPacket(e){let t=5+e,r=8-(t-4&7);r<4&&(r+=8),t+=r;const n=Buffer.allocUnsafe(t+16);return l(n,t-4,0),n[4]=r,o(n,5+e,r),n}encrypt(e){this._dead||(this._instance.encrypt(e,this.outSeqno),this._onWrite(e),this.outSeqno=this.outSeqno+1>>>0)}}class x{constructor(e){const t=e.outbound;this.outSeqno=t.seqno,this._onWrite=t.onWrite,this._encSSLName=t.cipherInfo.sslName,this._encKey=t.cipherKey,this._encIV=t.cipherIV,this._dead=!1}free(){this._dead=!0}allocPacket(e){let t=5+e,r=16-(t-4&15);r<4&&(r+=16),t+=r;const n=Buffer.allocUnsafe(t);return l(n,t-4,0),n[4]=r,o(n,5+e,r),n}encrypt(e){if(this._dead)return;const t=n(this._encSSLName,this._encKey,this._encIV);t.setAutoPadding(!1);const r=e.slice(0,4);t.setAAD(r),this._onWrite(r);const s=t.update(e.slice(4));this._onWrite(s);const i=t.final();i.length&&this._onWrite(i);const o=t.getAuthTag();this._onWrite(o),H(this._encIV),this.outSeqno=this.outSeqno+1>>>0}}class T{constructor(e){const t=e.outbound;this.outSeqno=t.seqno,this._onWrite=t.onWrite,this._instance=new m(t.cipherInfo.sslName,t.cipherKey,t.cipherIV),this._dead=!1}free(){this._dead=!0,this._instance.free()}allocPacket(e){let t=5+e,r=16-(t-4&15);r<4&&(r+=16),t+=r;const n=Buffer.allocUnsafe(t+16);return l(n,t-4,0),n[4]=r,o(n,5+e,r),n}encrypt(e){this._dead||(this._instance.encrypt(e),this._onWrite(e),this.outSeqno=this.outSeqno+1>>>0)}}class N{constructor(e){const t=e.outbound;this.outSeqno=t.seqno,this._onWrite=t.onWrite,this._encBlockLen=t.cipherInfo.blockLen,this._cipherInstance=n(t.cipherInfo.sslName,t.cipherKey,t.cipherIV),this._macSSLName=t.macInfo.sslName,this._macKey=t.macKey,this._macActualLen=t.macInfo.actualLen,this._macETM=t.macInfo.isETM,this._aadLen=this._macETM?4:0,this._dead=!1;const r=t.cipherInfo.discardLen;if(r){let e=p.get(r);void 0===e&&(e=Buffer.alloc(r),p.set(r,e)),this._cipherInstance.update(e)}}free(){this._dead=!0}allocPacket(e){const t=this._encBlockLen;let r=5+e,n=t-(r-this._aadLen&t-1);n<4&&(n+=t),r+=n;const s=Buffer.allocUnsafe(r);return l(s,r-4,0),s[4]=n,o(s,5+e,n),s}encrypt(e){if(this._dead)return;let t;if(this._macETM){const r=new Uint8Array(e.buffer,e.byteOffset,4),n=this._cipherInstance.update(new Uint8Array(e.buffer,e.byteOffset+4,e.length-4));this._onWrite(r),this._onWrite(n),t=i(this._macSSLName,this._macKey),l(f,this.outSeqno,0),t.update(f),t.update(r),t.update(n)}else{const r=this._cipherInstance.update(e);this._onWrite(r),t=i(this._macSSLName,this._macKey),l(f,this.outSeqno,0),t.update(f),t.update(e)}let r=t.digest();r.length>this._macActualLen&&(r=r.slice(0,this._macActualLen)),this._onWrite(r),this.outSeqno=this.outSeqno+1>>>0}}class F{constructor(e){const t=e.outbound;this.outSeqno=t.seqno,this._onWrite=t.onWrite,this._encBlockLen=t.cipherInfo.blockLen,this._macLen=t.macInfo.len,this._macActualLen=t.macInfo.actualLen,this._aadLen=t.macInfo.isETM?4:0,this._instance=new A(t.cipherInfo.sslName,t.cipherKey,t.cipherIV,t.macInfo.sslName,t.macKey,t.macInfo.isETM),this._dead=!1}free(){this._dead=!0,this._instance.free()}allocPacket(e){const t=this._encBlockLen;let r=5+e,n=t-(r-this._aadLen&t-1);n<4&&(n+=t),r+=n;const s=Buffer.allocUnsafe(r+this._macLen);return l(s,r-4,0),s[4]=n,o(s,5+e,n),s}encrypt(e){this._dead||(this._instance.encrypt(e,this.outSeqno),this._macActualLen<this._macLen&&(e=new u(e.buffer,e.byteOffset,e.length-(this._macLen-this._macActualLen))),this._onWrite(e),this.outSeqno=this.outSeqno+1>>>0)}}class M{constructor(e){const t=e.inbound;this.inSeqno=t.seqno,this._onPayload=t.onPayload,this._decKeyMain=t.decipherKey.slice(0,32),this._decKeyPktLen=t.decipherKey.slice(32),this._len=0,this._lenBuf=Buffer.alloc(4),this._lenPos=0,this._packet=null,this._pktLen=0,this._mac=Buffer.allocUnsafe(16),this._calcMac=Buffer.allocUnsafe(16),this._macPos=0}free(){}decrypt(e,t,r){for(;t<r;){if(this._lenPos<4){let n=Math.min(4-this._lenPos,r-t);for(;n--;)this._lenBuf[this._lenPos++]=e[t++];if(this._lenPos<4)return;P[0]=0,l(P,this.inSeqno,12);const i=s("chacha20",this._decKeyPktLen,P).update(this._lenBuf);if(this._len=c(i,0),this._len>_||this._len<8||7&this._len)throw new Error("Bad packet length")}if(this._pktLen<this._len){if(t>=r)return;const n=Math.min(this._len-this._pktLen,r-t);let s;if(s=0!==t||n!==r?new Uint8Array(e.buffer,e.byteOffset+t,n):e,n===this._len?this._packet=s:(this._packet||(this._packet=Buffer.allocUnsafe(this._len)),this._packet.set(s,this._pktLen)),t+=n,this._pktLen+=n,this._pktLen<this._len||t>=r)return}{const n=Math.min(16-this._macPos,r-t);if(0!==t||n!==r?this._mac.set(new Uint8Array(e.buffer,e.byteOffset+t,n),this._macPos):this._mac.set(e,this._macPos),t+=n,this._macPos+=n,this._macPos<16)return}P[0]=0,l(P,this.inSeqno,12);const i=n("chacha20",this._decKeyMain,P).update(S);if(C(O,this._lenBuf,4,this._packet,this._packet.length,i),this._calcMac.set(new Uint8Array(k.HEAPU8.buffer,O,16),0),!a(this._calcMac,this._mac))throw new Error("Invalid MAC");P[0]=1;const o=s("chacha20",this._decKeyMain,P).update(this._packet),h=new u(o.buffer,o.byteOffset+1,o.length-o[0]-1);this.inSeqno=this.inSeqno+1>>>0,this._len=0,this._lenPos=0,this._packet=null,this._pktLen=0,this._macPos=0;{const e=this._onPayload(h);if(void 0!==e)return!1===e?t:e}}}}class L{constructor(e){const t=e.inbound;this.inSeqno=t.seqno,this._onPayload=t.onPayload,this._instance=new b(t.decipherKey),this._len=0,this._lenBuf=Buffer.alloc(4),this._lenPos=0,this._packet=null,this._pktLen=0,this._mac=Buffer.allocUnsafe(16),this._macPos=0}free(){this._instance.free()}decrypt(e,t,r){for(;t<r;){if(this._lenPos<4){let n=Math.min(4-this._lenPos,r-t);for(;n--;)this._lenBuf[this._lenPos++]=e[t++];if(this._lenPos<4)return;if(this._len=this._instance.decryptLen(this._lenBuf,this.inSeqno),this._len>_||this._len<8||7&this._len)throw new Error("Bad packet length");if(t>=r)return}if(this._pktLen<this._len){const n=Math.min(this._len-this._pktLen,r-t);let s;if(s=0!==t||n!==r?new Uint8Array(e.buffer,e.byteOffset+t,n):e,n===this._len?this._packet=s:(this._packet||(this._packet=Buffer.allocUnsafe(this._len)),this._packet.set(s,this._pktLen)),t+=n,this._pktLen+=n,this._pktLen<this._len||t>=r)return}{const n=Math.min(16-this._macPos,r-t);if(0!==t||n!==r?this._mac.set(new Uint8Array(e.buffer,e.byteOffset+t,n),this._macPos):this._mac.set(e,this._macPos),t+=n,this._macPos+=n,this._macPos<16)return}this._instance.decrypt(this._packet,this._mac,this.inSeqno);const n=new u(this._packet.buffer,this._packet.byteOffset+1,this._packet.length-this._packet[0]-1);this.inSeqno=this.inSeqno+1>>>0,this._len=0,this._lenPos=0,this._packet=null,this._pktLen=0,this._macPos=0;{const e=this._onPayload(n);if(void 0!==e)return!1===e?t:e}}}}class U{constructor(e){const t=e.inbound;this.inSeqno=t.seqno,this._onPayload=t.onPayload,this._decipherInstance=null,this._decipherSSLName=t.decipherInfo.sslName,this._decipherKey=t.decipherKey,this._decipherIV=t.decipherIV,this._len=0,this._lenBytes=0,this._packet=null,this._packetPos=0,this._pktLen=0,this._tag=Buffer.allocUnsafe(16),this._tagPos=0}free(){}decrypt(e,t,r){for(;t<r;){if(this._lenBytes<4){let n=Math.min(4-this._lenBytes,r-t);for(this._lenBytes+=n;n--;)this._len=(this._len<<8)+e[t++];if(this._lenBytes<4)return;if(this._len+20>_||this._len<16||15&this._len)throw new Error("Bad packet length");this._decipherInstance=s(this._decipherSSLName,this._decipherKey,this._decipherIV),this._decipherInstance.setAutoPadding(!1),this._decipherInstance.setAAD(G(this._len))}if(this._pktLen<this._len){if(t>=r)return;const n=Math.min(this._len-this._pktLen,r-t);let s;if(s=0!==t||n!==r?this._decipherInstance.update(new Uint8Array(e.buffer,e.byteOffset+t,n)):this._decipherInstance.update(e),s.length&&(n===this._len?this._packet=s:(this._packet||(this._packet=Buffer.allocUnsafe(this._len)),this._packet.set(s,this._packetPos)),this._packetPos+=s.length),t+=n,this._pktLen+=n,this._pktLen<this._len||t>=r)return}{const n=Math.min(16-this._tagPos,r-t);if(0!==t||n!==r?this._tag.set(new Uint8Array(e.buffer,e.byteOffset+t,n),this._tagPos):this._tag.set(e,this._tagPos),t+=n,this._tagPos+=n,this._tagPos<16)return}{this._decipherInstance.setAuthTag(this._tag);const e=this._decipherInstance.final();e.length&&(this._packet?this._packet.set(e,this._packetPos):this._packet=e)}const n=this._packet?new u(this._packet.buffer,this._packet.byteOffset+1,this._packet.length-this._packet[0]-1):d;this.inSeqno=this.inSeqno+1>>>0,H(this._decipherIV),this._len=0,this._lenBytes=0,this._packet=null,this._packetPos=0,this._pktLen=0,this._tagPos=0;{const e=this._onPayload(n);if(void 0!==e)return!1===e?t:e}}}}class D{constructor(e){const t=e.inbound;this.inSeqno=t.seqno,this._onPayload=t.onPayload,this._instance=new v(t.decipherInfo.sslName,t.decipherKey,t.decipherIV),this._len=0,this._lenBytes=0,this._packet=null,this._pktLen=0,this._tag=Buffer.allocUnsafe(16),this._tagPos=0}free(){}decrypt(e,t,r){for(;t<r;){if(this._lenBytes<4){let n=Math.min(4-this._lenBytes,r-t);for(this._lenBytes+=n;n--;)this._len=(this._len<<8)+e[t++];if(this._lenBytes<4)return;if(this._len+20>_||this._len<16||15&this._len)throw new Error(`Bad packet length: ${this._len}`)}if(this._pktLen<this._len){if(t>=r)return;const n=Math.min(this._len-this._pktLen,r-t);let s;if(s=0!==t||n!==r?new Uint8Array(e.buffer,e.byteOffset+t,n):e,n===this._len?this._packet=s:(this._packet||(this._packet=Buffer.allocUnsafe(this._len)),this._packet.set(s,this._pktLen)),t+=n,this._pktLen+=n,this._pktLen<this._len||t>=r)return}{const n=Math.min(16-this._tagPos,r-t);if(0!==t||n!==r?this._tag.set(new Uint8Array(e.buffer,e.byteOffset+t,n),this._tagPos):this._tag.set(e,this._tagPos),t+=n,this._tagPos+=n,this._tagPos<16)return}this._instance.decrypt(this._packet,this._len,this._tag);const n=new u(this._packet.buffer,this._packet.byteOffset+1,this._packet.length-this._packet[0]-1);this.inSeqno=this.inSeqno+1>>>0,this._len=0,this._lenBytes=0,this._packet=null,this._pktLen=0,this._tagPos=0;{const e=this._onPayload(n);if(void 0!==e)return!1===e?t:e}}}}class ${constructor(e){const t=e.inbound;this.inSeqno=t.seqno,this._onPayload=t.onPayload,this._decipherInstance=s(t.decipherInfo.sslName,t.decipherKey,t.decipherIV),this._decipherInstance.setAutoPadding(!1),this._block=Buffer.allocUnsafe(t.macInfo.isETM?4:t.decipherInfo.blockLen),this._blockSize=t.decipherInfo.blockLen,this._blockPos=0,this._len=0,this._packet=null,this._packetPos=0,this._pktLen=0,this._mac=Buffer.allocUnsafe(t.macInfo.actualLen),this._macPos=0,this._macSSLName=t.macInfo.sslName,this._macKey=t.macKey,this._macActualLen=t.macInfo.actualLen,this._macETM=t.macInfo.isETM,this._macInstance=null;const r=t.decipherInfo.discardLen;if(r){let e=p.get(r);void 0===e&&(e=Buffer.alloc(r),p.set(r,e)),this._decipherInstance.update(e)}}free(){}decrypt(e,t,r){for(;t<r;){if(this._blockPos<this._block.length){const n=Math.min(this._block.length-this._blockPos,r-t);if(0!==t||n!==r||n<e.length?this._block.set(new Uint8Array(e.buffer,e.byteOffset+t,n),this._blockPos):this._block.set(e,this._blockPos),t+=n,this._blockPos+=n,this._blockPos<this._block.length)return;let s,o;if(this._macETM?this._len=o=c(this._block,0):(s=this._decipherInstance.update(this._block),this._len=c(s,0),o=4+this._len-this._blockSize),this._len>_||this._len<5||o&this._blockSize-1)throw new Error("Bad packet length");if(this._macInstance=i(this._macSSLName,this._macKey),l(f,this.inSeqno,0),this._macInstance.update(f),this._macETM?this._macInstance.update(this._block):(this._macInstance.update(new Uint8Array(s.buffer,s.byteOffset,4)),this._pktLen=s.length-4,this._packetPos=this._pktLen,this._packet=Buffer.allocUnsafe(this._len),this._packet.set(new Uint8Array(s.buffer,s.byteOffset+4,this._packetPos),0)),t>=r)return}if(this._pktLen<this._len){const n=Math.min(this._len-this._pktLen,r-t);let s;s=0!==t||n!==r?new Uint8Array(e.buffer,e.byteOffset+t,n):e,this._macETM&&this._macInstance.update(s);const i=this._decipherInstance.update(s);if(i.length&&(n===this._len?this._packet=i:(this._packet||(this._packet=Buffer.allocUnsafe(this._len)),this._packet.set(i,this._packetPos)),this._packetPos+=i.length),t+=n,this._pktLen+=n,this._pktLen<this._len||t>=r)return}{const n=Math.min(this._macActualLen-this._macPos,r-t);if(0!==t||n!==r?this._mac.set(new Uint8Array(e.buffer,e.byteOffset+t,n),this._macPos):this._mac.set(e,this._macPos),t+=n,this._macPos+=n,this._macPos<this._macActualLen)return}this._macETM||this._macInstance.update(this._packet);let n=this._macInstance.digest();if(this._macActualLen<n.length&&(n=new Uint8Array(n.buffer,n.byteOffset,this._macActualLen)),!Q(n,this._mac))throw new Error("Invalid MAC");const s=new u(this._packet.buffer,this._packet.byteOffset+1,this._packet.length-this._packet[0]-1);this.inSeqno=this.inSeqno+1>>>0,this._blockPos=0,this._len=0,this._packet=null,this._packetPos=0,this._pktLen=0,this._macPos=0,this._macInstance=null;{const e=this._onPayload(s);if(void 0!==e)return!1===e?t:e}}}}class j{constructor(e){const t=e.inbound;this.inSeqno=t.seqno,this._onPayload=t.onPayload,this._instance=new w(t.decipherInfo.sslName,t.decipherKey,t.decipherIV,t.macInfo.sslName,t.macKey,t.macInfo.isETM,t.macInfo.actualLen),this._block=Buffer.allocUnsafe(t.macInfo.isETM||t.decipherInfo.stream?4:t.decipherInfo.blockLen),this._blockPos=0,this._len=0,this._packet=null,this._pktLen=0,this._mac=Buffer.allocUnsafe(t.macInfo.actualLen),this._macPos=0,this._macActualLen=t.macInfo.actualLen,this._macETM=t.macInfo.isETM}free(){this._instance.free()}decrypt(e,t,r){for(;t<r;){if(this._blockPos<this._block.length){const n=Math.min(this._block.length-this._blockPos,r-t);if(0!==t||n!==r||n<e.length?this._block.set(new Uint8Array(e.buffer,e.byteOffset+t,n),this._blockPos):this._block.set(e,this._blockPos),t+=n,this._blockPos+=n,this._blockPos<this._block.length)return;let s;if(this._macETM?this._len=s=c(this._block,0):(this._instance.decryptBlock(this._block),this._len=c(this._block,0),s=4+this._len-this._block.length),this._len>_||this._len<5||s&this._block.length-1)throw new Error("Bad packet length");if(this._macETM||(this._pktLen=this._block.length-4,this._pktLen&&(this._packet=Buffer.allocUnsafe(this._len),this._packet.set(new Uint8Array(this._block.buffer,this._block.byteOffset+4,this._pktLen),0))),t>=r)return}if(this._pktLen<this._len){const n=Math.min(this._len-this._pktLen,r-t);let s;if(s=0!==t||n!==r?new Uint8Array(e.buffer,e.byteOffset+t,n):e,n===this._len?this._packet=s:(this._packet||(this._packet=Buffer.allocUnsafe(this._len)),this._packet.set(s,this._pktLen)),t+=n,this._pktLen+=n,this._pktLen<this._len||t>=r)return}{const n=Math.min(this._macActualLen-this._macPos,r-t);if(0!==t||n!==r?this._mac.set(new Uint8Array(e.buffer,e.byteOffset+t,n),this._macPos):this._mac.set(e,this._macPos),t+=n,this._macPos+=n,this._macPos<this._macActualLen)return}this._instance.decrypt(this._packet,this.inSeqno,this._block,this._mac);const n=new u(this._packet.buffer,this._packet.byteOffset+1,this._packet.length-this._packet[0]-1);this.inSeqno=this.inSeqno+1>>>0,this._blockPos=0,this._len=0,this._packet=null,this._pktLen=0,this._macPos=0,this._macInstance=null;{const e=this._onPayload(n);if(void 0!==e)return!1===e?t:e}}}}function H(e){++e[11]>>>8&&++e[10]>>>8&&++e[9]>>>8&&++e[8]>>>8&&++e[7]>>>8&&++e[6]>>>8&&++e[5]>>>8&&++e[4]}const G=(()=>{const e=Buffer.alloc(4);return t=>(e[0]=t>>>24,e[1]=t>>>16,e[2]=t>>>8,e[3]=t,e)})();function Q(e,t){return e.length!==t.length?(a(e,e),!1):a(e,t)}e.exports={CIPHER_INFO:E,MAC_INFO:I,bindingAvailable:!!g,init:new Promise(async(e,t)=>{try{k=await r(8465)(),O=k._malloc(16),C=k.cwrap("poly1305_auth",null,["number","array","number","array","number","array"])}catch(e){return t(e)}e()}),NullCipher:class{constructor(e,t){this.outSeqno=e,this._onWrite=t,this._dead=!1}free(){this._dead=!0}allocPacket(e){let t=5+e,r=8-(7&t);r<4&&(r+=8),t+=r;const n=Buffer.allocUnsafe(t);return l(n,t-4,0),n[4]=r,o(n,5+e,r),n}encrypt(e){this._dead||(this._onWrite(e),this.outSeqno=this.outSeqno+1>>>0)}},createCipher:function(e){if("object"!=typeof e||null===e)throw new Error("Invalid config");if("object"!=typeof e.outbound||null===e.outbound)throw new Error("Invalid outbound");const t=e.outbound;if("function"!=typeof t.onWrite)throw new Error("Invalid outbound.onWrite");if("object"!=typeof t.cipherInfo||null===t.cipherInfo)throw new Error("Invalid outbound.cipherInfo");if(!Buffer.isBuffer(t.cipherKey)||t.cipherKey.length!==t.cipherInfo.keyLen)throw new Error("Invalid outbound.cipherKey");if(t.cipherInfo.ivLen&&(!Buffer.isBuffer(t.cipherIV)||t.cipherIV.length!==t.cipherInfo.ivLen))throw new Error("Invalid outbound.cipherIV");if("number"!=typeof t.seqno||t.seqno<0||t.seqno>h)throw new Error("Invalid outbound.seqno");const r=!!t.forceNative;switch(t.cipherInfo.sslName){case"aes-128-gcm":case"aes-256-gcm":return m&&!r?new T(e):new x(e);case"chacha20":return y&&!r?new B(e):new R(e);default:if("object"!=typeof t.macInfo||null===t.macInfo)throw new Error("Invalid outbound.macInfo");if(!Buffer.isBuffer(t.macKey)||t.macKey.length!==t.macInfo.len)throw new Error("Invalid outbound.macKey");return A&&!r?new F(e):new N(e)}},NullDecipher:class{constructor(e,t){this.inSeqno=e,this._onPayload=t,this._len=0,this._lenBytes=0,this._packet=null,this._packetPos=0}free(){}decrypt(e,t,r){for(;t<r;){if(this._lenBytes<4){let n=Math.min(4-this._lenBytes,r-t);for(this._lenBytes+=n;n--;)this._len=(this._len<<8)+e[t++];if(this._lenBytes<4)return;if(this._len>_||this._len<8||4+this._len&7)throw new Error("Bad packet length");if(t>=r)return}if(this._packetPos<this._len){const n=Math.min(this._len-this._packetPos,r-t);let s;if(s=0!==t||n!==r?new Uint8Array(e.buffer,e.byteOffset+t,n):e,n===this._len?this._packet=s:(this._packet||(this._packet=Buffer.allocUnsafe(this._len)),this._packet.set(s,this._packetPos)),t+=n,this._packetPos+=n,this._packetPos<this._len)return}const n=this._packet?new u(this._packet.buffer,this._packet.byteOffset+1,this._packet.length-this._packet[0]-1):d;this.inSeqno=this.inSeqno+1>>>0,this._len=0,this._lenBytes=0,this._packet=null,this._packetPos=0;{const e=this._onPayload(n);if(void 0!==e)return!1===e?t:e}}}},createDecipher:function(e){if("object"!=typeof e||null===e)throw new Error("Invalid config");if("object"!=typeof e.inbound||null===e.inbound)throw new Error("Invalid inbound");const t=e.inbound;if("function"!=typeof t.onPayload)throw new Error("Invalid inbound.onPayload");if("object"!=typeof t.decipherInfo||null===t.decipherInfo)throw new Error("Invalid inbound.decipherInfo");if(!Buffer.isBuffer(t.decipherKey)||t.decipherKey.length!==t.decipherInfo.keyLen)throw new Error("Invalid inbound.decipherKey");if(t.decipherInfo.ivLen&&(!Buffer.isBuffer(t.decipherIV)||t.decipherIV.length!==t.decipherInfo.ivLen))throw new Error("Invalid inbound.decipherIV");if("number"!=typeof t.seqno||t.seqno<0||t.seqno>h)throw new Error("Invalid inbound.seqno");const r=!!t.forceNative;switch(t.decipherInfo.sslName){case"aes-128-gcm":case"aes-256-gcm":return v&&!r?new D(e):new U(e);case"chacha20":return b&&!r?new L(e):new M(e);default:if("object"!=typeof t.macInfo||null===t.macInfo)throw new Error("Invalid inbound.macInfo");if(!Buffer.isBuffer(t.macKey)||t.macKey.length!==t.macInfo.len)throw new Error("Invalid inbound.macKey");return w&&!r?new j(e):new $(e)}}}},8701(e,t,r){e.exports=require(r.ab+"lib/protocol/crypto/build/Release/sshcrypto.node")},8465(e,t,r){var n,s=(n="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,"undefined"!=typeof __filename&&(n=n||__filename),function(e){var t,s,i;e=e||{},t||(t=void 0!==e?e:{}),t.ready=new Promise(function(e,t){s=e,i=t});var o,a={};for(o in t)t.hasOwnProperty(o)&&(a[o]=t[o]);var c,l,u,h,d,f="object"==typeof window,p="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,g="";_?(g=p?r(6928).dirname(g)+"/":__dirname+"/",c=function(e,t){var n=Q(e);return n?t?n:n.toString():(h||(h=r(9896)),d||(d=r(6928)),e=d.normalize(e),h.readFileSync(e,t?null:"utf8"))},u=function(e){return(e=c(e,!0)).buffer||(e=new Uint8Array(e)),b(e.buffer),e},l=function(e,t,n){var s=Q(e);s&&t(s),h||(h=r(9896)),d||(d=r(6928)),e=d.normalize(e),h.readFile(e,function(e,r){e?n(e):t(r.buffer)})},1<process.argv.length&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),t.inspect=function(){return"[Emscripten Module object]"}):(f||p)&&(p?g=self.location.href:"undefined"!=typeof document&&document.currentScript&&(g=document.currentScript.src),n&&(g=n),g=0!==g.indexOf("blob:")?g.substr(0,g.lastIndexOf("/")+1):"",c=function(e){try{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText}catch(s){if(e=Q(e)){t=[];for(var r=0;r<e.length;r++){var n=e[r];255<n&&(H&&b(!1,"Character code "+n+" ("+String.fromCharCode(n)+") at offset "+r+" not in 0x00-0xFF."),n&=255),t.push(String.fromCharCode(n))}return t.join("")}throw s}},p&&(u=function(e){try{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}catch(t){if(e=Q(e))return e;throw t}}),l=function(e,t,r){var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=function(){if(200==n.status||0==n.status&&n.response)t(n.response);else{var s=Q(e);s?t(s.buffer):r()}},n.onerror=r,n.send(null)}),t.print||console.log.bind(console);var m,y=t.printErr||console.warn.bind(console);for(o in a)a.hasOwnProperty(o)&&(t[o]=a[o]);a=null,t.wasmBinary&&(m=t.wasmBinary),t.noExitRuntime,"object"!=typeof WebAssembly&&M("no native wasm support detected");var A,v=!1;function b(e,t){e||M("Assertion failed: "+t)}function w(e){var r=t["_"+e];return b(r,"Cannot call unknown function "+e+", make sure it is exported"),r}var E,I,S,P="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function k(){var e=A.buffer;E=e,t.HEAP8=I=new Int8Array(e),t.HEAP16=new Int16Array(e),t.HEAP32=new Int32Array(e),t.HEAPU8=S=new Uint8Array(e),t.HEAPU16=new Uint16Array(e),t.HEAPU32=new Uint32Array(e),t.HEAPF32=new Float32Array(e),t.HEAPF64=new Float64Array(e)}var O,C=[],R=[],B=[];function x(){var e=t.preRun.shift();C.unshift(e)}var T=0,N=null,F=null;function M(e){throw t.onAbort&&t.onAbort(e),y(e),v=!0,e=new WebAssembly.RuntimeError("abort("+e+"). Build with -s ASSERTIONS=1 for more info."),i(e),e}t.preloadedImages={},t.preloadedAudios={};var L,U="data:application/octet-stream;base64,";if(!(L="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==").startsWith(U)){var D=L;L=t.locateFile?t.locateFile(D,g):g+D}function $(){var e=L;try{if(e==L&&m)return new Uint8Array(m);var t=Q(e);if(t)return t;if(u)return u(e);throw"both async and sync fetching of the wasm failed"}catch(e){M(e)}}function j(e){for(;0<e.length;){var r=e.shift();if("function"==typeof r)r(t);else{var n=r.m;"number"==typeof n?void 0===r.l?O.get(n)():O.get(n)(r.l):n(void 0===r.l?null:r.l)}}}var H=!1,G="function"==typeof atob?atob:function(e){var t="",r=0;e=e.replace(/[^A-Za-z0-9\+\/=]/g,"");do{var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e.charAt(r++)),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e.charAt(r++)),i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e.charAt(r++)),o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e.charAt(r++));n=n<<2|s>>4,s=(15&s)<<4|i>>2;var a=(3&i)<<6|o;t+=String.fromCharCode(n),64!==i&&(t+=String.fromCharCode(s)),64!==o&&(t+=String.fromCharCode(a))}while(r<e.length);return t};function Q(e){if(e.startsWith(U)){if(e=e.slice(U.length),"boolean"==typeof _&&_){var t=Buffer.from(e,"base64");t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}else try{var r=G(e),n=new Uint8Array(r.length);for(e=0;e<r.length;++e)n[e]=r.charCodeAt(e);t=n}catch(e){throw Error("Converting base64 string to bytes failed.")}return t}}var q={a:function(e){var t=S.length;if(2147483648<(e>>>=0))return!1;for(var r=1;4>=r;r*=2){var n=t*(1+.2/r);n=Math.min(n,e+100663296),0<(n=Math.max(e,n))%65536&&(n+=65536-n%65536);e:{try{A.grow(Math.min(2147483648,n)-E.byteLength+65535>>>16),k();var s=1;break e}catch(e){}s=void 0}if(s)return!0}return!1}};!function(){function e(e){t.asm=e.exports,A=t.asm.b,k(),O=t.asm.j,R.unshift(t.asm.c),T--,t.monitorRunDependencies&&t.monitorRunDependencies(T),0==T&&(null!==N&&(clearInterval(N),N=null),F&&(e=F,F=null,e()))}function r(t){e(t.instance)}function n(e){return function(){if(!m&&(f||p)){if("function"==typeof fetch&&!L.startsWith("file://"))return fetch(L,{credentials:"same-origin"}).then(function(e){if(!e.ok)throw"failed to load wasm binary file at '"+L+"'";return e.arrayBuffer()}).catch(function(){return $()});if(l)return new Promise(function(e,t){l(L,function(t){e(new Uint8Array(t))},t)})}return Promise.resolve().then(function(){return $()})}().then(function(e){return WebAssembly.instantiate(e,s)}).then(e,function(e){y("failed to asynchronously prepare wasm: "+e),M(e)})}var s={a:q};if(T++,t.monitorRunDependencies&&t.monitorRunDependencies(T),t.instantiateWasm)try{return t.instantiateWasm(s,e)}catch(e){return y("Module.instantiateWasm callback failed with error: "+e),!1}(m||"function"!=typeof WebAssembly.instantiateStreaming||L.startsWith(U)||L.startsWith("file://")||"function"!=typeof fetch?n(r):fetch(L,{credentials:"same-origin"}).then(function(e){return WebAssembly.instantiateStreaming(e,s).then(r,function(e){return y("wasm streaming compile failed: "+e),y("falling back to ArrayBuffer instantiation"),n(r)})})).catch(i)}(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.c).apply(null,arguments)},t._poly1305_auth=function(){return(t._poly1305_auth=t.asm.d).apply(null,arguments)};var W,K=t.stackSave=function(){return(K=t.stackSave=t.asm.e).apply(null,arguments)},X=t.stackRestore=function(){return(X=t.stackRestore=t.asm.f).apply(null,arguments)},z=t.stackAlloc=function(){return(z=t.stackAlloc=t.asm.g).apply(null,arguments)};function Y(){function e(){if(!W&&(W=!0,t.calledRun=!0,!v)){if(j(R),s(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),t.postRun)for("function"==typeof t.postRun&&(t.postRun=[t.postRun]);t.postRun.length;){var e=t.postRun.shift();B.unshift(e)}j(B)}}if(!(0<T)){if(t.preRun)for("function"==typeof t.preRun&&(t.preRun=[t.preRun]);t.preRun.length;)x();j(C),0<T||(t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),e()},1)):e())}}if(t._malloc=function(){return(t._malloc=t.asm.h).apply(null,arguments)},t._free=function(){return(t._free=t.asm.i).apply(null,arguments)},t.cwrap=function(e,t,r,n){var s=(r=r||[]).every(function(e){return"number"===e});return"string"!==t&&s&&!n?w(e):function(){return function(e,t,r,n){var s={string:function(e){var t=0;if(null!=e&&0!==e){var r=1+(e.length<<2),n=t=z(r),s=S;if(0<r){r=n+r-1;for(var i=0;i<e.length;++i){var o=e.charCodeAt(i);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++i)),127>=o){if(n>=r)break;s[n++]=o}else{if(2047>=o){if(n+1>=r)break;s[n++]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;s[n++]=224|o>>12}else{if(n+3>=r)break;s[n++]=240|o>>18,s[n++]=128|o>>12&63}s[n++]=128|o>>6&63}s[n++]=128|63&o}}s[n]=0}}return t},array:function(e){var t=z(e.length);return I.set(e,t),t}},i=w(e),o=[];if(e=0,n)for(var a=0;a<n.length;a++){var c=s[r[a]];c?(0===e&&(e=K()),o[a]=c(n[a])):o[a]=n[a]}return r=function(e){if("string"===t)if(e){for(var r=S,n=e+NaN,s=e;r[s]&&!(s>=n);)++s;if(16<s-e&&r.subarray&&P)e=P.decode(r.subarray(e,s));else{for(n="";e<s;){var i=r[e++];if(128&i){var o=63&r[e++];if(192==(224&i))n+=String.fromCharCode((31&i)<<6|o);else{var a=63&r[e++];65536>(i=224==(240&i)?(15&i)<<12|o<<6|a:(7&i)<<18|o<<12|a<<6|63&r[e++])?n+=String.fromCharCode(i):(i-=65536,n+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else n+=String.fromCharCode(i)}e=n}}else e="";else e="boolean"===t?!!e:e;return e}(r=i.apply(null,o)),0!==e&&X(e),r}(e,t,r,arguments)}},F=function e(){W||Y(),W||(F=e)},t.run=Y,t.preInit)for("function"==typeof t.preInit&&(t.preInit=[t.preInit]);0<t.preInit.length;)t.preInit.pop()();return Y(),e.ready});e.exports=s},2917(e,t,r){"use strict";const n=new Array(256);[r(7198).G,r(8499)].forEach(e=>{for(let[t,r]of Object.entries(e))t=+t,isFinite(t)&&t>=0&&t<n.length&&(n[t]=r)}),e.exports=n},8499(e,t,r){"use strict";const{bufferSlice:n,bufferParser:s,doFatalError:i,sigSSHToASN1:o,writeUInt32BE:a}=r(4787),{CHANNEL_OPEN_FAILURE:c,COMPAT:l,MESSAGE:u,TERMINAL_MODE:h}=r(4963),{parseKey:d}=r(614),f=Array.from(Object.entries(h)).reduce((e,[t,r])=>({...e,[t]:r}),{});e.exports={[u.DISCONNECT]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE(),n=s.readString(!0),o=s.readString();if(s.clear(),void 0===o)return i(e,"Inbound: Malformed DISCONNECT packet");e._debug&&e._debug(`Inbound: Received DISCONNECT (${r}, "${n}")`);const a=e._handlers.DISCONNECT;a&&a(e,r,n)},[u.IGNORE]:(e,t)=>{e._debug&&e._debug("Inbound: Received IGNORE")},[u.UNIMPLEMENTED]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE();if(s.clear(),void 0===r)return i(e,"Inbound: Malformed UNIMPLEMENTED packet");e._debug&&e._debug(`Inbound: Received UNIMPLEMENTED (seqno ${r})`)},[u.DEBUG]:(e,t)=>{s.init(t,1);const r=s.readBool(),n=s.readString(!0),o=s.readString();if(s.clear(),void 0===o)return i(e,"Inbound: Malformed DEBUG packet");e._debug&&e._debug("Inbound: Received DEBUG");const a=e._handlers.DEBUG;a&&a(e,r,n)},[u.SERVICE_REQUEST]:(e,t)=>{s.init(t,1);const r=s.readString(!0);if(s.clear(),void 0===r)return i(e,"Inbound: Malformed SERVICE_REQUEST packet");e._debug&&e._debug(`Inbound: Received SERVICE_REQUEST (${r})`);const n=e._handlers.SERVICE_REQUEST;n&&n(e,r)},[u.SERVICE_ACCEPT]:(e,t)=>{s.init(t,1);const r=s.readString(!0);if(s.clear(),void 0===r)return i(e,"Inbound: Malformed SERVICE_ACCEPT packet");e._debug&&e._debug(`Inbound: Received SERVICE_ACCEPT (${r})`);const n=e._handlers.SERVICE_ACCEPT;n&&n(e,r)},[u.EXT_INFO]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE();let n;if(void 0!==r){n=[];for(let e=0;e<r;++e){const e=s.readString(!0),t=s.readString();if(void 0===t){n=void 0;break}if("server-sig-algs"===e){const r=t.latin1Slice(0,t.length).split(",");n.push({name:e,algs:r});continue}}}if(s.clear(),void 0===n)return i(e,"Inbound: Malformed EXT_INFO packet");e._debug&&e._debug("Inbound: Received EXT_INFO");const o=e._handlers.EXT_INFO;o&&o(e,n)},[u.USERAUTH_REQUEST]:(e,t)=>{s.init(t,1);const r=s.readString(!0),c=s.readString(!0),l=s.readString(!0);let u,h;switch(l){case"none":u=null;break;case"password":{const e=s.readBool();if(void 0!==e&&(u=s.readString(!0),void 0!==u&&e)){const e=s.readString(!0);u=void 0!==e?{oldPassword:u,newPassword:e}:void 0}break}case"publickey":{const r=s.readBool();if(void 0!==r){const i=s.readString(!0);let c=i;const l=s.readString();let d;switch(i){case"rsa-sha2-256":c="ssh-rsa",d="sha256";break;case"rsa-sha2-512":c="ssh-rsa",d="sha512"}if(r){const r=s.pos();let h=s.readString();if(void 0!==h&&(h.length>4+i.length+4&&h.utf8Slice(4,4+i.length)===i&&(h=n(h,4+i.length+4)),h=o(h,c),h)){const n=e._kex.sessionID,s=Buffer.allocUnsafe(4+n.length+r);a(s,n.length,0),s.set(n,4),s.set(new Uint8Array(t.buffer,t.byteOffset,r),4+n.length),u={keyAlgo:c,key:l,signature:h,blob:s,hashAlgo:d}}}else u={keyAlgo:c,key:l,hashAlgo:d},h="publickey -- check"}break}case"hostbased":{const r=s.readString(!0);let i=r;const c=s.readString(),l=s.readString(!0),h=s.readString(!0);let d;switch(r){case"rsa-sha2-256":i="ssh-rsa",d="sha256";break;case"rsa-sha2-512":i="ssh-rsa",d="sha512"}const f=s.pos();let p=s.readString();if(void 0!==p&&(p.length>4+r.length+4&&p.utf8Slice(4,4+r.length)===r&&(p=n(p,4+r.length+4)),p=o(p,i),void 0!==p)){const r=e._kex.sessionID,n=Buffer.allocUnsafe(4+r.length+f);a(n,r.length,0),n.set(r,4),n.set(new Uint8Array(t.buffer,t.byteOffset,f),4+r.length),u={keyAlgo:i,key:c,signature:p,blob:n,localHostname:l,localUsername:h,hashAlgo:d}}break}case"keyboard-interactive":s.skipString(),u=s.readList();break;default:void 0!==l&&(u=s.readRaw())}if(s.clear(),void 0===u)return i(e,"Inbound: Malformed USERAUTH_REQUEST packet");void 0===h&&(h=l),e._authsQueue.push(l),e._debug&&e._debug(`Inbound: Received USERAUTH_REQUEST (${h})`);const d=e._handlers.USERAUTH_REQUEST;d&&d(e,r,c,l,u)},[u.USERAUTH_FAILURE]:(e,t)=>{s.init(t,1);const r=s.readList(),n=s.readBool();if(s.clear(),void 0===n)return i(e,"Inbound: Malformed USERAUTH_FAILURE packet");e._debug&&e._debug(`Inbound: Received USERAUTH_FAILURE (${r})`),e._authsQueue.shift();const o=e._handlers.USERAUTH_FAILURE;o&&o(e,r,n)},[u.USERAUTH_SUCCESS]:(e,t)=>{e._debug&&e._debug("Inbound: Received USERAUTH_SUCCESS"),e._authsQueue.shift();const r=e._handlers.USERAUTH_SUCCESS;r&&r(e)},[u.USERAUTH_BANNER]:(e,t)=>{s.init(t,1);const r=s.readString(!0),n=s.readString();if(s.clear(),void 0===n)return i(e,"Inbound: Malformed USERAUTH_BANNER packet");e._debug&&e._debug("Inbound: Received USERAUTH_BANNER");const o=e._handlers.USERAUTH_BANNER;o&&o(e,r)},60:(e,t)=>{if(e._authsQueue.length)switch(e._authsQueue[0]){case"password":{s.init(t,1);const r=s.readString(!0),n=s.readString();if(s.clear(),void 0===n)return i(e,"Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet");e._debug&&e._debug("Inbound: Received USERAUTH_PASSWD_CHANGEREQ");const o=e._handlers.USERAUTH_PASSWD_CHANGEREQ;o&&o(e,r);break}case"publickey":{s.init(t,1);const r=s.readString(!0),n=s.readString();if(s.clear(),void 0===n)return i(e,"Inbound: Malformed USERAUTH_PK_OK packet");e._debug&&e._debug("Inbound: Received USERAUTH_PK_OK"),e._authsQueue.shift();const o=e._handlers.USERAUTH_PK_OK;o&&o(e,r,n);break}case"keyboard-interactive":{s.init(t,1);const r=s.readString(!0),n=s.readString(!0);s.readString();const o=s.readUInt32BE();let a;if(void 0!==o){let e;for(a=new Array(o),e=0;e<o;++e){const t=s.readString(!0),r=s.readBool();if(void 0===r)break;a[e]={prompt:t,echo:r}}e!==o&&(a=void 0)}if(s.clear(),void 0===a)return i(e,"Inbound: Malformed USERAUTH_INFO_REQUEST packet");e._debug&&e._debug("Inbound: Received USERAUTH_INFO_REQUEST");const c=e._handlers.USERAUTH_INFO_REQUEST;c&&c(e,r,n,a);break}default:e._debug&&e._debug("Inbound: Received unexpected payload type 60")}else e._debug&&e._debug("Inbound: Received payload type 60 without auth")},61:(e,t)=>{if(!e._authsQueue.length)return void(e._debug&&e._debug("Inbound: Received payload type 61 without auth"));if("keyboard-interactive"!==e._authsQueue[0])return i(e,"Inbound: Received unexpected payload type 61");s.init(t,1);const r=s.readUInt32BE();let n;if(void 0!==r){let e;for(n=new Array(r),e=0;e<r;++e){const t=s.readString(!0);if(void 0===t)break;n[e]=t}e!==r&&(n=void 0)}if(s.clear(),void 0===n)return i(e,"Inbound: Malformed USERAUTH_INFO_RESPONSE packet");e._debug&&e._debug("Inbound: Received USERAUTH_INFO_RESPONSE");const o=e._handlers.USERAUTH_INFO_RESPONSE;o&&o(e,n)},[u.GLOBAL_REQUEST]:(e,t)=>{s.init(t,1);const r=s.readString(!0),n=s.readBool();let o;if(void 0!==n)switch(r){case"tcpip-forward":case"cancel-tcpip-forward":{const e=s.readString(!0),t=s.readUInt32BE();void 0!==t&&(o={bindAddr:e,bindPort:t});break}case"streamlocal-forward@openssh.com":case"cancel-streamlocal-forward@openssh.com":{const e=s.readString(!0);void 0!==e&&(o={socketPath:e});break}case"no-more-sessions@openssh.com":o=null;break;case"hostkeys-00@openssh.com":for(o=[];s.avail()>0;){const e=s.readString();if(void 0===e){o=void 0;break}const t=d(e);t instanceof Error||o.push(t)}break;default:o=s.readRaw()}if(s.clear(),void 0===o)return i(e,"Inbound: Malformed GLOBAL_REQUEST packet");e._debug&&e._debug(`Inbound: GLOBAL_REQUEST (${r})`);const a=e._handlers.GLOBAL_REQUEST;a?a(e,r,n,o):e.requestFailure()},[u.REQUEST_SUCCESS]:(e,t)=>{const r=t.length>1?n(t,1):null;e._debug&&e._debug("Inbound: REQUEST_SUCCESS");const s=e._handlers.REQUEST_SUCCESS;s&&s(e,r)},[u.REQUEST_FAILURE]:(e,t)=>{e._debug&&e._debug("Inbound: Received REQUEST_FAILURE");const r=e._handlers.REQUEST_FAILURE;r&&r(e)},[u.CHANNEL_OPEN]:(e,t)=>{s.init(t,1);const r=s.readString(!0),n=s.readUInt32BE(),o=s.readUInt32BE(),a=s.readUInt32BE();let l;switch(r){case"forwarded-tcpip":case"direct-tcpip":{const e=s.readString(!0),t=s.readUInt32BE(),i=s.readString(!0),c=s.readUInt32BE();void 0!==c&&(l={type:r,sender:n,window:o,packetSize:a,data:{destIP:e,destPort:t,srcIP:i,srcPort:c}});break}case"forwarded-streamlocal@openssh.com":case"direct-streamlocal@openssh.com":{const e=s.readString(!0);void 0!==e&&(l={type:r,sender:n,window:o,packetSize:a,data:{socketPath:e}});break}case"x11":{const e=s.readString(!0),t=s.readUInt32BE();void 0!==t&&(l={type:r,sender:n,window:o,packetSize:a,data:{srcIP:e,srcPort:t}});break}default:l={type:r,sender:n,window:o,packetSize:a,data:{}}}if(s.clear(),void 0===l)return i(e,"Inbound: Malformed CHANNEL_OPEN packet");e._debug&&e._debug(`Inbound: CHANNEL_OPEN (s:${n}, ${r})`);const u=e._handlers.CHANNEL_OPEN;u?u(e,l):e.channelOpenFail(l.sender,c.ADMINISTRATIVELY_PROHIBITED,"","")},[u.CHANNEL_OPEN_CONFIRMATION]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE(),n=s.readUInt32BE(),o=s.readUInt32BE(),a=s.readUInt32BE(),c=s.avail()?s.readRaw():void 0;if(s.clear(),void 0===a)return i(e,"Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet");e._debug&&e._debug(`Inbound: CHANNEL_OPEN_CONFIRMATION (r:${r}, s:${n})`);const l=e._handlers.CHANNEL_OPEN_CONFIRMATION;l&&l(e,{recipient:r,sender:n,window:o,packetSize:a,data:c})},[u.CHANNEL_OPEN_FAILURE]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE(),n=s.readUInt32BE(),o=s.readString(!0),a=s.readString();if(s.clear(),void 0===a)return i(e,"Inbound: Malformed CHANNEL_OPEN_FAILURE packet");e._debug&&e._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${r})`);const c=e._handlers.CHANNEL_OPEN_FAILURE;c&&c(e,r,n,o)},[u.CHANNEL_WINDOW_ADJUST]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE(),n=s.readUInt32BE();if(s.clear(),void 0===n)return i(e,"Inbound: Malformed CHANNEL_WINDOW_ADJUST packet");e._debug&&e._debug(`Inbound: CHANNEL_WINDOW_ADJUST (r:${r}, ${n})`);const o=e._handlers.CHANNEL_WINDOW_ADJUST;o&&o(e,r,n)},[u.CHANNEL_DATA]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE(),n=s.readString();if(s.clear(),void 0===n)return i(e,"Inbound: Malformed CHANNEL_DATA packet");e._debug&&e._debug(`Inbound: CHANNEL_DATA (r:${r}, ${n.length})`);const o=e._handlers.CHANNEL_DATA;o&&o(e,r,n)},[u.CHANNEL_EXTENDED_DATA]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE(),n=s.readUInt32BE(),o=s.readString();if(s.clear(),void 0===o)return i(e,"Inbound: Malformed CHANNEL_EXTENDED_DATA packet");e._debug&&e._debug(`Inbound: CHANNEL_EXTENDED_DATA (r:${r}, ${o.length})`);const a=e._handlers.CHANNEL_EXTENDED_DATA;a&&a(e,r,o,n)},[u.CHANNEL_EOF]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE();if(s.clear(),void 0===r)return i(e,"Inbound: Malformed CHANNEL_EOF packet");e._debug&&e._debug(`Inbound: CHANNEL_EOF (r:${r})`);const n=e._handlers.CHANNEL_EOF;n&&n(e,r)},[u.CHANNEL_CLOSE]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE();if(s.clear(),void 0===r)return i(e,"Inbound: Malformed CHANNEL_CLOSE packet");e._debug&&e._debug(`Inbound: CHANNEL_CLOSE (r:${r})`);const n=e._handlers.CHANNEL_CLOSE;n&&n(e,r)},[u.CHANNEL_REQUEST]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE(),n=s.readString(!0),o=s.readBool();let a;if(void 0!==o)switch(n){case"exit-status":a=s.readUInt32BE(),e._debug&&e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${a})`);break;case"exit-signal":{let t,i;if(e._compatFlags&l.OLD_EXIT){const e=s.readUInt32BE();switch(e){case 1:t="HUP";break;case 2:t="INT";break;case 3:t="QUIT";break;case 6:t="ABRT";break;case 9:t="KILL";break;case 14:t="ALRM";break;case 15:t="TERM";break;default:void 0!==e&&(t=`UNKNOWN (${e})`)}i=!1}else t=s.readString(!0),i=s.readBool(),void 0===i&&(t=void 0);const o=s.readString(!0);void 0!==s.skipString()&&(a={signal:t,coreDumped:i,errorMessage:o}),e._debug&&e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${t})`);break}case"pty-req":{const t=s.readString(!0),i=s.readUInt32BE(),o=s.readUInt32BE(),c=s.readUInt32BE(),l=s.readUInt32BE(),u=s.readString();if(void 0!==u){s.init(u,1);let e={};for(;s.avail();){const t=s.readByte();if(t===h.TTY_OP_END)break;const r=f[t],n=s.readUInt32BE();if(void 0===t||void 0===r||void 0===n){e=void 0;break}e[r]=n}void 0!==e&&(a={term:t,cols:i,rows:o,width:c,height:l,modes:e})}e._debug&&e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`);break}case"window-change":{const t=s.readUInt32BE(),i=s.readUInt32BE(),o=s.readUInt32BE(),c=s.readUInt32BE();void 0!==c&&(a={cols:t,rows:i,width:o,height:c}),e._debug&&e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`);break}case"x11-req":{const t=s.readBool(),i=s.readString(!0),o=s.readString(),c=s.readUInt32BE();void 0!==c&&(a={single:t,protocol:i,cookie:o,screen:c}),e._debug&&e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`);break}case"env":{const t=s.readString(!0),i=s.readString(!0);void 0!==i&&(a={name:t,value:i}),e._debug&&e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${t}=${i})`);break}case"shell":case"auth-agent-req@openssh.com":a=null,e._debug&&e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`);break;case"exec":case"subsystem":case"signal":a=s.readString(!0),e._debug&&e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${a})`);break;case"xon-xoff":a=s.readBool(),e._debug&&e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${a})`);break;default:a=s.avail()?s.readRaw():null,e._debug&&e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`)}if(s.clear(),void 0===a)return i(e,"Inbound: Malformed CHANNEL_REQUEST packet");const c=e._handlers.CHANNEL_REQUEST;c&&c(e,r,n,o,a)},[u.CHANNEL_SUCCESS]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE();if(s.clear(),void 0===r)return i(e,"Inbound: Malformed CHANNEL_SUCCESS packet");e._debug&&e._debug(`Inbound: CHANNEL_SUCCESS (r:${r})`);const n=e._handlers.CHANNEL_SUCCESS;n&&n(e,r)},[u.CHANNEL_FAILURE]:(e,t)=>{s.init(t,1);const r=s.readUInt32BE();if(s.clear(),void 0===r)return i(e,"Inbound: Malformed CHANNEL_FAILURE packet");e._debug&&e._debug(`Inbound: CHANNEL_FAILURE (r:${r})`);const n=e._handlers.CHANNEL_FAILURE;n&&n(e,r)}}},7198(e,t,r){"use strict";const{createDiffieHellman:n,createDiffieHellmanGroup:s,createECDH:i,createHash:o,createPublicKey:a,diffieHellman:c,generateKeyPairSync:l,randomFillSync:u}=r(6982),{Ber:h}=r(5896),{COMPAT:d,curve25519Supported:f,DEFAULT_KEX:p,DEFAULT_SERVER_HOST_KEY:_,DEFAULT_CIPHER:g,DEFAULT_MAC:m,DEFAULT_COMPRESSION:y,DISCONNECT_REASON:A,MESSAGE:v}=r(4963),{CIPHER_INFO:b,createCipher:w,createDecipher:E,MAC_INFO:I}=r(2597),{parseDERKey:S}=r(614),{bufferFill:P,bufferParser:k,convertSignature:O,doFatalError:C,FastBuffer:R,sigSSHToASN1:B,writeUInt32BE:x}=r(4787),{PacketReader:T,PacketWriter:N,ZlibPacketReader:F,ZlibPacketWriter:M}=r(2797);let L;const U=Buffer.alloc(0);function D(e){let t;if(e._compatFlags&d.BAD_DHGEX){const r=e._offer.lists.kex;let n=r.array,s=!1;for(let e=0;e<n.length;++e)n[e].includes("group-exchange")&&(s||(s=!0,n=n.slice()),n.splice(e--,1));if(s){let s=17+e._offer.totalSize+1+4;const i=Buffer.from(n.join(","));s-=r.buffer.length-i.length;const o=e._offer.lists.all,a=new Uint8Array(o.buffer,o.byteOffset+4+r.buffer.length,o.length-(4+r.buffer.length));t=Buffer.allocUnsafe(s),x(t,i.length,17),t.set(i,21),t.set(a,21+i.length)}}void 0===t&&(t=Buffer.allocUnsafe(17+e._offer.totalSize+1+4),e._offer.copyAllTo(t,17)),e._debug&&e._debug("Outbound: Sending KEXINIT"),t[0]=v.KEXINIT,u(t,1,16),P(t,0,t.length-5),e._kexinit=t,e._packetRW.write.allocStart=0;{const r=e._packetRW.write.allocStartKEX,n=e._packetRW.write.alloc(t.length,!0);n.set(t,r),e._cipher.encrypt(e._packetRW.write.finalize(n,!0))}}function $(e,t){const r={kex:void 0,serverHostKey:void 0,cs:{cipher:void 0,mac:void 0,compress:void 0,lang:void 0},sc:{cipher:void 0,mac:void 0,compress:void 0,lang:void 0}};if(k.init(t,17),void 0===(r.kex=k.readList())||void 0===(r.serverHostKey=k.readList())||void 0===(r.cs.cipher=k.readList())||void 0===(r.sc.cipher=k.readList())||void 0===(r.cs.mac=k.readList())||void 0===(r.sc.mac=k.readList())||void 0===(r.cs.compress=k.readList())||void 0===(r.sc.compress=k.readList())||void 0===(r.cs.lang=k.readList())||void 0===(r.sc.lang=k.readList()))return k.clear(),C(e,"Received malformed KEXINIT","handshake",A.KEY_EXCHANGE_FAILED);const n=k.pos(),s=n<t.length&&1===t[n];k.clear();const i=e._offer,o=r;let a,c,l,u=i.lists.kex.array;if(e._compatFlags&d.BAD_DHGEX){let e=!1;for(let t=0;t<u.length;++t)-1!==u[t].indexOf("group-exchange")&&(e||(e=!0,u=u.slice()),u.splice(t--,1))}const h=e._debug;let f;if(h&&h("Inbound: Handshake in progress"),h&&h(`Handshake: (local) KEX method: ${u}`),h&&h(`Handshake: (remote) KEX method: ${o.kex}`),e._server?(c=u,a=o.kex,f=-1!==a.indexOf("ext-info-c")):(c=o.kex,a=u,f=-1!==c.indexOf("ext-info-s")),void 0===e._strictMode&&(e._server?e._strictMode=-1!==a.indexOf("kex-strict-c-v00@openssh.com"):e._strictMode=-1!==c.indexOf("kex-strict-s-v00@openssh.com"),e._strictMode&&(h&&h("Handshake: strict KEX mode enabled"),1!==e._decipher.inSeqno)))return h&&h("Handshake: KEXINIT not first packet in strict KEX mode"),C(e,"Handshake failed: KEXINIT not first packet in strict KEX mode","handshake",A.KEY_EXCHANGE_FAILED);for(l=0;l<a.length&&-1===c.indexOf(a[l]);++l);if(l===a.length)return h&&h("Handshake: no matching key exchange algorithm"),C(e,"Handshake failed: no matching key exchange algorithm","handshake",A.KEY_EXCHANGE_FAILED);r.kex=a[l],h&&h(`Handshake: KEX algorithm: ${a[l]}`),!s||o.kex.length&&a[l]===o.kex[0]||(e._skipNextInboundPacket=!0);const p=i.lists.serverHostKey.array;for(h&&h(`Handshake: (local) Host key format: ${p}`),h&&h(`Handshake: (remote) Host key format: ${o.serverHostKey}`),e._server?(c=p,a=o.serverHostKey):(c=o.serverHostKey,a=p),l=0;l<a.length&&-1===c.indexOf(a[l]);++l);if(l===a.length)return h&&h("Handshake: No matching host key format"),C(e,"Handshake failed: no matching host key format","handshake",A.KEY_EXCHANGE_FAILED);r.serverHostKey=a[l],h&&h(`Handshake: Host key format: ${a[l]}`);const _=i.lists.cs.cipher.array;for(h&&h(`Handshake: (local) C->S cipher: ${_}`),h&&h(`Handshake: (remote) C->S cipher: ${o.cs.cipher}`),e._server?(c=_,a=o.cs.cipher):(c=o.cs.cipher,a=_),l=0;l<a.length&&-1===c.indexOf(a[l]);++l);if(l===a.length)return h&&h("Handshake: No matching C->S cipher"),C(e,"Handshake failed: no matching C->S cipher","handshake",A.KEY_EXCHANGE_FAILED);r.cs.cipher=a[l],h&&h(`Handshake: C->S Cipher: ${a[l]}`);const g=i.lists.sc.cipher.array;for(h&&h(`Handshake: (local) S->C cipher: ${g}`),h&&h(`Handshake: (remote) S->C cipher: ${o.sc.cipher}`),e._server?(c=g,a=o.sc.cipher):(c=o.sc.cipher,a=g),l=0;l<a.length&&-1===c.indexOf(a[l]);++l);if(l===a.length)return h&&h("Handshake: No matching S->C cipher"),C(e,"Handshake failed: no matching S->C cipher","handshake",A.KEY_EXCHANGE_FAILED);r.sc.cipher=a[l],h&&h(`Handshake: S->C cipher: ${a[l]}`);const m=i.lists.cs.mac.array;if(h&&h(`Handshake: (local) C->S MAC: ${m}`),h&&h(`Handshake: (remote) C->S MAC: ${o.cs.mac}`),b[r.cs.cipher].authLen>0)r.cs.mac="",h&&h("Handshake: C->S MAC: <implicit>");else{for(e._server?(c=m,a=o.cs.mac):(c=o.cs.mac,a=m),l=0;l<a.length&&-1===c.indexOf(a[l]);++l);if(l===a.length)return h&&h("Handshake: No matching C->S MAC"),C(e,"Handshake failed: no matching C->S MAC","handshake",A.KEY_EXCHANGE_FAILED);r.cs.mac=a[l],h&&h(`Handshake: C->S MAC: ${a[l]}`)}const y=i.lists.sc.mac.array;if(h&&h(`Handshake: (local) S->C MAC: ${y}`),h&&h(`Handshake: (remote) S->C MAC: ${o.sc.mac}`),b[r.sc.cipher].authLen>0)r.sc.mac="",h&&h("Handshake: S->C MAC: <implicit>");else{for(e._server?(c=y,a=o.sc.mac):(c=o.sc.mac,a=y),l=0;l<a.length&&-1===c.indexOf(a[l]);++l);if(l===a.length)return h&&h("Handshake: No matching S->C MAC"),C(e,"Handshake failed: no matching S->C MAC","handshake",A.KEY_EXCHANGE_FAILED);r.sc.mac=a[l],h&&h(`Handshake: S->C MAC: ${a[l]}`)}const v=i.lists.cs.compress.array;for(h&&h(`Handshake: (local) C->S compression: ${v}`),h&&h(`Handshake: (remote) C->S compression: ${o.cs.compress}`),e._server?(c=v,a=o.cs.compress):(c=o.cs.compress,a=v),l=0;l<a.length&&-1===c.indexOf(a[l]);++l);if(l===a.length)return h&&h("Handshake: No matching C->S compression"),C(e,"Handshake failed: no matching C->S compression","handshake",A.KEY_EXCHANGE_FAILED);r.cs.compress=a[l],h&&h(`Handshake: C->S compression: ${a[l]}`);const w=i.lists.sc.compress.array;for(h&&h(`Handshake: (local) S->C compression: ${w}`),h&&h(`Handshake: (remote) S->C compression: ${o.sc.compress}`),e._server?(c=w,a=o.sc.compress):(c=o.sc.compress,a=w),l=0;l<a.length&&-1===c.indexOf(a[l]);++l);if(l===a.length)return h&&h("Handshake: No matching S->C compression"),C(e,"Handshake failed: no matching S->C compression","handshake",A.KEY_EXCHANGE_FAILED);r.sc.compress=a[l],h&&h(`Handshake: S->C compression: ${a[l]}`),r.cs.lang="",r.sc.lang="",e._kex&&(e._kexinit||D(e),e._decipher._onPayload=q.bind(e,{firstPacket:!1})),e._kex=j(r,e,t),e._kex.remoteExtInfoEnabled=f,e._kex.start()}const j=(()=>{function e(e){let t,r=0,n=e.length;for(;0===e[r];)++r,--n;return 128&e[r]?(t=Buffer.allocUnsafe(1+n),t[0]=0,e.copy(t,1,r),e=t):n!==e.length&&(t=Buffer.allocUnsafe(n),e.copy(t,0,r),e=t),e}class t{constructor(e,t,r){this._protocol=t,this.sessionID=t._kex?t._kex.sessionID:void 0,this.negotiated=e,this.remoteExtInfoEnabled=!1,this._step=1,this._public=null,this._dh=null,this._sentNEWKEYS=!1,this._receivedNEWKEYS=!1,this._finished=!1,this._hostVerified=!1,this._kexinit=t._kexinit,this._remoteKexinit=r,this._identRaw=t._identRaw,this._remoteIdentRaw=t._remoteIdentRaw,this._hostKey=void 0,this._dhData=void 0,this._sig=void 0}finish(e){if(this._finished)return!1;this._finished=!0;const t=this._protocol._server,r=this.negotiated,n=this.convertPublicKey(this._dhData);let s=this.computeSecret(this._dhData);if(s instanceof Error)return s.message=`Error while computing DH secret (${this.type}): ${s.message}`,s.level="handshake",C(this._protocol,s,A.KEY_EXCHANGE_FAILED);const i=o(this.hashName);G(i,t?this._remoteIdentRaw:this._identRaw),G(i,t?this._identRaw:this._remoteIdentRaw),G(i,t?this._remoteKexinit:this._kexinit),G(i,t?this._kexinit:this._remoteKexinit);const a=t?this._hostKey.getPublicSSH():this._hostKey;if(G(i,a),"groupex"===this.type){const e=this.getDHParams(),t=Buffer.allocUnsafe(4);x(t,this._minBits,0),i.update(t),x(t,this._prefBits,0),i.update(t),x(t,this._maxBits,0),i.update(t),G(i,e.prime),G(i,e.generator)}G(i,t?n:this.getPublicKey());const c=t?this.getPublicKey():n;G(i,c),G(i,s);const l=i.digest();if(t){let e;switch(this.negotiated.serverHostKey){case"rsa-sha2-256":e="sha256";break;case"rsa-sha2-512":e="sha512"}this._protocol._debug&&this._protocol._debug("Generating signature ...");let t=this._hostKey.sign(l,e);if(t instanceof Error)return C(this._protocol,`Handshake failed: signature generation failed for ${this._hostKey.type} host key: ${t.message}`,"handshake",A.KEY_EXCHANGE_FAILED);if(t=O(t,this._hostKey.type),!1===t)return C(this._protocol,`Handshake failed: signature conversion failed for ${this._hostKey.type} host key`,"handshake",A.KEY_EXCHANGE_FAILED);const r=this.negotiated.serverHostKey,n=Buffer.byteLength(r),s=4+n+4+t.length;let i=this._protocol._packetRW.write.allocStartKEX;const o=this._protocol._packetRW.write.alloc(5+a.length+4+c.length+4+s,!0);if(o[i]=v.KEXDH_REPLY,x(o,a.length,++i),o.set(a,i+=4),x(o,c.length,i+=a.length),o.set(c,i+=4),x(o,s,i+=c.length),x(o,n,i+=4),o.utf8Write(r,i+=4,n),x(o,t.length,i+=n),o.set(t,i+=4),this._protocol._debug){let e;switch(this.type){case"group":e="KEXDH_REPLY";break;case"groupex":e="KEXDH_GEX_REPLY";break;default:e="KEXECDH_REPLY"}this._protocol._debug(`Outbound: Sending ${e}`)}this._protocol._cipher.encrypt(this._protocol._packetRW.write.finalize(o,!0))}else{k.init(this._sig,0);const e=k.readString(!0);if(!e)return C(this._protocol,"Malformed packet while reading signature","handshake",A.KEY_EXCHANGE_FAILED);if(e!==r.serverHostKey)return C(this._protocol,`Wrong signature type: ${e}, expected: ${r.serverHostKey}`,"handshake",A.KEY_EXCHANGE_FAILED);let t,n,s=k.readString();if(k.clear(),void 0===s)return C(this._protocol,"Malformed packet while reading signature","handshake",A.KEY_EXCHANGE_FAILED);if(!(s=B(s,e)))return C(this._protocol,"Malformed signature","handshake",A.KEY_EXCHANGE_FAILED);{k.init(this._hostKey,0);const e=k.readString(!0),r=this._hostKey.slice(k.pos());if(k.clear(),t=S(r,e),t instanceof Error)return t.level="handshake",C(this._protocol,t,A.KEY_EXCHANGE_FAILED)}switch(this.negotiated.serverHostKey){case"rsa-sha2-256":n="sha256";break;case"rsa-sha2-512":n="sha512"}this._protocol._debug&&this._protocol._debug("Verifying signature ...");const i=t.verify(l,s,n);if(!0!==i)return i instanceof Error?this._protocol._debug&&this._protocol._debug(`Signature verification failed: ${i.stack}`):this._protocol._debug&&this._protocol._debug("Signature verification failed"),C(this._protocol,"Handshake failed: signature verification failed","handshake",A.KEY_EXCHANGE_FAILED);this._protocol._debug&&this._protocol._debug("Verified signature")}let u,h;!t&&e||W(this);const d=e=>{if(u)return W(this),u.outbound.seqno=this._protocol._cipher.outSeqno,this._protocol._cipher.free(),this._protocol._cipher=w(u),this._protocol._packetRW.write=h,u=void 0,h=void 0,this._protocol._onHandshakeComplete(r),!1;this.sessionID||(this.sessionID=l);{const e=Buffer.allocUnsafe(4+s.length);x(e,s.length,0),e.set(s,4),s=e}const n=b[r.cs.cipher],i=b[r.sc.cipher],o=Q(n.ivLen,this.hashName,s,l,this.sessionID,"A"),a=Q(i.ivLen,this.hashName,s,l,this.sessionID,"B"),c=Q(n.keyLen,this.hashName,s,l,this.sessionID,"C"),f=Q(i.keyLen,this.hashName,s,l,this.sessionID,"D");let p,_,g,m;n.authLen||(p=I[r.cs.mac],_=Q(p.len,this.hashName,s,l,this.sessionID,"E")),i.authLen||(g=I[r.sc.mac],m=Q(g.len,this.hashName,s,l,this.sessionID,"F"));const y={inbound:{onPayload:this._protocol._onPayload,seqno:this._protocol._decipher.inSeqno,decipherInfo:t?n:i,decipherIV:t?o:a,decipherKey:t?c:f,macInfo:t?p:g,macKey:t?_:m},outbound:{onWrite:this._protocol._onWrite,seqno:this._protocol._cipher.outSeqno,cipherInfo:t?i:n,cipherIV:t?a:o,cipherKey:t?f:c,macInfo:t?g:p,macKey:t?m:_}};this._protocol._decipher.free(),u=y,this._protocol._decipher=E(y);const A={read:void 0,write:void 0};switch(r.cs.compress){case"zlib":t?A.read=new F:A.write=new M(this._protocol);break;case"zlib@openssh.com":if(this._protocol._authenticated){t?A.read=new F:A.write=new M(this._protocol);break}default:t?A.read=new T:A.write=new N(this._protocol)}switch(r.sc.compress){case"zlib":t?A.write=new M(this._protocol):A.read=new F;break;case"zlib@openssh.com":if(this._protocol._authenticated){t?A.write=new M(this._protocol):A.read=new F;break}default:t?A.write=new N(this._protocol):A.read=new T}return this._protocol._packetRW.read.cleanup(),this._protocol._packetRW.write.cleanup(),this._protocol._packetRW.read=A.read,h=A.write,this._public=null,this._dh=null,this._kexinit=this._protocol._kexinit=void 0,this._remoteKexinit=void 0,this._identRaw=void 0,this._remoteIdentRaw=void 0,this._hostKey=void 0,this._dhData=void 0,this._sig=void 0,!e&&d()};return(t||e)&&(this.finish=d),t?void 0:d(e)}start(){if(!this._protocol._server){if(this._protocol._debug){let e;e="group"===this.type?"KEXDH_INIT":"KEXECDH_INIT",this._protocol._debug(`Outbound: Sending ${e}`)}const e=this.getPublicKey();let t=this._protocol._packetRW.write.allocStartKEX;const r=this._protocol._packetRW.write.alloc(5+e.length,!0);r[t]=v.KEXDH_INIT,x(r,e.length,++t),r.set(e,t+=4),this._protocol._cipher.encrypt(this._protocol._packetRW.write.finalize(r,!0))}}getPublicKey(){this.generateKeys();const e=this._public;if(e)return this.convertPublicKey(e)}convertPublicKey(e){let t,r=0,n=e.length;for(;0===e[r];)++r,--n;return 128&e[r]?(t=Buffer.allocUnsafe(1+n),t[0]=0,e.copy(t,1,r),t):(n!==e.length&&(t=Buffer.allocUnsafe(n),e.copy(t,0,r),e=t),e)}computeSecret(t){this.generateKeys();try{return e(this._dh.computeSecret(t))}catch(e){return e}}parse(e){const t=e[0];switch(this._step){case 1:if(this._protocol._server){if(t!==v.KEXDH_INIT)return C(this._protocol,`Received packet ${t} instead of ${v.KEXDH_INIT}`,"handshake",A.KEY_EXCHANGE_FAILED);this._protocol._debug&&this._protocol._debug("Received DH Init"),k.init(e,1);const r=k.readString();if(k.clear(),void 0===r)return C(this._protocol,"Received malformed KEX*_INIT","handshake",A.KEY_EXCHANGE_FAILED);this._dhData=r;let n=this._protocol._hostKeys[this.negotiated.serverHostKey];Array.isArray(n)&&(n=n[0]),this._hostKey=n,this.finish()}else{if(t!==v.KEXDH_REPLY)return C(this._protocol,`Received packet ${t} instead of ${v.KEXDH_REPLY}`,"handshake",A.KEY_EXCHANGE_FAILED);let r,n,s;if(this._protocol._debug&&this._protocol._debug("Received DH Reply"),k.init(e,1),void 0===(r=k.readString())||void 0===(n=k.readString())||void 0===(s=k.readString()))return k.clear(),C(this._protocol,"Received malformed KEX*_REPLY","handshake",A.KEY_EXCHANGE_FAILED);k.clear(),k.init(r,0);const i=k.readString(!0);if(k.clear(),void 0===i)return C(this._protocol,"Received malformed host public key","handshake",A.KEY_EXCHANGE_FAILED);if(i!==this.negotiated.serverHostKey)switch(this.negotiated.serverHostKey){case"rsa-sha2-256":case"rsa-sha2-512":if("ssh-rsa"===i)break;default:return C(this._protocol,"Host key does not match negotiated type","handshake",A.KEY_EXCHANGE_FAILED)}this._hostKey=r,this._dhData=n,this._sig=s;let o,a=!1;if(void 0===this._protocol._hostVerifier?(o=!0,this._protocol._debug&&this._protocol._debug("Host accepted by default (no verification)")):o=this._protocol._hostVerifier(r,e=>{if(!a){if(a=!0,!1===e)return this._protocol._debug&&this._protocol._debug("Host denied (verification failed)"),C(this._protocol,"Host denied (verification failed)","handshake",A.KEY_EXCHANGE_FAILED);this._protocol._debug&&this._protocol._debug("Host accepted (verified)"),this._hostVerified=!0,this._receivedNEWKEYS?this.finish():W(this)}}),void 0===o)return void++this._step;if(a=!0,!1===o)return this._protocol._debug&&this._protocol._debug("Host denied (verification failed)"),C(this._protocol,"Host denied (verification failed)","handshake",A.KEY_EXCHANGE_FAILED);this._protocol._debug&&this._protocol._debug("Host accepted (verified)"),this._hostVerified=!0,W(this)}++this._step;break;case 2:return t!==v.NEWKEYS?C(this._protocol,`Received packet ${t} instead of ${v.NEWKEYS}`,"handshake",A.KEY_EXCHANGE_FAILED):(this._protocol._debug&&this._protocol._debug("Inbound: NEWKEYS"),this._receivedNEWKEYS=!0,this._protocol._strictMode&&(this._protocol._decipher.inSeqno=0),++this._step,this.finish(!this._protocol._server&&!this._hostVerified));default:return C(this._protocol,`Received unexpected packet ${t} after NEWKEYS`,"handshake",A.KEY_EXCHANGE_FAILED)}}}class r extends t{constructor(e,...t){super(...t),this.type="25519",this.hashName=e,this._keys=null}generateKeys(){this._keys||(this._keys=l("x25519"))}getPublicKey(){return this.generateKeys(),this._keys.publicKey.export({type:"spki",format:"der"}).slice(-32)}convertPublicKey(e){let t,r=0,n=e.length;for(;0===e[r];)++r,--n;return 32===e.length||n!==e.length&&(t=Buffer.allocUnsafe(n),e.copy(t,0,r),e=t),e}computeSecret(t){this.generateKeys();try{const r=new h.Writer;return r.startSequence(),r.startSequence(),r.writeOID("1.3.101.110"),r.endSequence(),r.startSequence(h.BitString),r.writeByte(0),r._ensure(t.length),t.copy(r._buf,r._offset,0,t.length),r._offset+=t.length,r.endSequence(),r.endSequence(),e(c({privateKey:this._keys.privateKey,publicKey:a({key:r.buffer,type:"spki",format:"der"})}))}catch(e){return e}}}class u extends t{constructor(e,t,...r){super(...r),this.type="ecdh",this.curveName=e,this.hashName=t}generateKeys(){this._dh||(this._dh=i(this.curveName),this._public=this._dh.generateKeys())}}class p extends t{constructor(e,...t){super(...t),this.type="groupex",this.hashName=e,this._prime=null,this._generator=null,this._minBits=2048,this._prefBits=function(e){const t=b[e.cs.cipher],r=b[e.sc.cipher],n=8*Math.max(0,"des-ede3-cbc"===t.sslName?14:t.keyLen,t.blockLen,t.ivLen,"des-ede3-cbc"===r.sslName?14:r.keyLen,r.blockLen,r.ivLen);return n<=112?2048:n<=128?3072:n<=192?7680:8192}(this.negotiated),this._protocol._compatFlags&d.BUG_DHGEX_LARGE&&(this._prefBits=Math.min(this._prefBits,4096)),this._maxBits=8192}start(){if(this._protocol._server)return;this._protocol._debug&&this._protocol._debug("Outbound: Sending KEXDH_GEX_REQUEST");let e=this._protocol._packetRW.write.allocStartKEX;const t=this._protocol._packetRW.write.alloc(13,!0);t[e]=v.KEXDH_GEX_REQUEST,x(t,this._minBits,++e),x(t,this._prefBits,e+=4),x(t,this._maxBits,e+=4),this._protocol._cipher.encrypt(this._protocol._packetRW.write.finalize(t,!0))}generateKeys(){!this._dh&&this._prime&&this._generator&&(this._dh=n(this._prime,this._generator),this._public=this._dh.generateKeys())}setDHParams(e,t){if(!Buffer.isBuffer(e))throw new Error("Invalid prime value");if(!Buffer.isBuffer(t))throw new Error("Invalid generator value");this._prime=e,this._generator=t}getDHParams(){if(this._dh)return{prime:e(this._dh.getPrime()),generator:e(this._dh.getGenerator())}}parse(e){const r=e[0];switch(this._step){case 1:{if(this._protocol._server)return r!==v.KEXDH_GEX_REQUEST?C(this._protocol,`Received packet ${r} instead of `+v.KEXDH_GEX_REQUEST,"handshake",A.KEY_EXCHANGE_FAILED):C(this._protocol,"Group exchange not implemented for server","handshake",A.KEY_EXCHANGE_FAILED);if(r!==v.KEXDH_GEX_GROUP)return C(this._protocol,`Received packet ${r} instead of ${v.KEXDH_GEX_GROUP}`,"handshake",A.KEY_EXCHANGE_FAILED);let t,n;if(this._protocol._debug&&this._protocol._debug("Received DH GEX Group"),k.init(e,1),void 0===(t=k.readString())||void 0===(n=k.readString()))return k.clear(),C(this._protocol,"Received malformed KEXDH_GEX_GROUP","handshake",A.KEY_EXCHANGE_FAILED);k.clear(),this.setDHParams(t,n),this.generateKeys();const s=this.getPublicKey();this._protocol._debug&&this._protocol._debug("Outbound: Sending KEXDH_GEX_INIT");let i=this._protocol._packetRW.write.allocStartKEX;const o=this._protocol._packetRW.write.alloc(5+s.length,!0);o[i]=v.KEXDH_GEX_INIT,x(o,s.length,++i),o.set(s,i+=4),this._protocol._cipher.encrypt(this._protocol._packetRW.write.finalize(o,!0)),++this._step;break}case 2:if(this._protocol._server)return r!==v.KEXDH_GEX_INIT?C(this._protocol,`Received packet ${r} instead of ${v.KEXDH_GEX_INIT}`,"handshake",A.KEY_EXCHANGE_FAILED):(this._protocol._debug&&this._protocol._debug("Received DH GEX Init"),C(this._protocol,"Group exchange not implemented for server","handshake",A.KEY_EXCHANGE_FAILED));if(r!==v.KEXDH_GEX_REPLY)return C(this._protocol,`Received packet ${r} instead of ${v.KEXDH_GEX_REPLY}`,"handshake",A.KEY_EXCHANGE_FAILED);this._protocol._debug&&this._protocol._debug("Received DH GEX Reply"),this._step=1,e[0]=v.KEXDH_REPLY,this.parse=t.prototype.parse,this.parse(e)}}}class _ extends t{constructor(e,t,...r){super(...r),this.type="group",this.groupName=e,this.hashName=t}start(){if(!this._protocol._server){this._protocol._debug&&this._protocol._debug("Outbound: Sending KEXDH_INIT");const e=this.getPublicKey();let t=this._protocol._packetRW.write.allocStartKEX;const r=this._protocol._packetRW.write.alloc(5+e.length,!0);r[t]=v.KEXDH_INIT,x(r,e.length,++t),r.set(e,t+=4),this._protocol._cipher.encrypt(this._protocol._packetRW.write.finalize(r,!0))}}generateKeys(){this._dh||(this._dh=s(this.groupName),this._public=this._dh.generateKeys())}getDHParams(){if(this._dh)return{prime:e(this._dh.getPrime()),generator:e(this._dh.getGenerator())}}}return(e,...t)=>{if("object"!=typeof e||null===e)throw new Error("Invalid negotiated argument");const n=e.kex;if("string"==typeof n){switch(t=[e,...t],n){case"curve25519-sha256":case"curve25519-sha256@libssh.org":if(!f)break;return new r("sha256",...t);case"ecdh-sha2-nistp256":return new u("prime256v1","sha256",...t);case"ecdh-sha2-nistp384":return new u("secp384r1","sha384",...t);case"ecdh-sha2-nistp521":return new u("secp521r1","sha512",...t);case"diffie-hellman-group1-sha1":return new _("modp2","sha1",...t);case"diffie-hellman-group14-sha1":return new _("modp14","sha1",...t);case"diffie-hellman-group14-sha256":return new _("modp14","sha256",...t);case"diffie-hellman-group15-sha512":return new _("modp15","sha512",...t);case"diffie-hellman-group16-sha512":return new _("modp16","sha512",...t);case"diffie-hellman-group17-sha512":return new _("modp17","sha512",...t);case"diffie-hellman-group18-sha512":return new _("modp18","sha512",...t);case"diffie-hellman-group-exchange-sha1":return new p("sha1",...t);case"diffie-hellman-group-exchange-sha256":return new p("sha256",...t)}throw new Error(`Unsupported key exchange algorithm: ${n}`)}throw new Error(`Invalid key exchange type: ${n}`)}})(),H=(()=>{const e=["kex","serverHostKey",["cs","cipher"],["sc","cipher"],["cs","mac"],["sc","mac"],["cs","compress"],["sc","compress"],["cs","lang"],["sc","lang"]];return class{constructor(t){if("object"!=typeof t||null===t)throw new TypeError("Argument must be an object");const r={kex:void 0,serverHostKey:void 0,cs:{cipher:void 0,mac:void 0,compress:void 0,lang:void 0},sc:{cipher:void 0,mac:void 0,compress:void 0,lang:void 0},all:void 0};let n=0;for(const s of e){let e,i,o,a;if("string"==typeof s)e=r,i=t[s],o=a=s;else{const n=s[0];e=r[n],a=s[1],i=t[n][a],o=`${n}.${a}`}const c={array:void 0,buffer:void 0};if(Buffer.isBuffer(i))c.array=(""+i).split(","),c.buffer=i,n+=4+i.length;else{if("string"==typeof i&&(i=i.split(",")),!Array.isArray(i))throw new TypeError(`Invalid \`${o}\` type: ${typeof i}`);c.array=i,c.buffer=Buffer.from(i.join(",")),n+=4+c.buffer.length}e[a]=c}const s=Buffer.allocUnsafe(n);r.all=s;let i=0;for(const t of e){let e;e="string"==typeof t?r[t].buffer:r[t[0]][t[1]].buffer,i=x(s,e.length,i),s.set(e,i),i+=e.length}this.totalSize=n,this.lists=r}copyAllTo(e,t){const r=this.lists.all;if("number"!=typeof t)throw new TypeError("Invalid offset value: "+typeof t);if(e.length-t<r.length)throw new Error("Insufficient space to copy list");return e.set(r,t),r.length}}})(),G=(()=>{const e=Buffer.allocUnsafe(4);return(t,r)=>{x(e,r.length,0),t.update(e),t.update(r)}})();function Q(e,t,r,n,s,i){let a;if(e){let c=o(t).update(r).update(n).update(i).update(s).digest();for(;c.length<e;){const e=o(t).update(r).update(n).update(c).digest(),s=Buffer.allocUnsafe(c.length+e.length);s.set(c,0),s.set(e,c.length),c=s}a=c.length===e?c:new R(c.buffer,c.byteOffset,e)}else a=U;return a}function q(e,t){if(0===t.length)return void(this._debug&&this._debug("Inbound: Skipping empty packet payload"));if(this._skipNextInboundPacket)return void(this._skipNextInboundPacket=!1);const n=(t=this._packetRW.read.read(t))[0];if(!this._strictMode)switch(n){case v.IGNORE:case v.UNIMPLEMENTED:case v.DEBUG:return L||(L=r(2917)),L[n](this,t)}switch(n){case v.DISCONNECT:return L||(L=r(2917)),L[n](this,t);case v.KEXINIT:return e.firstPacket?(e.firstPacket=!1,$(this,t)):C(this,"Received extra KEXINIT during handshake","handshake",A.KEY_EXCHANGE_FAILED);default:if(n<20||n>49)return C(this,`Received unexpected packet type ${n}`,"handshake",A.KEY_EXCHANGE_FAILED)}return this._kex.parse(t)}function W(e){if(!e._sentNEWKEYS){e._protocol._debug&&e._protocol._debug("Outbound: Sending NEWKEYS");const t=e._protocol._packetRW.write.allocStartKEX,r=e._protocol._packetRW.write.alloc(1,!0);r[t]=v.NEWKEYS,e._protocol._cipher.encrypt(e._protocol._packetRW.write.finalize(r,!0)),e._sentNEWKEYS=!0,e._protocol._strictMode&&(e._protocol._cipher.outSeqno=0)}}e.exports={KexInit:H,kexinit:D,onKEXPayload:q,DEFAULT_KEXINIT_CLIENT:new H({kex:p.concat(["ext-info-c","kex-strict-c-v00@openssh.com"]),serverHostKey:_,cs:{cipher:g,mac:m,compress:y,lang:[]},sc:{cipher:g,mac:m,compress:y,lang:[]}}),DEFAULT_KEXINIT_SERVER:new H({kex:p.concat(["kex-strict-s-v00@openssh.com"]),serverHostKey:_,cs:{cipher:g,mac:m,compress:y,lang:[]},sc:{cipher:g,mac:m,compress:y,lang:[]}}),G:{[v.KEXINIT]:$}}},614(e,t,r){"use strict";const{createDecipheriv:n,createECDH:s,createHash:i,createHmac:o,createSign:a,createVerify:c,getCiphers:l,sign:u,verify:h}=r(6982),d=l(),{Ber:f}=r(5896),p=r(3091).SF,{CIPHER_INFO:_}=r(2597),{eddsaSupported:g,SUPPORTED_CIPHER:m}=r(4963),{bufferSlice:y,makeBufferParser:A,readString:v,readUInt32BE:b,writeUInt32BE:w}=r(4787),E=Symbol("Hash Algorithm"),I=Symbol("Private key PEM"),S=Symbol("Public key PEM"),P=Symbol("Public key SSH"),k=Symbol("Decrypted Key"),O=Object.create(null);{const ee=Object.keys(_);for(let te=0;te<ee.length;++te){const re=_[ee[te]].sslName;re&&!O[re]&&(O[re]=_[ee[te]])}}const C=A();function R(e,t){let r=(t=t.base64Slice(0,t.length)).replace(/.{64}/g,"$&\n");return 63&t.length&&(r+="\n"),`-----BEGIN ${e} KEY-----\n${r}-----END ${e} KEY-----`}function B(e,t){const r=Buffer.allocUnsafe(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}function x(e,t){const r=e.length;let n=e._pos||0;for(let s=0;s<t;++s){const t=r-n;if(n>=r||t<4)return!1;const s=b(e,n);if(t<4+s)return!1;n+=4+s}return e._pos=n,!0}function T(e,t){const r=new f.Writer;return r.startSequence(),r.startSequence(),r.writeOID("1.2.840.113549.1.1.1"),r.writeNull(),r.endSequence(),r.startSequence(f.BitString),r.writeByte(0),r.startSequence(),r.writeBuffer(e,f.Integer),r.writeBuffer(t,f.Integer),r.endSequence(),r.endSequence(),r.endSequence(),R("PUBLIC",r.buffer)}function N(e,t){const r=Buffer.allocUnsafe(15+t.length+4+e.length);w(r,7,0),r.utf8Write("ssh-rsa",4,7);let n=11;return w(r,t.length,n),r.set(t,n+=4),w(r,e.length,n+=t.length),r.set(e,n+4),r}const F=(()=>{function e(e){return BigInt(`0x${e.hexSlice(0,e.length)}`)}function t(e){let t=e.toString(16);if(1&t.length)t=`0${t}`;else{const e=t.charCodeAt(0);(56===e||57===e||e>=97&&e<=102)&&(t=`00${t}`)}return Buffer.from(t,"hex")}return function(r,n,s,i,o,a){const c=e(s);return R("RSA PRIVATE",function(e,t,r,n,s,i,o,a){const c=new f.Writer;return c.startSequence(),c.writeInt(0,f.Integer),c.writeBuffer(e,f.Integer),c.writeBuffer(t,f.Integer),c.writeBuffer(r,f.Integer),c.writeBuffer(n,f.Integer),c.writeBuffer(s,f.Integer),c.writeBuffer(i,f.Integer),c.writeBuffer(o,f.Integer),c.writeBuffer(a,f.Integer),c.endSequence(),c.buffer}(r,n,s,o,a,t(c%(e(o)-1n)),t(c%(e(a)-1n)),i))}})();function M(e,t,r,n){const s=new f.Writer;return s.startSequence(),s.startSequence(),s.writeOID("1.2.840.10040.4.1"),s.startSequence(),s.writeBuffer(e,f.Integer),s.writeBuffer(t,f.Integer),s.writeBuffer(r,f.Integer),s.endSequence(),s.endSequence(),s.startSequence(f.BitString),s.writeByte(0),s.writeBuffer(n,f.Integer),s.endSequence(),s.endSequence(),R("PUBLIC",s.buffer)}function L(e,t,r,n){const s=Buffer.allocUnsafe(15+e.length+4+t.length+4+r.length+4+n.length);w(s,7,0),s.utf8Write("ssh-dss",4,7);let i=11;return w(s,e.length,i),s.set(e,i+=4),w(s,t.length,i+=e.length),s.set(t,i+=4),w(s,r.length,i+=t.length),s.set(r,i+=4),w(s,n.length,i+=r.length),s.set(n,i+4),s}function U(e,t,r,n,s){const i=new f.Writer;return i.startSequence(),i.writeInt(0,f.Integer),i.writeBuffer(e,f.Integer),i.writeBuffer(t,f.Integer),i.writeBuffer(r,f.Integer),i.writeBuffer(n,f.Integer),i.writeBuffer(s,f.Integer),i.endSequence(),R("DSA PRIVATE",i.buffer)}function D(e){const t=new f.Writer;return t.startSequence(),t.startSequence(),t.writeOID("1.3.101.112"),t.endSequence(),t.startSequence(f.BitString),t.writeByte(0),t._ensure(e.length),t._buf.set(e,t._offset),t._offset+=e.length,t.endSequence(),t.endSequence(),R("PUBLIC",t.buffer)}function $(e){const t=Buffer.allocUnsafe(19+e.length);return w(t,11,0),t.utf8Write("ssh-ed25519",4,11),w(t,e.length,15),t.set(e,19),t}function j(e){const t=new f.Writer;return t.startSequence(),t.writeInt(0,f.Integer),t.startSequence(),t.writeOID("1.3.101.112"),t.endSequence(),t.startSequence(f.OctetString),t.writeBuffer(e,f.OctetString),t.endSequence(),t.endSequence(),R("PRIVATE",t.buffer)}function H(e,t){const r=new f.Writer;return r.startSequence(),r.startSequence(),r.writeOID("1.2.840.10045.2.1"),r.writeOID(e),r.endSequence(),r.startSequence(f.BitString),r.writeByte(0),r._ensure(t.length),r._buf.set(t,r._offset),r._offset+=t.length,r.endSequence(),r.endSequence(),R("PUBLIC",r.buffer)}function G(e,t){let r;switch(e){case"1.2.840.10045.3.1.7":r="nistp256";break;case"1.3.132.0.34":r="nistp384";break;case"1.3.132.0.35":r="nistp521";break;default:return}const n=Buffer.allocUnsafe(39+t.length);return w(n,19,0),n.utf8Write(`ecdsa-sha2-${r}`,4,19),w(n,8,23),n.utf8Write(r,27,8),w(n,t.length,35),n.set(t,39),n}function Q(e,t,r){const n=new f.Writer;return n.startSequence(),n.writeInt(1,f.Integer),n.writeBuffer(r,f.OctetString),n.startSequence(160),n.writeOID(e),n.endSequence(),n.startSequence(161),n.startSequence(f.BitString),n.writeByte(0),n._ensure(t.length),n._buf.set(t,n._offset),n._offset+=t.length,n.endSequence(),n.endSequence(),n.endSequence(),R("EC PRIVATE",n.buffer)}const q={sign:"function"==typeof u?function(e,t){const r=this[I];if(null===r)return new Error("No private key available");t&&"string"==typeof t||(t=this[E]);try{return u(t,e,r)}catch(e){return e}}:function(e,t){const r=this[I];if(null===r)return new Error("No private key available");t&&"string"==typeof t||(t=this[E]);const n=a(t);n.update(e);try{return n.sign(r)}catch(e){return e}},verify:"function"==typeof h?function(e,t,r){const n=this[S];if(null===n)return new Error("No public key available");r&&"string"==typeof r||(r=this[E]);try{return h(r,e,n,t)}catch(e){return e}}:function(e,t,r){const n=this[S];if(null===n)return new Error("No public key available");r&&"string"==typeof r||(r=this[E]);const s=c(r);s.update(e);try{return s.verify(n,t)}catch(e){return e}},isPrivateKey:function(){return null!==this[I]},getPrivatePEM:function(){return this[I]},getPublicPEM:function(){return this[S]},getPublicSSH:function(){return this[P]},equals:function(e){const t=Z(e);return!(t instanceof Error)&&this.type===t.type&&this[I]===t[I]&&this[S]===t[S]&&this[P].equals(t[P])}};function W(e,t,r,n,s,i,o){this.type=e,this.comment=t,this[I]=r,this[S]=n,this[P]=s,this[E]=i,this[k]=o}W.prototype=q;{const ne=/^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/;function se(e,t,r){const n=[];if(e.length<8)return new Error("Malformed OpenSSH private key");if(b(e,0)!==b(e,4))return r?new Error("OpenSSH key integrity check failed -- bad passphrase?"):new Error("OpenSSH key integrity check failed");let s,i;for(e._pos=8,s=0;s<t;++s){let t,s,o,a;const c=v(e,e._pos,!0);if(void 0===c)return new Error("Malformed OpenSSH private key");switch(c){case"ssh-rsa":{const r=v(e,e._pos);if(void 0===r)return new Error("Malformed OpenSSH private key");const n=v(e,e._pos);if(void 0===n)return new Error("Malformed OpenSSH private key");const i=v(e,e._pos);if(void 0===i)return new Error("Malformed OpenSSH private key");const c=v(e,e._pos);if(void 0===c)return new Error("Malformed OpenSSH private key");const l=v(e,e._pos);if(void 0===l)return new Error("Malformed OpenSSH private key");const u=v(e,e._pos);if(void 0===u)return new Error("Malformed OpenSSH private key");o=T(r,n),a=N(r,n),s=F(r,n,i,c,l,u),t="sha1";break}case"ssh-dss":{const r=v(e,e._pos);if(void 0===r)return new Error("Malformed OpenSSH private key");const n=v(e,e._pos);if(void 0===n)return new Error("Malformed OpenSSH private key");const i=v(e,e._pos);if(void 0===i)return new Error("Malformed OpenSSH private key");const c=v(e,e._pos);if(void 0===c)return new Error("Malformed OpenSSH private key");const l=v(e,e._pos);if(void 0===l)return new Error("Malformed OpenSSH private key");o=M(r,n,i,c),a=L(r,n,i,c),s=U(r,n,i,c,l),t="sha1";break}case"ssh-ed25519":{if(!g)return new Error(`Unsupported OpenSSH private key type: ${c}`);const r=v(e,e._pos);if(void 0===r||32!==r.length)return new Error("Malformed OpenSSH private key");const n=v(e,e._pos);if(void 0===n||64!==n.length)return new Error("Malformed OpenSSH private key");o=D(r),a=$(r),s=j(y(n,0,32)),t=null;break}case"ecdsa-sha2-nistp256":t="sha256",i="1.2.840.10045.3.1.7";case"ecdsa-sha2-nistp384":void 0===t&&(t="sha384",i="1.3.132.0.34");case"ecdsa-sha2-nistp521":{if(void 0===t&&(t="sha512",i="1.3.132.0.35"),!x(e,1))return new Error("Malformed OpenSSH private key");const r=v(e,e._pos);if(void 0===r)return new Error("Malformed OpenSSH private key");const n=v(e,e._pos);if(void 0===n)return new Error("Malformed OpenSSH private key");o=H(i,r),a=G(i,r),s=Q(i,r,n);break}default:return new Error(`Unsupported OpenSSH private key type: ${c}`)}const l=v(e,e._pos,!0);if(void 0===l)return new Error("Malformed OpenSSH private key");n.push(new W(c,l,s,o,a,t,r))}let o=0;for(s=e._pos;s<e.length;++s)if(e[s]!==++o%255)return new Error("Malformed OpenSSH private key");return n}W.parse=(e,t)=>{const r=ne.exec(e);if(null===r)return null;let s;const i=Buffer.from(r[1],"base64");if(i.length<31)return new Error("Malformed OpenSSH private key");const o=i.utf8Slice(0,15);if("openssh-key-v1\0"!==o)return new Error(`Unsupported OpenSSH key magic: ${o}`);const a=v(i,15,!0);if(void 0===a)return new Error("Malformed OpenSSH private key");if("none"!==a&&-1===m.indexOf(a))return new Error(`Unsupported cipher for OpenSSH key: ${a}`);const c=v(i,i._pos,!0);if(void 0===c)return new Error("Malformed OpenSSH private key");if("none"!==c){if("none"===a)return new Error("Malformed OpenSSH private key");if("bcrypt"!==c)return new Error(`Unsupported kdf name for OpenSSH key: ${c}`);if(!t)return new Error("Encrypted private OpenSSH key detected, but no passphrase given")}else if("none"!==a)return new Error("Malformed OpenSSH private key");let l,u,h;"none"!==a&&(l=_[a]);const d=v(i,i._pos);if(void 0===d)return new Error("Malformed OpenSSH private key");if(d.length)switch(c){case"none":return new Error("Malformed OpenSSH private key");case"bcrypt":{const e=v(d,0);if(void 0===e||d._pos+4>d.length)return new Error("Malformed OpenSSH private key");const r=b(d,d._pos),n=Buffer.allocUnsafe(l.keyLen+l.ivLen);if(0!==p(t,t.length,e,e.length,n,n.length,r))return new Error("Failed to generate information to decrypt key");u=y(n,0,l.keyLen),h=y(n,l.keyLen,n.length);break}}else if("none"!==c)return new Error("Malformed OpenSSH private key");if(i._pos+3>=i.length)return new Error("Malformed OpenSSH private key");const f=b(i,i._pos);if(i._pos+=4,f>0){for(let e=0;e<f;++e){const e=v(i,i._pos);if(void 0===e)return new Error("Malformed OpenSSH private key");if(void 0===v(e,0,!0))return new Error("Malformed OpenSSH private key")}let e=v(i,i._pos);if(void 0===e)return new Error("Malformed OpenSSH private key");if(void 0!==u){if(e.length<l.blockLen||e.length%l.blockLen!==0)return new Error("Malformed OpenSSH private key");try{const t={authTagLength:l.authLen},r=n(l.sslName,u,h,t);if(r.setAutoPadding(!1),l.authLen>0){if(i.length-i._pos<l.authLen)return new Error("Malformed OpenSSH private key");r.setAuthTag(y(i,i._pos,i._pos+=l.authLen))}e=B(r.update(e),r.final())}catch(e){return e}}if(i._pos!==i.length)return new Error("Malformed OpenSSH private key");s=se(e,f,void 0!==u)}else s=[];return s instanceof Error?s:s[0]}}function K(e,t,r,n,s,i,o){this.type=e,this.comment=t,this[I]=r,this[S]=n,this[P]=s,this[E]=i,this[k]=o}K.prototype=q;{const ie=/^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/;K.parse=(e,t)=>{const r=ie.exec(e);if(null===r)return null;let o,a,c,l,u,h,p=Buffer.from(r[3],"base64"),_=r[2],g=!1;if(void 0!==_){_=_.split(/\r\n|\n/g);for(let e=0;e<_.length;++e){const r=_[e];let s=r.indexOf(":");if("DEK-Info"===r.slice(0,s)){const e=r.slice(s+2);if(s=e.indexOf(","),-1===s)continue;const o=e.slice(0,s).toLowerCase();if(-1===d.indexOf(o))return new Error(`Cipher (${o}) not supported for encrypted OpenSSH private key`);const a=O[o];if(!a)return new Error(`Cipher (${o}) not supported for encrypted OpenSSH private key`);const c=Buffer.from(e.slice(s+1),"hex");if(c.length!==a.ivLen)return new Error("Malformed encrypted OpenSSH private key");if(!t)return new Error("Encrypted OpenSSH private key detected, but no passphrase given");const l=y(c,0,8);let u=i("md5").update(t).update(l).digest();for(;u.length<a.keyLen;)u=B(u,i("md5").update(u).update(t).update(l).digest());u.length>a.keyLen&&(u=y(u,0,a.keyLen));try{const e=n(o,u,c);e.setAutoPadding(!1),p=B(e.update(p),e.final()),g=!0}catch(e){return e}}}}let m="Malformed OpenSSH private key";switch(g&&(m+=". Bad passphrase?"),r[1]){case"RSA":o="ssh-rsa",a=R("RSA PRIVATE",p);try{h=new f.Reader(p),h.readSequence(),h.readInt();const e=h.readString(f.Integer,!0);if(null===e)return new Error(m);const t=h.readString(f.Integer,!0);if(null===t)return new Error(m);c=T(e,t),l=N(e,t)}catch{return new Error(m)}u="sha1";break;case"DSA":o="ssh-dss",a=R("DSA PRIVATE",p);try{h=new f.Reader(p),h.readSequence(),h.readInt();const e=h.readString(f.Integer,!0);if(null===e)return new Error(m);const t=h.readString(f.Integer,!0);if(null===t)return new Error(m);const r=h.readString(f.Integer,!0);if(null===r)return new Error(m);const n=h.readString(f.Integer,!0);if(null===n)return new Error(m);c=M(e,t,r,n),l=L(e,t,r,n)}catch{return new Error(m)}u="sha1";break;case"EC":{let e,t,r;try{h=new f.Reader(p),h.readSequence(),h.readInt(),t=h.readString(f.OctetString,!0),h.readByte();const n=h.readLength();if(null===n)return new Error(m);if(h._offset=n,r=h.readOID(),null===r)return new Error(m);switch(r){case"1.2.840.10045.3.1.7":e="prime256v1",o="ecdsa-sha2-nistp256",u="sha256";break;case"1.3.132.0.34":e="secp384r1",o="ecdsa-sha2-nistp384",u="sha384";break;case"1.3.132.0.35":e="secp521r1",o="ecdsa-sha2-nistp521",u="sha512";break;default:return new Error(`Unsupported private key EC OID: ${r}`)}}catch{return new Error(m)}a=R("EC PRIVATE",p);const n=function(e,t){const r=s(e);return r.setPrivateKey(t),r.getPublicKey()}(e,t);c=H(r,n),l=G(r,n);break}}return new K(o,"",a,c,l,u,g)}}function X(e,t,r,n,s,i,o){this.type=e,this.comment=t,this[I]=r,this[S]=n,this[P]=s,this[E]=i,this[k]=o}X.prototype=q;{const oe=Buffer.alloc(0),ae=Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),ce=Buffer.from([0,0,0,0]),le=Buffer.from([0,0,0,1]),ue=/^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/;X.parse=(e,t)=>{const r=ue.exec(e);if(null===r)return null;const s=r[2],a="none"!==s;if(a&&!t)return new Error("Encrypted PPK private key detected, but no passphrase given");let c=Buffer.from(r[5],"base64");if(a){const e=_[s];let r=B(i("sha1").update(ce).update(t).digest(),i("sha1").update(le).update(t).digest());r.length>e.keyLen&&(r=y(r,0,e.keyLen));try{const t=n(e.sslName,r,ae);t.setAutoPadding(!1),c=B(t.update(c),t.final())}catch(e){return e}}const l=r[1],u=r[3],h=Buffer.from(r[4],"base64"),d=r[6],f=l.length,p=s.length,g=Buffer.byteLength(u),m=h.length,A=c.length,b=Buffer.allocUnsafe(4+f+4+p+4+g+4+m+4+A);let E,I,S,P=0;if(w(b,f,P),b.utf8Write(l,P+=4,f),w(b,p,P+=f),b.utf8Write(s,P+=4,p),w(b,g,P+=p),b.utf8Write(u,P+=4,g),w(b,m,P+=g),b.set(h,P+=4),w(b,A,P+=m),b.set(c,P+4),t||(t=oe),o("sha1",i("sha1").update("putty-private-key-file-mac-key").update(t).digest()).update(b).digest("hex")!==d)return a?new Error("PPK private key integrity check failed -- bad passphrase?"):new Error("PPK private key integrity check failed");switch(h._pos=0,x(h,1),l){case"ssh-rsa":{const e=v(h,h._pos);if(void 0===e)return new Error("Malformed PPK public key");const t=v(h,h._pos);if(void 0===t)return new Error("Malformed PPK public key");const r=v(c,0);if(void 0===r)return new Error("Malformed PPK private key");const n=v(c,c._pos);if(void 0===n)return new Error("Malformed PPK private key");const s=v(c,c._pos);if(void 0===s)return new Error("Malformed PPK private key");const i=v(c,c._pos);if(void 0===i)return new Error("Malformed PPK private key");E=T(t,e),I=N(t,e),S=F(t,e,r,i,n,s);break}case"ssh-dss":{const e=v(h,h._pos);if(void 0===e)return new Error("Malformed PPK public key");const t=v(h,h._pos);if(void 0===t)return new Error("Malformed PPK public key");const r=v(h,h._pos);if(void 0===r)return new Error("Malformed PPK public key");const n=v(h,h._pos);if(void 0===n)return new Error("Malformed PPK public key");const s=v(c,0);if(void 0===s)return new Error("Malformed PPK private key");E=M(e,t,r,n),I=L(e,t,r,n),S=U(e,t,r,n,s);break}}return new X(l,u,S,E,I,"sha1",a)}}function z(e,t,r,n,s){this.type=e,this.comment=t,this[I]=null,this[S]=r,this[P]=n,this[E]=s,this[k]=!1}z.prototype=q;{let he;he=g?/^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/:/^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/,z.parse=e=>{const t=he.exec(e);if(null===t)return null;const r=t[1],n=t[2],s=Buffer.from(t[3],"base64"),i=t[4]||"",o=v(s,s._pos,!0);return void 0===o||0!==o.indexOf(n)?new Error("Malformed OpenSSH public key"):J(s,n,i,r)}}function Y(e,t,r,n,s){this.type=e,this.comment=t,this[I]=null,this[S]=r,this[P]=n,this[E]=s,this[k]=!1}Y.prototype=q;{const de=/^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/,fe=/^[A-Z0-9a-z/+=\r\n]+$/,pe=/^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm,_e=/\\\r?\n/g;Y.parse=e=>{let t=de.exec(e);if(null===t)return null;const r=t[1];let n=0,s="";for(;t=pe.exec(r);){const e=t[1],r=t[2].replace(_e,"");if(r.length>1024)return pe.lastIndex=0,new Error("Malformed RFC4716 public key");n=pe.lastIndex,"comment"===e.toLowerCase()&&(s=r,s.length>1&&34===s.charCodeAt(0)&&34===s.charCodeAt(s.length-1)&&(s=s.slice(1,-1)))}let i=r.slice(n);if(!fe.test(i))return new Error("Malformed RFC4716 public key");i=Buffer.from(i,"base64");const o=v(i,0,!0);if(void 0===o)return new Error("Malformed RFC4716 public key");let a=null,c=null;switch(o){case"ssh-rsa":{const e=v(i,i._pos);if(void 0===e)return new Error("Malformed RFC4716 public key");const t=v(i,i._pos);if(void 0===t)return new Error("Malformed RFC4716 public key");a=T(t,e),c=N(t,e);break}case"ssh-dss":{const e=v(i,i._pos);if(void 0===e)return new Error("Malformed RFC4716 public key");const t=v(i,i._pos);if(void 0===t)return new Error("Malformed RFC4716 public key");const r=v(i,i._pos);if(void 0===r)return new Error("Malformed RFC4716 public key");const n=v(i,i._pos);if(void 0===n)return new Error("Malformed RFC4716 public key");a=M(e,t,r,n),c=L(e,t,r,n);break}default:return new Error("Malformed RFC4716 public key")}return new Y(o,s,a,c,"sha1")}}function J(e,t,r,n){if(!function(e){switch(e){case"ssh-rsa":case"ssh-dss":case"ecdsa-sha2-nistp256":case"ecdsa-sha2-nistp384":case"ecdsa-sha2-nistp521":return!0;case"ssh-ed25519":if(g)return!0;default:return!1}}(t))return new Error(`Unsupported OpenSSH public key type: ${t}`);let s,i,o=null,a=null;switch(t){case"ssh-rsa":{const t=v(e,e._pos||0);if(void 0===t)return new Error("Malformed OpenSSH public key");const r=v(e,e._pos);if(void 0===r)return new Error("Malformed OpenSSH public key");o=T(r,t),a=N(r,t),s="sha1";break}case"ssh-dss":{const t=v(e,e._pos||0);if(void 0===t)return new Error("Malformed OpenSSH public key");const r=v(e,e._pos);if(void 0===r)return new Error("Malformed OpenSSH public key");const n=v(e,e._pos);if(void 0===n)return new Error("Malformed OpenSSH public key");const i=v(e,e._pos);if(void 0===i)return new Error("Malformed OpenSSH public key");o=M(t,r,n,i),a=L(t,r,n,i),s="sha1";break}case"ssh-ed25519":{const t=v(e,e._pos||0);if(void 0===t||32!==t.length)return new Error("Malformed OpenSSH public key");o=D(t),a=$(t),s=null;break}case"ecdsa-sha2-nistp256":s="sha256",i="1.2.840.10045.3.1.7";case"ecdsa-sha2-nistp384":void 0===s&&(s="sha384",i="1.3.132.0.34");case"ecdsa-sha2-nistp521":{if(void 0===s&&(s="sha512",i="1.3.132.0.35"),!x(e,1))return new Error("Malformed OpenSSH public key");const t=v(e,e._pos||0);if(void 0===t)return new Error("Malformed OpenSSH public key");o=H(i,t),a=G(i,t);break}default:return new Error(`Unsupported OpenSSH public key type: ${t}`)}return new z(n,r,o,a,s)}function V(e){return!!e&&"boolean"==typeof e[k]}function Z(e,t){if(V(e))return e;let r,n;if(Buffer.isBuffer(e))r=e,e=e.utf8Slice(0,e.length).trim();else{if("string"!=typeof e)return new Error("Key data must be a Buffer or string");e=e.trim()}if(null!=t)if("string"==typeof t)t=Buffer.from(t);else if(!Buffer.isBuffer(t))return new Error("Passphrase must be a string or Buffer when supplied");if(null!==(n=W.parse(e,t)))return n;if(null!==(n=K.parse(e,t)))return n;if(null!==(n=X.parse(e,t)))return n;if(null!==(n=z.parse(e)))return n;if(null!==(n=Y.parse(e)))return n;if(r){C.init(r,0);const t=C.readString(!0);void 0!==t&&void 0!==(e=C.readRaw())&&(n=J(e,t,"",t),n instanceof Error&&(n=null)),C.clear()}return n||new Error("Unsupported key format")}e.exports={isParsedKey:V,parseDERKey:(e,t)=>J(e,t,"",t),parseKey:Z}},4397(e,t,r){"use strict";const n=r(2613),{inspect:s}=r(9023);function i(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function o(e,t){if(n("string"==typeof t,"`thing` has to be of type string"),Array.isArray(e)){const r=e.length;return n(r>0,"At least one expected value needs to be specified"),e=e.map(e=>String(e)),r>2?`one of ${t} ${e.slice(0,r-1).join(", ")}, or `+e[r-1]:2===r?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}return`of ${t} ${String(e)}`}Error;const a=2**32,c=(()=>{try{return new Function("return 2n ** 32n")()}catch{}})();t.ERR_OUT_OF_RANGE=class e extends RangeError{constructor(t,r,o,l){super(),Error.captureStackTrace(this,e),n(r,'Missing "range" argument');let u,h=l?t:`The value of "${t}" is out of range.`;Number.isInteger(o)&&Math.abs(o)>a?u=i(String(o)):"bigint"==typeof o?(u=String(o),(o>c||o<-c)&&(u=i(u)),u+="n"):u=s(o),h+=` It must be ${r}. Received ${u}`,this.message=h}};class l extends TypeError{constructor(e,t,r){let s,i;if(super(),Error.captureStackTrace(this,l),n("string"==typeof e,"'name' must be a string"),"string"==typeof t&&t.startsWith("not ")?(s="must not be",t=t.replace(/^not /,"")):s="must be",e.endsWith(" argument"))i=`The ${e} ${s} ${o(t,"type")}`;else{const r=e.includes(".")?"property":"argument";i=`The "${e}" ${r} ${s} ${o(t,"type")}`}i+=". Received type "+typeof r,this.message=i}}t.ERR_INVALID_ARG_TYPE=l,t.validateNumber=function(e,t){if("number"!=typeof e)throw new l(t,"number",e)}},4787(e,t,r){"use strict";const n=r(5896).Ber;let s;const i=Buffer[Symbol.species],o=Object.getPrototypeOf(Uint8Array.prototype).fill;function a(e,t){return 16777216*e[t++]+65536*e[t++]+256*e[t++]+e[t]}function c(e,t,r,n,s){s||(s=0),n>e.length&&(n=e.length);let i=n-r;const o=t.length-s;return i>o&&(i=o),t.set(new Uint8Array(e.buffer,e.byteOffset+r,i),s),i}function l(e,t,r){return void 0===r&&(r=e.length),new i(e.buffer,e.byteOffset+t,r-t)}function u(){let e,t=0;const r={init:(r,n)=>{e=r,t="number"==typeof n?n:0},pos:()=>t,length:()=>e?e.length:0,avail:()=>e&&t<e.length?e.length-t:0,clear:()=>{e=void 0},readUInt32BE:()=>{if(e&&!(t+3>=e.length))return 16777216*e[t++]+65536*e[t++]+256*e[t++]+e[t++]},readUInt64BE:r=>{if(e&&!(t+7>=e.length))switch(r){case"always":return BigInt(`0x${e.hexSlice(t,t+=8)}`);case"maybe":if(e[t]>31)return BigInt(`0x${e.hexSlice(t,t+=8)}`);default:return 72057594037927940*e[t++]+281474976710656*e[t++]+1099511627776*e[t++]+4294967296*e[t++]+16777216*e[t++]+65536*e[t++]+256*e[t++]+e[t++]}},skip:r=>{e&&r>0&&(t+=r)},skipString:()=>{const n=r.readUInt32BE();if(void 0!==n)return t+=n,t<=e.length?n:void 0},readByte:()=>{if(e&&t<e.length)return e[t++]},readBool:()=>{if(e&&t<e.length)return!!e[t++]},readList:()=>{const e=r.readString(!0);if(void 0!==e)return e?e.split(","):[]},readString:(n,s)=>{"number"==typeof n&&(s=n,n=void 0);const i=r.readUInt32BE();if(void 0!==i&&!(e.length-t<i||"number"==typeof s&&i>s))return n?Buffer.isBuffer(n)?c(e,n,t,t+=i):e.utf8Slice(t,t+=i):l(e,t,t+=i)},readRaw:r=>{if(e)return"number"!=typeof r?l(e,t,t+=e.length-t):e.length-t>=r?l(e,t,t+=r):void 0}};return r}function h(e,t,r){const n=new Error(e);return"boolean"==typeof t?(r=t,n.level="protocol"):n.level=t||"protocol",n.fatal=!!r,n}function d(e,t,r){return e[r++]=t>>>24,e[r++]=t>>>16,e[r++]=t>>>8,e[r++]=t,r}const f=u();e.exports={bufferCopy:c,bufferSlice:l,FastBuffer:i,bufferFill:(e,t,r,n)=>o.call(e,t,r,n),makeError:h,doFatalError:(e,t,n,i)=>{let o;return void 0===s&&({DISCONNECT_REASON:s}=r(4963)),t instanceof Error?(o=t,i="number"!=typeof n?s.PROTOCOL_ERROR:n):o=h(t,n,!0),"number"!=typeof i&&(i=s.PROTOCOL_ERROR),e.disconnect(i),e._destruct(),e._onError(o),1/0},readUInt32BE:a,writeUInt32BE:d,writeUInt32LE:(e,t,r)=>(e[r++]=t,e[r++]=t>>>8,e[r++]=t>>>16,e[r++]=t>>>24,r),makeBufferParser:u,bufferParser:u(),readString:(e,t,r,n)=>{"number"==typeof r&&(n=r,r=void 0),void 0===t&&(t=0);const s=e.length-t;if(t<0||t>=e.length||s<4)return;const i=a(e,t);if(s<4+i||"number"==typeof n&&i>n)return;const o=(t+=4)+i;return e._pos=o,r?Buffer.isBuffer(r)?c(e,r,t,o):e.utf8Slice(t,o):l(e,t,o)},sigSSHToASN1:(e,t)=>{switch(t){case"ssh-dss":{if(e.length>40)return e;const t=new n.Writer;t.startSequence();let r=e.slice(0,20),s=e.slice(20);if(128&r[0]){const e=Buffer.allocUnsafe(21);e[0]=0,r.copy(e,1),r=e}else 0!==r[0]||128&r[1]||(r=r.slice(1));if(128&s[0]){const e=Buffer.allocUnsafe(21);e[0]=0,s.copy(e,1),s=e}else 0!==s[0]||128&s[1]||(s=s.slice(1));return t.writeBuffer(r,n.Integer),t.writeBuffer(s,n.Integer),t.endSequence(),t.buffer}case"ecdsa-sha2-nistp256":case"ecdsa-sha2-nistp384":case"ecdsa-sha2-nistp521":{f.init(e,0);const t=f.readString(),r=f.readString();if(f.clear(),void 0===t||void 0===r)return;const s=new n.Writer;return s.startSequence(),s.writeBuffer(t,n.Integer),s.writeBuffer(r,n.Integer),s.endSequence(),s.buffer}default:return e}},convertSignature:(e,t)=>{switch(t){case"ssh-dss":{if(e.length<=40)return e;const t=new n.Reader(e);t.readSequence();let r=t.readString(n.Integer,!0),s=t.readString(n.Integer,!0),i=0,o=0;if(r.length<20){const e=Buffer.allocUnsafe(20);e.set(r,1),r=e,r[0]=0}if(s.length<20){const e=Buffer.allocUnsafe(20);e.set(s,1),s=e,s[0]=0}r.length>20&&0===r[0]&&(i=1),s.length>20&&0===s[0]&&(o=1);const a=Buffer.allocUnsafe(r.length-i+(s.length-o));return c(r,a,i,r.length,0),c(s,a,o,s.length,r.length-i),a}case"ecdsa-sha2-nistp256":case"ecdsa-sha2-nistp384":case"ecdsa-sha2-nistp521":{if(0===e[0])return e;const t=new n.Reader(e);t.readSequence();const r=t.readString(n.Integer,!0),s=t.readString(n.Integer,!0);if(null===r||null===s)return;const i=Buffer.allocUnsafe(4+r.length+4+s.length);return d(i,r.length,0),i.set(r,4),d(i,s.length,4+r.length),i.set(s,8+r.length),i}}return e},sendPacket:(e,t,r)=>r||void 0===e._kexinit?(e._cipher.encrypt(t),!0):(void 0===e._queue&&(e._queue=[]),e._queue.push(t),e._debug&&e._debug("Outbound: ... packet queued"),!1)}},2797(e,t,r){"use strict";const{kMaxLength:n}=r(181),{createInflate:s,constants:{DEFLATE:i,INFLATE:o,Z_DEFAULT_CHUNK:a,Z_DEFAULT_COMPRESSION:c,Z_DEFAULT_MEMLEVEL:l,Z_DEFAULT_STRATEGY:u,Z_DEFAULT_WINDOWBITS:h,Z_PARTIAL_FLUSH:d}}=r(3106),f=s()._handle.constructor;function p(){throw new Error("Should not get here")}function _(e,t,r){const n=this._owner,s=new Error(e);s.errno=t,s.code=r,n._err=s}function g(e){e._handle&&(e._handle.close(),e._handle=null)}class m{constructor(e){const t=h,r=c,s=l,i=u;this._err=void 0,this._writeState=new Uint32Array(2),this._chunkSize=a,this._maxOutputLength=n,this._outBuffer=Buffer.allocUnsafe(this._chunkSize),this._outOffset=0,this._handle=new f(e),this._handle._owner=this,this._handle.onerror=_,this._handle.init(t,r,s,i,this._writeState,p,void 0)}writeSync(e,t){const r=this._handle;if(!r)throw new Error("Invalid Zlib instance");let n,s,i,o=e.length,a=this._chunkSize-this._outOffset,c=0,l=0;const u=this._writeState;let h=this._outBuffer,f=this._outOffset;const p=this._chunkSize;for(;;){if(r.writeSync(d,e,c,o,h,f,a),this._err)throw this._err;n=u[0],s=u[1];const t=o-s,_=a-n;if(_>0){const e=0===f&&_===h.length?h:h.slice(f,f+_);if(f+=_,i?void 0===i.push?i=[i,e]:i.push(e):i=e,l+=e.byteLength,l>this._maxOutputLength)throw g(this),new Error(`Output length exceeded maximum of ${this._maxOutputLength}`)}else if(0!==_)throw new Error("have should not go down");if((0===n||f>=p)&&(a=p,f=0,h=Buffer.allocUnsafe(p)),0!==n)break;c+=t,o=s}if(this._outBuffer=h,this._outOffset=f,0===l&&(i=Buffer.alloc(0)),t)return i.totalLen=l,i;if(void 0===i.push)return i;const _=Buffer.allocUnsafe(l);for(let e=0,t=0;e<i.length;++e){const r=i[e];_.set(r,t),t+=r.length}return _}}e.exports={PacketReader:class{cleanup(){}read(e){return e}},PacketWriter:class{constructor(e){this.allocStart=5,this.allocStartKEX=5,this._protocol=e}cleanup(){}alloc(e,t){return void 0===this._protocol._kexinit||t?this._protocol._cipher.allocPacket(e):Buffer.allocUnsafe(e)}finalize(e,t){return e}},ZlibPacketReader:class{constructor(){this._zlib=new m(o)}cleanup(){this._zlib&&g(this._zlib)}read(e){return this._zlib.writeSync(e,!1)}},ZlibPacketWriter:class{constructor(e){this.allocStart=0,this.allocStartKEX=0,this._protocol=e,this._zlib=new m(i)}cleanup(){this._zlib&&g(this._zlib)}alloc(e,t){return Buffer.allocUnsafe(e)}finalize(e,t){if(void 0===this._protocol._kexinit||t){const t=this._zlib.writeSync(e,!0),r=this._protocol._cipher.allocPacket(t.totalLen);if(void 0===t.push)r.set(t,5);else for(let e=0,n=5;e<t.length;++e){const s=t[e];r.set(s,n),n+=s.length}return r}return e}}}},2490(e,t,r){"use strict";const{Server:n}=r(9278),s=r(4434),{listenerCount:i}=s,{CHANNEL_OPEN_FAILURE:o,DEFAULT_CIPHER:a,DEFAULT_COMPRESSION:c,DEFAULT_KEX:l,DEFAULT_MAC:u,DEFAULT_SERVER_HOST_KEY:h,DISCONNECT_REASON:d,DISCONNECT_REASON_BY_VALUE:f,SUPPORTED_CIPHER:p,SUPPORTED_COMPRESSION:_,SUPPORTED_KEX:g,SUPPORTED_MAC:m,SUPPORTED_SERVER_HOST_KEY:y}=r(4963),{init:A}=r(2597),{KexInit:v}=r(7198),{parseKey:b}=r(614),w=r(7020),{SFTP:E}=r(5473),{writeUInt32BE:I}=r(4787),{Channel:S,MAX_WINDOW:P,PACKET_SIZE:k,windowAdjust:O,WINDOW_THRESHOLD:C}=r(634),{ChannelManager:R,generateAlgorithmList:B,isWritable:x,onChannelOpenFailure:T,onCHANNEL_CLOSE:N}=r(3952);class F extends s{constructor(e,t,r,n,s){super(),this.username=this.user=t,this.service=r,this.method=n,this._initialResponse=!1,this._finalResponse=!1,this._multistep=!1,this._cbfinal=(e,t,r)=>{this._finalResponse||(this._finalResponse=!0,s(this,e,t,r))},this._protocol=e}accept(){this._cleanup&&this._cleanup(),this._initialResponse=!0,this._cbfinal(!0)}reject(e,t){this._cleanup&&this._cleanup(),this._initialResponse=!0,this._cbfinal(!1,e,t)}}class M extends F{constructor(e,t,r,n,s,i){super(e,t,r,n,i),this._multistep=!0,this._cb=void 0,this._onInfoResponse=e=>{const t=this._cb;t&&(this._cb=void 0,t(e))},this.submethods=s,this.on("abort",()=>{this._cb&&this._cb(new Error("Authentication request aborted"))})}prompt(e,t,r,n){Array.isArray(e)||(e=[e]),"function"==typeof t?(n=t,t=r=void 0):"function"==typeof r?(n=r,r=void 0):"function"!=typeof n&&(n=void 0);for(let t=0;t<e.length;++t)"string"==typeof e[t]&&(e[t]={prompt:e[t],echo:!0});this._cb=n,this._initialResponse=!0,this._protocol.authInfoReq(t,r,e)}}class L extends F{constructor(e,t,r,n,s,i){super(e,t,r,n,i),this.key={algo:s.keyAlgo,data:s.key},this.hashAlgo=s.hashAlgo,this.signature=s.signature,this.blob=s.blob}accept(){this.signature?F.prototype.accept.call(this):(this._initialResponse=!0,this._protocol.authPKOK(this.key.algo,this.key.data))}}class U extends F{constructor(e,t,r,n,s,i){super(e,t,r,n,i),this.key={algo:s.keyAlgo,data:s.key},this.hashAlgo=s.hashAlgo,this.signature=s.signature,this.blob=s.blob,this.localHostname=s.localHostname,this.localUsername=s.localUsername}}class D extends F{constructor(e,t,r,n,s,i){super(e,t,r,n,i),this.password=s,this._changeCb=void 0}requestChange(e,t){if(this._changeCb)throw new Error("Change request already in progress");if("string"!=typeof e)throw new Error("prompt argument must be a string");if("function"!=typeof t)throw new Error("Callback argument must be a function");this._changeCb=t,this._protocol.authPasswdChg(e)}}class $ extends s{constructor(e,t,r){super(),this.type="session",this.subtype=void 0,this.server=!0,this._ending=!1,this._channel=void 0,this._chanInfo={type:"session",incoming:{id:r,window:P,packetSize:k,state:"open"},outgoing:{id:t.sender,window:t.window,packetSize:t.packetSize,state:"open"}}}}class j extends s{constructor(e,t){if(super(),"object"!=typeof e||null===e)throw new Error("Missing configuration object");const r=Object.create(null),s=[],i=e.hostKeys;if(!Array.isArray(i))throw new Error("hostKeys must be an array");const o="object"==typeof e.algorithms&&null!==e.algorithms?e.algorithms:{},d=B(o.serverHostKey,h,y);for(let e=0;e<i.length;++e){let t;if(t=Buffer.isBuffer(i[e])||"string"==typeof i[e]?b(i[e]):b(i[e].key,i[e].passphrase),t instanceof Error)throw new Error(`Cannot parse privateKey: ${t.message}`);if(Array.isArray(t)&&(t=t[0]),null===t.getPrivatePEM())throw new Error("privateKey value contains an invalid private key");if(!s.includes(t.type))if("ssh-rsa"===t.type){let e=d.indexOf("ssh-rsa");const n=d.indexOf("rsa-sha2-256"),i=d.indexOf("rsa-sha2-512");-1===e&&(e=1/0),[e,n,i].sort(Q).forEach(o=>{if(-1===o)return;let a;switch(o){case e:a="ssh-rsa";break;case n:a="rsa-sha2-256";break;case i:a="rsa-sha2-512";break;default:return}r[a]=t,s.push(a)})}else r[t.type]=t,s.push(t.type)}const f={kex:B(o.kex,l,g).concat(["kex-strict-s-v00@openssh.com"]),serverHostKey:s,cs:{cipher:B(o.cipher,a,p),mac:B(o.hmac,u,m),compress:B(o.compress,c,_),lang:[]},sc:void 0};f.sc=f.cs,"function"==typeof t&&this.on("connection",t);const A="function"==typeof e.debug?e.debug:void 0,w=e.ident?Buffer.from(e.ident):void 0,E=new v(f);this._srv=new n(t=>{if(this._connections>=this.maxConnections)return void t.destroy();let n;if(++this._connections,t.once("close",()=>{--this._connections}),A){const e=`[${process.hrtime().join(".")}] `;n=t=>{A(`${e}${t}`)}}new H(t,r,w,E,n,this,e)}).on("error",e=>{this.emit("error",e)}).on("listening",()=>{this.emit("listening")}).on("close",()=>{this.emit("close")}),this._connections=0,this.maxConnections=1/0}injectSocket(e){this._srv.emit("connection",e)}listen(...e){return this._srv.listen(...e),this}address(){return this._srv.address()}getConnections(e){return this._srv.getConnections(e),this}close(e){return this._srv.close(e),this}ref(){return this._srv.ref(),this}unref(){return this._srv.unref(),this}}j.KEEPALIVE_CLIENT_INTERVAL=15e3,j.KEEPALIVE_CLIENT_COUNT_MAX=3;class H extends s{constructor(e,t,r,n,s,a,c){super();let l,u,h,p=0,_=!1,g=[];const m=[];function y(e){}this._sock=e,this._chanMgr=new R(this),this._debug=s,this.noMoreSessions=!1,this.authenticated=!1,this.on("error",y);const v=s?(e,t,r)=>{s(`Debug output from client: ${JSON.stringify(r)}`)}:void 0,b="number"==typeof c.keepaliveInterval&&isFinite(c.keepaliveInterval)&&c.keepaliveInterval>0?c.keepaliveInterval:"number"==typeof j.KEEPALIVE_CLIENT_INTERVAL&&isFinite(j.KEEPALIVE_CLIENT_INTERVAL)&&j.KEEPALIVE_CLIENT_INTERVAL>0?j.KEEPALIVE_CLIENT_INTERVAL:-1,B="number"==typeof c.keepaliveCountMax&&isFinite(c.keepaliveCountMax)&&c.keepaliveCountMax>=0?c.keepaliveCountMax:"number"==typeof j.KEEPALIVE_CLIENT_COUNT_MAX&&isFinite(j.KEEPALIVE_CLIENT_COUNT_MAX)&&j.KEEPALIVE_CLIENT_COUNT_MAX>=0?j.KEEPALIVE_CLIENT_COUNT_MAX:-1;let H=0;-1!==b&&-1!==B&&(this.once("ready",()=>{const e=()=>{clearInterval(u)};this.on("close",e).on("end",e),u=setInterval(()=>{if(++H>B){clearInterval(u);const e=new Error("Keepalive timeout");e.level="client-timeout",this.emit("error",e),this.end()}else G.ping()},b)}),h=()=>{u&&u.refresh(),H=0});const G=this._protocol=new w({server:!0,hostKeys:t,ident:r,offer:n,onPacket:h,greeting:c.greeting,banner:c.banner,onWrite:t=>{x(e)&&e.write(t)},onError:t=>{G._destruct||e.removeAllListeners("data"),this.emit("error",t);try{e.end()}catch{}},onHeader:t=>{this.removeListener("error",y);const r={ip:e.remoteAddress,family:e.remoteFamily,port:e.remotePort,header:t};if(!a.emit("connection",this,r))return G.disconnect(d.BY_APPLICATION),void e.end();t.greeting&&this.emit("greeting",t.greeting)},onHandshakeComplete:e=>{++p>1&&this.emit("rekey"),this.emit("handshake",e)},debug:s,messageHandlers:{DEBUG:v,DISCONNECT:(t,r,n)=>{if(r!==d.BY_APPLICATION){n||void 0===(n=f[r])&&(n=`Unexpected disconnection reason: ${r}`);const e=new Error(n);e.code=r,this.emit("error",e)}e.end()},CHANNEL_OPEN:(e,t)=>{if("session"===t.type&&this.noMoreSessions||!this.authenticated){const e=o.ADMINISTRATIVELY_PROHIBITED;return G.channelOpenFail(t.sender,e)}let r,n,a=-1,c=!1;const l=()=>{c||(c=!0,void 0===r&&(r=-1===a?o.RESOURCE_SHORTAGE:o.CONNECT_FAILED),-1!==a&&this._chanMgr.remove(a),G.channelOpenFail(t.sender,r,""))},u=()=>(a=this._chanMgr.add(),-1===a&&(r=o.RESOURCE_SHORTAGE,s&&s("Automatic rejection of incoming channel open: no channels available")),-1!==a),h=t.data;switch(t.type){case"session":if(i(this,"session")&&u())return n=()=>{if(c)return;c=!0;const e=new $(this,t,a);return this._chanMgr.update(a,e),G.channelOpenConfirm(t.sender,a,P,k),e},void this.emit("session",n,l);break;case"direct-tcpip":if(i(this,"tcpip")&&u())return n=()=>{if(c)return;c=!0;const e={type:void 0,incoming:{id:a,window:P,packetSize:k,state:"open"},outgoing:{id:t.sender,window:t.window,packetSize:t.packetSize,state:"open"}},r=new S(this,e,{server:!0});return this._chanMgr.update(a,r),G.channelOpenConfirm(t.sender,a,P,k),r},void this.emit("tcpip",n,l,h);break;case"direct-streamlocal@openssh.com":if(i(this,"openssh.streamlocal")&&u())return n=()=>{if(c)return;c=!0;const e={type:void 0,incoming:{id:a,window:P,packetSize:k,state:"open"},outgoing:{id:t.sender,window:t.window,packetSize:t.packetSize,state:"open"}},r=new S(this,e,{server:!0});return this._chanMgr.update(a,r),G.channelOpenConfirm(t.sender,a,P,k),r},void this.emit("openssh.streamlocal",n,l,h);break;default:r=o.UNKNOWN_CHANNEL_TYPE,s&&s(`Automatic rejection of unsupported incoming channel open type: ${t.type}`)}void 0===r&&(r=o.ADMINISTRATIVELY_PROHIBITED,s&&s(`Automatic rejection of unexpected incoming channel open for: ${t.type}`)),l()},CHANNEL_OPEN_CONFIRMATION:(e,t)=>{const r=this._chanMgr.get(t.recipient);if("function"!=typeof r)return;const n={type:r.type,incoming:{id:t.recipient,window:P,packetSize:k,state:"open"},outgoing:{id:t.sender,window:t.window,packetSize:t.packetSize,state:"open"}},s=new S(this,n,{server:!0});this._chanMgr.update(t.recipient,s),r(void 0,s)},CHANNEL_OPEN_FAILURE:(e,t,r,n)=>{const s=this._chanMgr.get(t);"function"==typeof s&&T(this,t,{reason:r,description:n},s)},CHANNEL_DATA:(e,t,r)=>{let n=this._chanMgr.get(t);"object"==typeof n&&null!==n&&(n.constructor!==$||(n=n._channel,n))&&0!==n.incoming.window&&(n.incoming.window-=r.length,!1!==n.push(r)?n.incoming.window<=C&&O(n):n._waitChanDrain=!0)},CHANNEL_EXTENDED_DATA:(e,t,r,n)=>{},CHANNEL_WINDOW_ADJUST:(e,t,r)=>{let n=this._chanMgr.get(t);"object"==typeof n&&null!==n&&(n.constructor!==$||(n=n._channel,n))&&(n.outgoing.window+=r,n._waitWindow&&(n._waitWindow=!1,n._chunk?n._write(n._chunk,null,n._chunkcb):n._chunkcb?n._chunkcb():n._chunkErr?n.stderr._write(n._chunkErr,null,n._chunkcbErr):n._chunkcbErr&&n._chunkcbErr()))},CHANNEL_SUCCESS:(e,t)=>{let r=this._chanMgr.get(t);"object"==typeof r&&null!==r&&(r.constructor!==$||(r=r._channel,r))&&r._callbacks.length&&r._callbacks.shift()(!1)},CHANNEL_FAILURE:(e,t)=>{let r=this._chanMgr.get(t);"object"==typeof r&&null!==r&&(r.constructor!==$||(r=r._channel,r))&&r._callbacks.length&&r._callbacks.shift()(!0)},CHANNEL_REQUEST:(e,t,r,n,o)=>{const a=this._chanMgr.get(t);if("object"!=typeof a||null===a)return;let c,l,u=!1;if(a.constructor===$)if(n&&("shell"!==r&&"exec"!==r&&"subsystem"!==r&&(c=()=>{u||a._ending||a._channel||(u=!0,G.channelSuccess(a._chanInfo.outgoing.id))}),l=()=>{u||a._ending||a._channel||(u=!0,G.channelFailure(a._chanInfo.outgoing.id))}),a._ending)l&&l();else{switch(r){case"env":if(i(a,"env"))return void a.emit("env",c,l,{key:o.name,val:o.value});break;case"pty-req":if(i(a,"pty"))return void a.emit("pty",c,l,o);break;case"window-change":i(a,"window-change")?a.emit("window-change",c,l,o):l&&l();break;case"x11-req":if(i(a,"x11"))return void a.emit("x11",c,l,o);break;case"signal":if(i(a,"signal"))return void a.emit("signal",c,l,{name:o});break;case"auth-agent-req@openssh.com":if(i(a,"auth-agent"))return void a.emit("auth-agent",c,l);break;case"shell":if(i(a,"shell"))return c=()=>{if(u||a._ending||a._channel)return;u=!0,n&&G.channelSuccess(a._chanInfo.outgoing.id);const e=new S(this,a._chanInfo,{server:!0});return e.subtype=a.subtype=r,a._channel=e,e},void a.emit("shell",c,l);break;case"exec":if(i(a,"exec"))return c=()=>{if(u||a._ending||a._channel)return;u=!0,n&&G.channelSuccess(a._chanInfo.outgoing.id);const e=new S(this,a._chanInfo,{server:!0});return e.subtype=a.subtype=r,a._channel=e,e},void a.emit("exec",c,l,{command:o});break;case"subsystem":{let e="sftp"===o;if(c=()=>{if(u||a._ending||a._channel)return;let t;return u=!0,n&&G.channelSuccess(a._chanInfo.outgoing.id),e?t=new E(this,a._chanInfo,{server:!0,debug:s}):(t=new S(this,a._chanInfo,{server:!0}),t.subtype=a.subtype=`${r}:${o}`),a._channel=t,t},"sftp"===o){if(i(a,"sftp"))return void a.emit("sftp",c,l);e=!1}if(i(a,"subsystem"))return void a.emit("subsystem",c,l,{name:o});break}}s&&s(`Automatic rejection of incoming channel request: ${r}`),l&&l()}else n&&G.channelFailure(a.outgoing.id)},CHANNEL_EOF:(e,t)=>{let r=this._chanMgr.get(t);"object"==typeof r&&null!==r&&(r.constructor!==$||(r._ending||(r._ending=!0,r.emit("eof"),r.emit("end")),r=r._channel,r))&&"open"===r.incoming.state&&(r.incoming.state="eof",r.readable&&r.push(null))},CHANNEL_CLOSE:(e,t)=>{let r=this._chanMgr.get(t);"object"==typeof r&&null!==r&&(r.constructor!==$||(r._ending=!0,r.emit("close"),r=r._channel,r))&&N(this,t,r)},SERVICE_REQUEST:(t,r)=>{if(0===p||_||this.authenticated||"ssh-userauth"!==r)return G.disconnect(d.SERVICE_NOT_AVAILABLE),void e.end();_=!0,G.serviceAccept(r)},USERAUTH_REQUEST:(t,r,n,s,o)=>{if(0===p||this.authenticated||l&&(l.username!==r||l.service!==n)||"password"!==s&&"publickey"!==s&&"hostbased"!==s&&"keyboard-interactive"!==s&&"none"!==s||10===g.length)return G.disconnect(d.PROTOCOL_ERROR),void e.end();if("ssh-connection"!==n)return G.disconnect(d.SERVICE_NOT_AVAILABLE),void e.end();let a;switch(s){case"keyboard-interactive":a=new M(G,r,n,s,o,Q);break;case"publickey":a=new L(G,r,n,s,o,Q);break;case"hostbased":a=new U(G,r,n,s,o,Q);break;case"password":if(l&&l instanceof D&&l._changeCb){const e=l._changeCb;return l._changeCb=void 0,void e(o.newPassword)}a=new D(G,r,n,s,o,Q);break;case"none":a=new F(G,r,n,s,Q)}if(l){if(!l._initialResponse)return g.push(a);l._multistep&&!l._finalResponse&&(l._cleanup&&l._cleanup(),l.emit("abort"))}l=a,i(this,"authentication")?this.emit("authentication",l):l.reject()},USERAUTH_INFO_RESPONSE:(e,t)=>{l&&l instanceof M&&l._onInfoResponse(t)},GLOBAL_REQUEST:(e,t,r,n)=>{const s={type:null,buf:null};function o(e,t){s.type=e,s.buf=t,function(){for(;m.length>0&&m[0].type;){const e=m.shift();"SUCCESS"===e.type&&G.requestSuccess(e.buf),"FAILURE"===e.type&&G.requestFailure()}}()}if(r&&m.push(s),("tcpip-forward"===t||"cancel-tcpip-forward"===t||"no-more-sessions@openssh.com"===t||"streamlocal-forward@openssh.com"===t||"cancel-streamlocal-forward@openssh.com"===t)&&i(this,"request")&&this.authenticated){let e,s;if(r){let r=!1;e=e=>{if(r)return;let s;r=!0,"tcpip-forward"===t&&0===n.bindPort&&"number"==typeof e&&(s=Buffer.allocUnsafe(4),I(s,e,0)),o("SUCCESS",s)},s=()=>{r||(r=!0,o("FAILURE"))}}if("no-more-sessions@openssh.com"===t)return this.noMoreSessions=!0,void(e&&e());this.emit("request",e,s,t,n)}else r&&o("FAILURE")}}});e.pause(),A.then(()=>{G.start(),e.on("data",t=>{try{G.parse(t,0,t.length)}catch(t){this.emit("error",t);try{x(e)&&e.end()}catch{}}}),e.resume()}).catch(t=>{this.emit("error",t);try{x(e)&&e.end()}catch{}}),e.on("error",e=>{e.level="socket",this.emit("error",e)}).once("end",()=>{s&&s("Socket ended"),G.cleanup(),this.emit("end")}).once("close",()=>{s&&s("Socket closed"),G.cleanup(),this.emit("close");const e=new Error("No response from server");this._chanMgr.cleanup(e)});const Q=(e,t,r,n)=>{l!==e||this.authenticated||(t?(l=void 0,this.authenticated=!0,G.authSuccess(),g=[],this.emit("ready")):(G.authFailure(r,n),g.length&&(l=g.pop(),i(this,"authentication")?this.emit("authentication",l):l.reject())))}}end(){return this._sock&&x(this._sock)&&(this._protocol.disconnect(d.BY_APPLICATION),this._sock.end()),this}x11(e,t,r){return G(this,"x11",{originAddr:e,originPort:t},r),this}forwardOut(e,t,r,n,s){return G(this,"forwarded-tcpip",{boundAddr:e,boundPort:t,remoteAddr:r,remotePort:n},s),this}openssh_forwardOutStreamLocal(e,t){return G(this,"forwarded-streamlocal@openssh.com",{socketPath:e},t),this}rekey(e){let t;try{this._protocol.rekey()}catch(e){t=e}"function"==typeof e&&(t?process.nextTick(e,t):this.once("rekey",e))}setNoDelay(e){return this._sock&&"function"==typeof this._sock.setNoDelay&&this._sock.setNoDelay(e),this}}function G(e,t,r,n){const s=P,i=k;"function"==typeof r&&(n=r,r={});const o=(e,t)=>{n(e,t)};o.type=t;const a=e._chanMgr.add(o);if(-1!==a)switch(t){case"forwarded-tcpip":e._protocol.forwardedTcpip(a,s,i,r);break;case"x11":e._protocol.x11(a,s,i,r);break;case"forwarded-streamlocal@openssh.com":e._protocol.openssh_forwardedStreamLocal(a,s,i,r);break;default:throw new Error(`Unsupported channel type: ${t}`)}else n(new Error("No free channels available"))}function Q(e,t){return e-t}e.exports=j,e.exports.IncomingClient=H},3952(e,t,r){"use strict";const{SFTP:n}=r(5473),s=2**32-1;function i(e,t,r,n){if(e._chanMgr.remove(t),"function"!=typeof n)return;let s;r instanceof Error?s=r:"object"==typeof r&&null!==r?(s=new Error(`(SSH) Channel open failure: ${r.description}`),s.reason=r.reason):(s=new Error("(SSH) Channel open failure: server closed channel unexpectedly"),s.reason=""),n(s)}function o(e,t,r,s,o){if("function"==typeof r)return void i(e,t,s,r);if("object"!=typeof r||null===r)return;if(r.incoming&&"closed"===r.incoming.state)return;if(e._chanMgr.remove(t),r.server&&"Session"===r.constructor.name)return;r.incoming.state="closed",r.readable&&r.push(null),r.server?r.stderr.writable&&r.stderr.end():r.stderr.readable&&r.stderr.push(null),r.constructor===n||"open"!==r.outgoing.state&&"eof"!==r.outgoing.state||o||r.close(),"closing"===r.outgoing.state&&(r.outgoing.state="closed");const a=r._readableState,c=r._writableState;!c||c.ending||c.finished||o||r.end();const l=r._callbacks;r._callbacks=[];for(let e=0;e<l.length;++e)l[e](!0);if(r.server)!r.readable||r.destroyed||a&&a.endEmitted?r.emit("close"):r.once("end",()=>r.emit("close"));else{let e;switch(r.type){case"direct-streamlocal@openssh.com":case"direct-tcpip":e=()=>r.emit("close");break;default:{const t=r._exit;e=()=>{null===t.code?r.emit("close",t.code,t.signal,t.dump,t.desc):r.emit("close",t.code)}}}!r.readable||r.destroyed||a&&a.endEmitted?e():r.once("end",e);const t=r.stderr._readableState;!r.stderr.readable||r.stderr.destroyed||t&&t.endEmitted?r.stderr.emit("close"):r.stderr.once("end",()=>r.stderr.emit("close"))}}const a=(()=>{const e=Object.prototype.toString;return t=>"[object RegExp]"===e.call(t)})();e.exports={ChannelManager:class{constructor(e){this._client=e,this._channels={},this._cur=-1,this._count=0}add(e){let t;if(this._cur<s)t=++this._cur;else if(0===this._count)this._cur=0,t=0;else{const e=this._channels;for(let r=0;r<s;++r)if(void 0===e[r]){t=r;break}}return void 0===t?-1:(this._channels[t]=e||!0,++this._count,t)}update(e,t){if("number"!=typeof e||e<0||e>=s||!isFinite(e))throw new Error(`Invalid channel id: ${e}`);t&&this._channels[e]&&(this._channels[e]=t)}get(e){if("number"!=typeof e||e<0||e>=s||!isFinite(e))throw new Error(`Invalid channel id: ${e}`);return this._channels[e]}remove(e){if("number"!=typeof e||e<0||e>=s||!isFinite(e))throw new Error(`Invalid channel id: ${e}`);this._channels[e]&&(delete this._channels[e],this._count&&--this._count)}cleanup(e){const t=this._channels;this._channels={},this._cur=-1,this._count=0;const r=Object.keys(t),n=this._client;for(let s=0;s<r.length;++s){const i=+r[s],a=t[i];o(n,i,a._channel||a,e,!0)}}},generateAlgorithmList:function(e,t,r){if(Array.isArray(e)&&e.length>0){for(let t=0;t<e.length;++t)if(-1===r.indexOf(e[t]))throw new Error(`Unsupported algorithm: ${e[t]}`);return e}if("object"==typeof e&&null!==e){const n=Object.keys(e);let s=t;for(let i=0;i<n.length;++i){const o=n[i];let c=e[o];switch(o){case"append":if(Array.isArray(c)||(c=[c]),Array.isArray(c))for(let e=0;e<c.length;++e){const n=c[e];if("string"==typeof n){if(!n||-1!==s.indexOf(n))continue;if(-1===r.indexOf(n))throw new Error(`Unsupported algorithm: ${n}`);s===t&&(s=s.slice()),s.push(n)}else if(a(n))for(let e=0;e<r.length;++e){const i=r[e];if(n.test(i)){if(-1!==s.indexOf(i))continue;s===t&&(s=s.slice()),s.push(i)}}}break;case"prepend":if(Array.isArray(c)||(c=[c]),Array.isArray(c))for(let e=c.length;e>=0;--e){const n=c[e];if("string"==typeof n){if(!n||-1!==s.indexOf(n))continue;if(-1===r.indexOf(n))throw new Error(`Unsupported algorithm: ${n}`);s===t&&(s=s.slice()),s.unshift(n)}else if(a(n))for(let e=r.length;e>=0;--e){const i=r[e];if(n.test(i)){if(-1!==s.indexOf(i))continue;s===t&&(s=s.slice()),s.unshift(i)}}}break;case"remove":if(Array.isArray(c)||(c=[c]),Array.isArray(c))for(let e=0;e<c.length;++e){const r=c[e];if("string"==typeof r){if(!r)continue;const e=s.indexOf(r);if(-1===e)continue;s===t&&(s=s.slice()),s.splice(e,1)}else if(a(r))for(let e=0;e<s.length;++e)r.test(s[e])&&(s===t&&(s=s.slice()),s.splice(e,1),--e)}}}return s}return t},onChannelOpenFailure:i,onCHANNEL_CLOSE:o,isWritable:e=>e&&e.writable&&e._readableState&&!1===e._readableState.ended}},9463(e,t,r){!function(e){"use strict";var t=function(e){var t,r=new Float64Array(16);if(e)for(t=0;t<e.length;t++)r[t]=e[t];return r},n=function(){throw new Error("no PRNG")},s=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var o=t(),a=t([1]),c=t([56129,1]),l=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),u=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),h=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),d=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),f=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function p(e,t,r,n){e[t]=r>>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function _(e,t,r,n,s){var i,o=0;for(i=0;i<s;i++)o|=e[t+i]^r[n+i];return(1&o-1>>>8)-1}function g(e,t,r,n){return _(e,t,r,n,16)}function m(e,t,r,n){return _(e,t,r,n,32)}function y(e,t,r,n){!function(e,t,r,n){for(var s,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,o=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,a=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,c=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,l=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,u=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,h=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,d=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,f=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,p=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,_=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,g=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,m=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,y=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,A=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,v=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,b=i,w=o,E=a,I=c,S=l,P=u,k=h,O=d,C=f,R=p,B=_,x=g,T=m,N=y,F=A,M=v,L=0;L<20;L+=2)b^=(s=(T^=(s=(C^=(s=(S^=(s=b+T|0)<<7|s>>>25)+b|0)<<9|s>>>23)+S|0)<<13|s>>>19)+C|0)<<18|s>>>14,P^=(s=(w^=(s=(N^=(s=(R^=(s=P+w|0)<<7|s>>>25)+P|0)<<9|s>>>23)+R|0)<<13|s>>>19)+N|0)<<18|s>>>14,B^=(s=(k^=(s=(E^=(s=(F^=(s=B+k|0)<<7|s>>>25)+B|0)<<9|s>>>23)+F|0)<<13|s>>>19)+E|0)<<18|s>>>14,M^=(s=(x^=(s=(O^=(s=(I^=(s=M+x|0)<<7|s>>>25)+M|0)<<9|s>>>23)+I|0)<<13|s>>>19)+O|0)<<18|s>>>14,b^=(s=(I^=(s=(E^=(s=(w^=(s=b+I|0)<<7|s>>>25)+b|0)<<9|s>>>23)+w|0)<<13|s>>>19)+E|0)<<18|s>>>14,P^=(s=(S^=(s=(O^=(s=(k^=(s=P+S|0)<<7|s>>>25)+P|0)<<9|s>>>23)+k|0)<<13|s>>>19)+O|0)<<18|s>>>14,B^=(s=(R^=(s=(C^=(s=(x^=(s=B+R|0)<<7|s>>>25)+B|0)<<9|s>>>23)+x|0)<<13|s>>>19)+C|0)<<18|s>>>14,M^=(s=(F^=(s=(N^=(s=(T^=(s=M+F|0)<<7|s>>>25)+M|0)<<9|s>>>23)+T|0)<<13|s>>>19)+N|0)<<18|s>>>14;b=b+i|0,w=w+o|0,E=E+a|0,I=I+c|0,S=S+l|0,P=P+u|0,k=k+h|0,O=O+d|0,C=C+f|0,R=R+p|0,B=B+_|0,x=x+g|0,T=T+m|0,N=N+y|0,F=F+A|0,M=M+v|0,e[0]=b>>>0&255,e[1]=b>>>8&255,e[2]=b>>>16&255,e[3]=b>>>24&255,e[4]=w>>>0&255,e[5]=w>>>8&255,e[6]=w>>>16&255,e[7]=w>>>24&255,e[8]=E>>>0&255,e[9]=E>>>8&255,e[10]=E>>>16&255,e[11]=E>>>24&255,e[12]=I>>>0&255,e[13]=I>>>8&255,e[14]=I>>>16&255,e[15]=I>>>24&255,e[16]=S>>>0&255,e[17]=S>>>8&255,e[18]=S>>>16&255,e[19]=S>>>24&255,e[20]=P>>>0&255,e[21]=P>>>8&255,e[22]=P>>>16&255,e[23]=P>>>24&255,e[24]=k>>>0&255,e[25]=k>>>8&255,e[26]=k>>>16&255,e[27]=k>>>24&255,e[28]=O>>>0&255,e[29]=O>>>8&255,e[30]=O>>>16&255,e[31]=O>>>24&255,e[32]=C>>>0&255,e[33]=C>>>8&255,e[34]=C>>>16&255,e[35]=C>>>24&255,e[36]=R>>>0&255,e[37]=R>>>8&255,e[38]=R>>>16&255,e[39]=R>>>24&255,e[40]=B>>>0&255,e[41]=B>>>8&255,e[42]=B>>>16&255,e[43]=B>>>24&255,e[44]=x>>>0&255,e[45]=x>>>8&255,e[46]=x>>>16&255,e[47]=x>>>24&255,e[48]=T>>>0&255,e[49]=T>>>8&255,e[50]=T>>>16&255,e[51]=T>>>24&255,e[52]=N>>>0&255,e[53]=N>>>8&255,e[54]=N>>>16&255,e[55]=N>>>24&255,e[56]=F>>>0&255,e[57]=F>>>8&255,e[58]=F>>>16&255,e[59]=F>>>24&255,e[60]=M>>>0&255,e[61]=M>>>8&255,e[62]=M>>>16&255,e[63]=M>>>24&255}(e,t,r,n)}function A(e,t,r,n){!function(e,t,r,n){for(var s,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,o=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,a=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,c=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,l=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,u=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,h=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,d=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,f=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,p=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,_=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,g=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,m=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,y=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,A=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,v=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,b=0;b<20;b+=2)i^=(s=(m^=(s=(f^=(s=(l^=(s=i+m|0)<<7|s>>>25)+i|0)<<9|s>>>23)+l|0)<<13|s>>>19)+f|0)<<18|s>>>14,u^=(s=(o^=(s=(y^=(s=(p^=(s=u+o|0)<<7|s>>>25)+u|0)<<9|s>>>23)+p|0)<<13|s>>>19)+y|0)<<18|s>>>14,_^=(s=(h^=(s=(a^=(s=(A^=(s=_+h|0)<<7|s>>>25)+_|0)<<9|s>>>23)+A|0)<<13|s>>>19)+a|0)<<18|s>>>14,v^=(s=(g^=(s=(d^=(s=(c^=(s=v+g|0)<<7|s>>>25)+v|0)<<9|s>>>23)+c|0)<<13|s>>>19)+d|0)<<18|s>>>14,i^=(s=(c^=(s=(a^=(s=(o^=(s=i+c|0)<<7|s>>>25)+i|0)<<9|s>>>23)+o|0)<<13|s>>>19)+a|0)<<18|s>>>14,u^=(s=(l^=(s=(d^=(s=(h^=(s=u+l|0)<<7|s>>>25)+u|0)<<9|s>>>23)+h|0)<<13|s>>>19)+d|0)<<18|s>>>14,_^=(s=(p^=(s=(f^=(s=(g^=(s=_+p|0)<<7|s>>>25)+_|0)<<9|s>>>23)+g|0)<<13|s>>>19)+f|0)<<18|s>>>14,v^=(s=(A^=(s=(y^=(s=(m^=(s=v+A|0)<<7|s>>>25)+v|0)<<9|s>>>23)+m|0)<<13|s>>>19)+y|0)<<18|s>>>14;e[0]=i>>>0&255,e[1]=i>>>8&255,e[2]=i>>>16&255,e[3]=i>>>24&255,e[4]=u>>>0&255,e[5]=u>>>8&255,e[6]=u>>>16&255,e[7]=u>>>24&255,e[8]=_>>>0&255,e[9]=_>>>8&255,e[10]=_>>>16&255,e[11]=_>>>24&255,e[12]=v>>>0&255,e[13]=v>>>8&255,e[14]=v>>>16&255,e[15]=v>>>24&255,e[16]=h>>>0&255,e[17]=h>>>8&255,e[18]=h>>>16&255,e[19]=h>>>24&255,e[20]=d>>>0&255,e[21]=d>>>8&255,e[22]=d>>>16&255,e[23]=d>>>24&255,e[24]=f>>>0&255,e[25]=f>>>8&255,e[26]=f>>>16&255,e[27]=f>>>24&255,e[28]=p>>>0&255,e[29]=p>>>8&255,e[30]=p>>>16&255,e[31]=p>>>24&255}(e,t,r,n)}var v=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function b(e,t,r,n,s,i,o){var a,c,l=new Uint8Array(16),u=new Uint8Array(64);for(c=0;c<16;c++)l[c]=0;for(c=0;c<8;c++)l[c]=i[c];for(;s>=64;){for(y(u,l,o,v),c=0;c<64;c++)e[t+c]=r[n+c]^u[c];for(a=1,c=8;c<16;c++)a=a+(255&l[c])|0,l[c]=255&a,a>>>=8;s-=64,t+=64,n+=64}if(s>0)for(y(u,l,o,v),c=0;c<s;c++)e[t+c]=r[n+c]^u[c];return 0}function w(e,t,r,n,s){var i,o,a=new Uint8Array(16),c=new Uint8Array(64);for(o=0;o<16;o++)a[o]=0;for(o=0;o<8;o++)a[o]=n[o];for(;r>=64;){for(y(c,a,s,v),o=0;o<64;o++)e[t+o]=c[o];for(i=1,o=8;o<16;o++)i=i+(255&a[o])|0,a[o]=255&i,i>>>=8;r-=64,t+=64}if(r>0)for(y(c,a,s,v),o=0;o<r;o++)e[t+o]=c[o];return 0}function E(e,t,r,n,s){var i=new Uint8Array(32);A(i,n,s,v);for(var o=new Uint8Array(8),a=0;a<8;a++)o[a]=n[a+16];return w(e,t,r,o,i)}function I(e,t,r,n,s,i,o){var a=new Uint8Array(32);A(a,i,o,v);for(var c=new Uint8Array(8),l=0;l<8;l++)c[l]=i[l+16];return b(e,t,r,n,s,c,a)}var S=function(e){var t,r,n,s,i,o,a,c;this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0,t=255&e[0]|(255&e[1])<<8,this.r[0]=8191&t,r=255&e[2]|(255&e[3])<<8,this.r[1]=8191&(t>>>13|r<<3),n=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(r>>>10|n<<6),s=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(n>>>7|s<<9),i=255&e[8]|(255&e[9])<<8,this.r[4]=255&(s>>>4|i<<12),this.r[5]=i>>>1&8190,o=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(i>>>14|o<<2),a=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(o>>>11|a<<5),c=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function P(e,t,r,n,s,i){var o=new S(i);return o.update(r,n,s),o.finish(e,t),0}function k(e,t,r,n,s,i){var o=new Uint8Array(16);return P(o,0,r,n,s,i),g(e,t,o,0)}function O(e,t,r,n,s){var i;if(r<32)return-1;for(I(e,0,t,0,r,n,s),P(e,16,e,32,r-32,e),i=0;i<16;i++)e[i]=0;return 0}function C(e,t,r,n,s){var i,o=new Uint8Array(32);if(r<32)return-1;if(E(o,0,32,n,s),0!==k(t,16,t,32,r-32,o))return-1;for(I(e,0,t,0,r,n,s),i=0;i<32;i++)e[i]=0;return 0}function R(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function B(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function x(e,t,r){for(var n,s=~(r-1),i=0;i<16;i++)n=s&(e[i]^t[i]),e[i]^=n,t[i]^=n}function T(e,r){var n,s,i,o=t(),a=t();for(n=0;n<16;n++)a[n]=r[n];for(B(a),B(a),B(a),s=0;s<2;s++){for(o[0]=a[0]-65517,n=1;n<15;n++)o[n]=a[n]-65535-(o[n-1]>>16&1),o[n-1]&=65535;o[15]=a[15]-32767-(o[14]>>16&1),i=o[15]>>16&1,o[14]&=65535,x(a,o,1-i)}for(n=0;n<16;n++)e[2*n]=255&a[n],e[2*n+1]=a[n]>>8}function N(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return T(r,e),T(n,t),m(r,0,n,0)}function F(e){var t=new Uint8Array(32);return T(t,e),1&t[0]}function M(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function L(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function U(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function D(e,t,r){var n,s,i=0,o=0,a=0,c=0,l=0,u=0,h=0,d=0,f=0,p=0,_=0,g=0,m=0,y=0,A=0,v=0,b=0,w=0,E=0,I=0,S=0,P=0,k=0,O=0,C=0,R=0,B=0,x=0,T=0,N=0,F=0,M=r[0],L=r[1],U=r[2],D=r[3],$=r[4],j=r[5],H=r[6],G=r[7],Q=r[8],q=r[9],W=r[10],K=r[11],X=r[12],z=r[13],Y=r[14],J=r[15];i+=(n=t[0])*M,o+=n*L,a+=n*U,c+=n*D,l+=n*$,u+=n*j,h+=n*H,d+=n*G,f+=n*Q,p+=n*q,_+=n*W,g+=n*K,m+=n*X,y+=n*z,A+=n*Y,v+=n*J,o+=(n=t[1])*M,a+=n*L,c+=n*U,l+=n*D,u+=n*$,h+=n*j,d+=n*H,f+=n*G,p+=n*Q,_+=n*q,g+=n*W,m+=n*K,y+=n*X,A+=n*z,v+=n*Y,b+=n*J,a+=(n=t[2])*M,c+=n*L,l+=n*U,u+=n*D,h+=n*$,d+=n*j,f+=n*H,p+=n*G,_+=n*Q,g+=n*q,m+=n*W,y+=n*K,A+=n*X,v+=n*z,b+=n*Y,w+=n*J,c+=(n=t[3])*M,l+=n*L,u+=n*U,h+=n*D,d+=n*$,f+=n*j,p+=n*H,_+=n*G,g+=n*Q,m+=n*q,y+=n*W,A+=n*K,v+=n*X,b+=n*z,w+=n*Y,E+=n*J,l+=(n=t[4])*M,u+=n*L,h+=n*U,d+=n*D,f+=n*$,p+=n*j,_+=n*H,g+=n*G,m+=n*Q,y+=n*q,A+=n*W,v+=n*K,b+=n*X,w+=n*z,E+=n*Y,I+=n*J,u+=(n=t[5])*M,h+=n*L,d+=n*U,f+=n*D,p+=n*$,_+=n*j,g+=n*H,m+=n*G,y+=n*Q,A+=n*q,v+=n*W,b+=n*K,w+=n*X,E+=n*z,I+=n*Y,S+=n*J,h+=(n=t[6])*M,d+=n*L,f+=n*U,p+=n*D,_+=n*$,g+=n*j,m+=n*H,y+=n*G,A+=n*Q,v+=n*q,b+=n*W,w+=n*K,E+=n*X,I+=n*z,S+=n*Y,P+=n*J,d+=(n=t[7])*M,f+=n*L,p+=n*U,_+=n*D,g+=n*$,m+=n*j,y+=n*H,A+=n*G,v+=n*Q,b+=n*q,w+=n*W,E+=n*K,I+=n*X,S+=n*z,P+=n*Y,k+=n*J,f+=(n=t[8])*M,p+=n*L,_+=n*U,g+=n*D,m+=n*$,y+=n*j,A+=n*H,v+=n*G,b+=n*Q,w+=n*q,E+=n*W,I+=n*K,S+=n*X,P+=n*z,k+=n*Y,O+=n*J,p+=(n=t[9])*M,_+=n*L,g+=n*U,m+=n*D,y+=n*$,A+=n*j,v+=n*H,b+=n*G,w+=n*Q,E+=n*q,I+=n*W,S+=n*K,P+=n*X,k+=n*z,O+=n*Y,C+=n*J,_+=(n=t[10])*M,g+=n*L,m+=n*U,y+=n*D,A+=n*$,v+=n*j,b+=n*H,w+=n*G,E+=n*Q,I+=n*q,S+=n*W,P+=n*K,k+=n*X,O+=n*z,C+=n*Y,R+=n*J,g+=(n=t[11])*M,m+=n*L,y+=n*U,A+=n*D,v+=n*$,b+=n*j,w+=n*H,E+=n*G,I+=n*Q,S+=n*q,P+=n*W,k+=n*K,O+=n*X,C+=n*z,R+=n*Y,B+=n*J,m+=(n=t[12])*M,y+=n*L,A+=n*U,v+=n*D,b+=n*$,w+=n*j,E+=n*H,I+=n*G,S+=n*Q,P+=n*q,k+=n*W,O+=n*K,C+=n*X,R+=n*z,B+=n*Y,x+=n*J,y+=(n=t[13])*M,A+=n*L,v+=n*U,b+=n*D,w+=n*$,E+=n*j,I+=n*H,S+=n*G,P+=n*Q,k+=n*q,O+=n*W,C+=n*K,R+=n*X,B+=n*z,x+=n*Y,T+=n*J,A+=(n=t[14])*M,v+=n*L,b+=n*U,w+=n*D,E+=n*$,I+=n*j,S+=n*H,P+=n*G,k+=n*Q,O+=n*q,C+=n*W,R+=n*K,B+=n*X,x+=n*z,T+=n*Y,N+=n*J,v+=(n=t[15])*M,o+=38*(w+=n*U),a+=38*(E+=n*D),c+=38*(I+=n*$),l+=38*(S+=n*j),u+=38*(P+=n*H),h+=38*(k+=n*G),d+=38*(O+=n*Q),f+=38*(C+=n*q),p+=38*(R+=n*W),_+=38*(B+=n*K),g+=38*(x+=n*X),m+=38*(T+=n*z),y+=38*(N+=n*Y),A+=38*(F+=n*J),i=(n=(i+=38*(b+=n*L))+(s=1)+65535)-65536*(s=Math.floor(n/65536)),o=(n=o+s+65535)-65536*(s=Math.floor(n/65536)),a=(n=a+s+65535)-65536*(s=Math.floor(n/65536)),c=(n=c+s+65535)-65536*(s=Math.floor(n/65536)),l=(n=l+s+65535)-65536*(s=Math.floor(n/65536)),u=(n=u+s+65535)-65536*(s=Math.floor(n/65536)),h=(n=h+s+65535)-65536*(s=Math.floor(n/65536)),d=(n=d+s+65535)-65536*(s=Math.floor(n/65536)),f=(n=f+s+65535)-65536*(s=Math.floor(n/65536)),p=(n=p+s+65535)-65536*(s=Math.floor(n/65536)),_=(n=_+s+65535)-65536*(s=Math.floor(n/65536)),g=(n=g+s+65535)-65536*(s=Math.floor(n/65536)),m=(n=m+s+65535)-65536*(s=Math.floor(n/65536)),y=(n=y+s+65535)-65536*(s=Math.floor(n/65536)),A=(n=A+s+65535)-65536*(s=Math.floor(n/65536)),v=(n=v+s+65535)-65536*(s=Math.floor(n/65536)),i=(n=(i+=s-1+37*(s-1))+(s=1)+65535)-65536*(s=Math.floor(n/65536)),o=(n=o+s+65535)-65536*(s=Math.floor(n/65536)),a=(n=a+s+65535)-65536*(s=Math.floor(n/65536)),c=(n=c+s+65535)-65536*(s=Math.floor(n/65536)),l=(n=l+s+65535)-65536*(s=Math.floor(n/65536)),u=(n=u+s+65535)-65536*(s=Math.floor(n/65536)),h=(n=h+s+65535)-65536*(s=Math.floor(n/65536)),d=(n=d+s+65535)-65536*(s=Math.floor(n/65536)),f=(n=f+s+65535)-65536*(s=Math.floor(n/65536)),p=(n=p+s+65535)-65536*(s=Math.floor(n/65536)),_=(n=_+s+65535)-65536*(s=Math.floor(n/65536)),g=(n=g+s+65535)-65536*(s=Math.floor(n/65536)),m=(n=m+s+65535)-65536*(s=Math.floor(n/65536)),y=(n=y+s+65535)-65536*(s=Math.floor(n/65536)),A=(n=A+s+65535)-65536*(s=Math.floor(n/65536)),v=(n=v+s+65535)-65536*(s=Math.floor(n/65536)),i+=s-1+37*(s-1),e[0]=i,e[1]=o,e[2]=a,e[3]=c,e[4]=l,e[5]=u,e[6]=h,e[7]=d,e[8]=f,e[9]=p,e[10]=_,e[11]=g,e[12]=m,e[13]=y,e[14]=A,e[15]=v}function $(e,t){D(e,t,t)}function j(e,r){var n,s=t();for(n=0;n<16;n++)s[n]=r[n];for(n=253;n>=0;n--)$(s,s),2!==n&&4!==n&&D(s,s,r);for(n=0;n<16;n++)e[n]=s[n]}function H(e,r,n){var s,i,o=new Uint8Array(32),a=new Float64Array(80),l=t(),u=t(),h=t(),d=t(),f=t(),p=t();for(i=0;i<31;i++)o[i]=r[i];for(o[31]=127&r[31]|64,o[0]&=248,M(a,n),i=0;i<16;i++)u[i]=a[i],d[i]=l[i]=h[i]=0;for(l[0]=d[0]=1,i=254;i>=0;--i)x(l,u,s=o[i>>>3]>>>(7&i)&1),x(h,d,s),L(f,l,h),U(l,l,h),L(h,u,d),U(u,u,d),$(d,f),$(p,l),D(l,h,l),D(h,u,f),L(f,l,h),U(l,l,h),$(u,l),U(h,d,p),D(l,h,c),L(l,l,d),D(h,h,l),D(l,d,p),D(d,u,a),$(u,f),x(l,u,s),x(h,d,s);for(i=0;i<16;i++)a[i+16]=l[i],a[i+32]=h[i],a[i+48]=u[i],a[i+64]=d[i];var _=a.subarray(32),g=a.subarray(16);return j(_,_),D(g,g,_),T(e,g),0}function G(e,t){return H(e,t,i)}function Q(e,t){return n(t,32),G(e,t)}function q(e,t,r){var n=new Uint8Array(32);return H(n,r,t),A(e,s,n,v)}S.prototype.blocks=function(e,t,r){for(var n,s,i,o,a,c,l,u,h,d,f,p,_,g,m,y,A,v,b,w=this.fin?0:2048,E=this.h[0],I=this.h[1],S=this.h[2],P=this.h[3],k=this.h[4],O=this.h[5],C=this.h[6],R=this.h[7],B=this.h[8],x=this.h[9],T=this.r[0],N=this.r[1],F=this.r[2],M=this.r[3],L=this.r[4],U=this.r[5],D=this.r[6],$=this.r[7],j=this.r[8],H=this.r[9];r>=16;)d=h=0,d+=(E+=8191&(n=255&e[t+0]|(255&e[t+1])<<8))*T,d+=(I+=8191&(n>>>13|(s=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*H),d+=(S+=8191&(s>>>10|(i=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*j),d+=(P+=8191&(i>>>7|(o=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*$),h=(d+=(k+=8191&(o>>>4|(a=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*D))>>>13,d&=8191,d+=(O+=a>>>1&8191)*(5*U),d+=(C+=8191&(a>>>14|(c=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*L),d+=(R+=8191&(c>>>11|(l=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*M),d+=(B+=8191&(l>>>8|(u=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*F),f=h+=(d+=(x+=u>>>5|w)*(5*N))>>>13,f+=E*N,f+=I*T,f+=S*(5*H),f+=P*(5*j),h=(f+=k*(5*$))>>>13,f&=8191,f+=O*(5*D),f+=C*(5*U),f+=R*(5*L),f+=B*(5*M),h+=(f+=x*(5*F))>>>13,f&=8191,p=h,p+=E*F,p+=I*N,p+=S*T,p+=P*(5*H),h=(p+=k*(5*j))>>>13,p&=8191,p+=O*(5*$),p+=C*(5*D),p+=R*(5*U),p+=B*(5*L),_=h+=(p+=x*(5*M))>>>13,_+=E*M,_+=I*F,_+=S*N,_+=P*T,h=(_+=k*(5*H))>>>13,_&=8191,_+=O*(5*j),_+=C*(5*$),_+=R*(5*D),_+=B*(5*U),g=h+=(_+=x*(5*L))>>>13,g+=E*L,g+=I*M,g+=S*F,g+=P*N,h=(g+=k*T)>>>13,g&=8191,g+=O*(5*H),g+=C*(5*j),g+=R*(5*$),g+=B*(5*D),m=h+=(g+=x*(5*U))>>>13,m+=E*U,m+=I*L,m+=S*M,m+=P*F,h=(m+=k*N)>>>13,m&=8191,m+=O*T,m+=C*(5*H),m+=R*(5*j),m+=B*(5*$),y=h+=(m+=x*(5*D))>>>13,y+=E*D,y+=I*U,y+=S*L,y+=P*M,h=(y+=k*F)>>>13,y&=8191,y+=O*N,y+=C*T,y+=R*(5*H),y+=B*(5*j),A=h+=(y+=x*(5*$))>>>13,A+=E*$,A+=I*D,A+=S*U,A+=P*L,h=(A+=k*M)>>>13,A&=8191,A+=O*F,A+=C*N,A+=R*T,A+=B*(5*H),v=h+=(A+=x*(5*j))>>>13,v+=E*j,v+=I*$,v+=S*D,v+=P*U,h=(v+=k*L)>>>13,v&=8191,v+=O*M,v+=C*F,v+=R*N,v+=B*T,b=h+=(v+=x*(5*H))>>>13,b+=E*H,b+=I*j,b+=S*$,b+=P*D,h=(b+=k*U)>>>13,b&=8191,b+=O*L,b+=C*M,b+=R*F,b+=B*N,E=d=8191&(h=(h=((h+=(b+=x*T)>>>13)<<2)+h|0)+(d&=8191)|0),I=f+=h>>>=13,S=p&=8191,P=_&=8191,k=g&=8191,O=m&=8191,C=y&=8191,R=A&=8191,B=v&=8191,x=b&=8191,t+=16,r-=16;this.h[0]=E,this.h[1]=I,this.h[2]=S,this.h[3]=P,this.h[4]=k,this.h[5]=O,this.h[6]=C,this.h[7]=R,this.h[8]=B,this.h[9]=x},S.prototype.finish=function(e,t){var r,n,s,i,o=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=r,r=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*r,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,o[0]=this.h[0]+5,r=o[0]>>>13,o[0]&=8191,i=1;i<10;i++)o[i]=this.h[i]+r,r=o[i]>>>13,o[i]&=8191;for(o[9]-=8192,n=(1^r)-1,i=0;i<10;i++)o[i]&=n;for(n=~n,i=0;i<10;i++)this.h[i]=this.h[i]&n|o[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),s=this.h[0]+this.pad[0],this.h[0]=65535&s,i=1;i<8;i++)s=(this.h[i]+this.pad[i]|0)+(s>>>16)|0,this.h[i]=65535&s;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},S.prototype.update=function(e,t,r){var n,s;if(this.leftover){for((s=16-this.leftover)>r&&(s=r),n=0;n<s;n++)this.buffer[this.leftover+n]=e[t+n];if(r-=s,t+=s,this.leftover+=s,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(r>=16&&(s=r-r%16,this.blocks(e,t,s),t+=s,r-=s),r){for(n=0;n<r;n++)this.buffer[this.leftover+n]=e[t+n];this.leftover+=r}};var W=O,K=C,X=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function z(e,t,r,n){for(var s,i,o,a,c,l,u,h,d,f,p,_,g,m,y,A,v,b,w,E,I,S,P,k,O,C,R=new Int32Array(16),B=new Int32Array(16),x=e[0],T=e[1],N=e[2],F=e[3],M=e[4],L=e[5],U=e[6],D=e[7],$=t[0],j=t[1],H=t[2],G=t[3],Q=t[4],q=t[5],W=t[6],K=t[7],z=0;n>=128;){for(w=0;w<16;w++)E=8*w+z,R[w]=r[E+0]<<24|r[E+1]<<16|r[E+2]<<8|r[E+3],B[w]=r[E+4]<<24|r[E+5]<<16|r[E+6]<<8|r[E+7];for(w=0;w<80;w++)if(s=x,i=T,o=N,a=F,c=M,l=L,u=U,d=$,f=j,p=H,_=G,g=Q,m=q,y=W,P=65535&(S=K),k=S>>>16,O=65535&(I=D),C=I>>>16,P+=65535&(S=(Q>>>14|M<<18)^(Q>>>18|M<<14)^(M>>>9|Q<<23)),k+=S>>>16,O+=65535&(I=(M>>>14|Q<<18)^(M>>>18|Q<<14)^(Q>>>9|M<<23)),C+=I>>>16,P+=65535&(S=Q&q^~Q&W),k+=S>>>16,O+=65535&(I=M&L^~M&U),C+=I>>>16,P+=65535&(S=X[2*w+1]),k+=S>>>16,O+=65535&(I=X[2*w]),C+=I>>>16,I=R[w%16],k+=(S=B[w%16])>>>16,O+=65535&I,C+=I>>>16,O+=(k+=(P+=65535&S)>>>16)>>>16,P=65535&(S=b=65535&P|k<<16),k=S>>>16,O=65535&(I=v=65535&O|(C+=O>>>16)<<16),C=I>>>16,P+=65535&(S=($>>>28|x<<4)^(x>>>2|$<<30)^(x>>>7|$<<25)),k+=S>>>16,O+=65535&(I=(x>>>28|$<<4)^($>>>2|x<<30)^($>>>7|x<<25)),C+=I>>>16,k+=(S=$&j^$&H^j&H)>>>16,O+=65535&(I=x&T^x&N^T&N),C+=I>>>16,h=65535&(O+=(k+=(P+=65535&S)>>>16)>>>16)|(C+=O>>>16)<<16,A=65535&P|k<<16,P=65535&(S=_),k=S>>>16,O=65535&(I=a),C=I>>>16,k+=(S=b)>>>16,O+=65535&(I=v),C+=I>>>16,T=s,N=i,F=o,M=a=65535&(O+=(k+=(P+=65535&S)>>>16)>>>16)|(C+=O>>>16)<<16,L=c,U=l,D=u,x=h,j=d,H=f,G=p,Q=_=65535&P|k<<16,q=g,W=m,K=y,$=A,w%16==15)for(E=0;E<16;E++)I=R[E],P=65535&(S=B[E]),k=S>>>16,O=65535&I,C=I>>>16,I=R[(E+9)%16],P+=65535&(S=B[(E+9)%16]),k+=S>>>16,O+=65535&I,C+=I>>>16,v=R[(E+1)%16],P+=65535&(S=((b=B[(E+1)%16])>>>1|v<<31)^(b>>>8|v<<24)^(b>>>7|v<<25)),k+=S>>>16,O+=65535&(I=(v>>>1|b<<31)^(v>>>8|b<<24)^v>>>7),C+=I>>>16,v=R[(E+14)%16],k+=(S=((b=B[(E+14)%16])>>>19|v<<13)^(v>>>29|b<<3)^(b>>>6|v<<26))>>>16,O+=65535&(I=(v>>>19|b<<13)^(b>>>29|v<<3)^v>>>6),C+=I>>>16,C+=(O+=(k+=(P+=65535&S)>>>16)>>>16)>>>16,R[E]=65535&O|C<<16,B[E]=65535&P|k<<16;P=65535&(S=$),k=S>>>16,O=65535&(I=x),C=I>>>16,I=e[0],k+=(S=t[0])>>>16,O+=65535&I,C+=I>>>16,C+=(O+=(k+=(P+=65535&S)>>>16)>>>16)>>>16,e[0]=x=65535&O|C<<16,t[0]=$=65535&P|k<<16,P=65535&(S=j),k=S>>>16,O=65535&(I=T),C=I>>>16,I=e[1],k+=(S=t[1])>>>16,O+=65535&I,C+=I>>>16,C+=(O+=(k+=(P+=65535&S)>>>16)>>>16)>>>16,e[1]=T=65535&O|C<<16,t[1]=j=65535&P|k<<16,P=65535&(S=H),k=S>>>16,O=65535&(I=N),C=I>>>16,I=e[2],k+=(S=t[2])>>>16,O+=65535&I,C+=I>>>16,C+=(O+=(k+=(P+=65535&S)>>>16)>>>16)>>>16,e[2]=N=65535&O|C<<16,t[2]=H=65535&P|k<<16,P=65535&(S=G),k=S>>>16,O=65535&(I=F),C=I>>>16,I=e[3],k+=(S=t[3])>>>16,O+=65535&I,C+=I>>>16,C+=(O+=(k+=(P+=65535&S)>>>16)>>>16)>>>16,e[3]=F=65535&O|C<<16,t[3]=G=65535&P|k<<16,P=65535&(S=Q),k=S>>>16,O=65535&(I=M),C=I>>>16,I=e[4],k+=(S=t[4])>>>16,O+=65535&I,C+=I>>>16,C+=(O+=(k+=(P+=65535&S)>>>16)>>>16)>>>16,e[4]=M=65535&O|C<<16,t[4]=Q=65535&P|k<<16,P=65535&(S=q),k=S>>>16,O=65535&(I=L),C=I>>>16,I=e[5],k+=(S=t[5])>>>16,O+=65535&I,C+=I>>>16,C+=(O+=(k+=(P+=65535&S)>>>16)>>>16)>>>16,e[5]=L=65535&O|C<<16,t[5]=q=65535&P|k<<16,P=65535&(S=W),k=S>>>16,O=65535&(I=U),C=I>>>16,I=e[6],k+=(S=t[6])>>>16,O+=65535&I,C+=I>>>16,C+=(O+=(k+=(P+=65535&S)>>>16)>>>16)>>>16,e[6]=U=65535&O|C<<16,t[6]=W=65535&P|k<<16,P=65535&(S=K),k=S>>>16,O=65535&(I=D),C=I>>>16,I=e[7],k+=(S=t[7])>>>16,O+=65535&I,C+=I>>>16,C+=(O+=(k+=(P+=65535&S)>>>16)>>>16)>>>16,e[7]=D=65535&O|C<<16,t[7]=K=65535&P|k<<16,z+=128,n-=128}return n}function Y(e,t,r){var n,s=new Int32Array(8),i=new Int32Array(8),o=new Uint8Array(256),a=r;for(s[0]=1779033703,s[1]=3144134277,s[2]=1013904242,s[3]=2773480762,s[4]=1359893119,s[5]=2600822924,s[6]=528734635,s[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,z(s,i,t,r),r%=128,n=0;n<r;n++)o[n]=t[a-r+n];for(o[r]=128,o[(r=256-128*(r<112?1:0))-9]=0,p(o,r-8,a/536870912|0,a<<3),z(s,i,o,r),n=0;n<8;n++)p(e,8*n,s[n],i[n]);return 0}function J(e,r){var n=t(),s=t(),i=t(),o=t(),a=t(),c=t(),l=t(),h=t(),d=t();U(n,e[1],e[0]),U(d,r[1],r[0]),D(n,n,d),L(s,e[0],e[1]),L(d,r[0],r[1]),D(s,s,d),D(i,e[3],r[3]),D(i,i,u),D(o,e[2],r[2]),L(o,o,o),U(a,s,n),U(c,o,i),L(l,o,i),L(h,s,n),D(e[0],a,c),D(e[1],h,l),D(e[2],l,c),D(e[3],a,h)}function V(e,t,r){var n;for(n=0;n<4;n++)x(e[n],t[n],r)}function Z(e,r){var n=t(),s=t(),i=t();j(i,r[2]),D(n,r[0],i),D(s,r[1],i),T(e,s),e[31]^=F(n)<<7}function ee(e,t,r){var n,s;for(R(e[0],o),R(e[1],a),R(e[2],a),R(e[3],o),s=255;s>=0;--s)V(e,t,n=r[s/8|0]>>(7&s)&1),J(t,e),J(e,e),V(e,t,n)}function te(e,r){var n=[t(),t(),t(),t()];R(n[0],h),R(n[1],d),R(n[2],a),D(n[3],h,d),ee(e,n,r)}function re(e,r,s){var i,o=new Uint8Array(64),a=[t(),t(),t(),t()];for(s||n(r,32),Y(o,r,32),o[0]&=248,o[31]&=127,o[31]|=64,te(a,o),Z(e,a),i=0;i<32;i++)r[i+32]=e[i];return 0}var ne=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function se(e,t){var r,n,s,i;for(n=63;n>=32;--n){for(r=0,s=n-32,i=n-12;s<i;++s)t[s]+=r-16*t[n]*ne[s-(n-32)],r=t[s]+128>>8,t[s]-=256*r;t[s]+=r,t[n]=0}for(r=0,s=0;s<32;s++)t[s]+=r-(t[31]>>4)*ne[s],r=t[s]>>8,t[s]&=255;for(s=0;s<32;s++)t[s]-=r*ne[s];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function ie(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;se(e,r)}function oe(e,r,n,s){var i,o,a=new Uint8Array(64),c=new Uint8Array(64),l=new Uint8Array(64),u=new Float64Array(64),h=[t(),t(),t(),t()];Y(a,s,32),a[0]&=248,a[31]&=127,a[31]|=64;var d=n+64;for(i=0;i<n;i++)e[64+i]=r[i];for(i=0;i<32;i++)e[32+i]=a[32+i];for(Y(l,e.subarray(32),n+32),ie(l),te(h,l),Z(e,h),i=32;i<64;i++)e[i]=s[i];for(Y(c,e,n+64),ie(c),i=0;i<64;i++)u[i]=0;for(i=0;i<32;i++)u[i]=l[i];for(i=0;i<32;i++)for(o=0;o<32;o++)u[i+o]+=c[i]*a[o];return se(e.subarray(32),u),d}function ae(e,r,n,s){var i,c=new Uint8Array(32),u=new Uint8Array(64),h=[t(),t(),t(),t()],d=[t(),t(),t(),t()];if(n<64)return-1;if(function(e,r){var n=t(),s=t(),i=t(),c=t(),u=t(),h=t(),d=t();return R(e[2],a),M(e[1],r),$(i,e[1]),D(c,i,l),U(i,i,e[2]),L(c,e[2],c),$(u,c),$(h,u),D(d,h,u),D(n,d,i),D(n,n,c),function(e,r){var n,s=t();for(n=0;n<16;n++)s[n]=r[n];for(n=250;n>=0;n--)$(s,s),1!==n&&D(s,s,r);for(n=0;n<16;n++)e[n]=s[n]}(n,n),D(n,n,i),D(n,n,c),D(n,n,c),D(e[0],n,c),$(s,e[0]),D(s,s,c),N(s,i)&&D(e[0],e[0],f),$(s,e[0]),D(s,s,c),N(s,i)?-1:(F(e[0])===r[31]>>7&&U(e[0],o,e[0]),D(e[3],e[0],e[1]),0)}(d,s))return-1;for(i=0;i<n;i++)e[i]=r[i];for(i=0;i<32;i++)e[i+32]=s[i];if(Y(u,e,n),ie(u),ee(h,d,u),te(d,r.subarray(32)),J(h,d),Z(c,h),n-=64,m(r,0,c,0)){for(i=0;i<n;i++)e[i]=0;return-1}for(i=0;i<n;i++)e[i]=r[i+64];return n}var ce=64,le=32,ue=64;function he(e,t){if(32!==e.length)throw new Error("bad key size");if(24!==t.length)throw new Error("bad nonce size")}function de(){var e,t;for(t=0;t<arguments.length;t++)if("[object Uint8Array]"!==(e=Object.prototype.toString.call(arguments[t])))throw new TypeError("unexpected type "+e+", use Uint8Array")}function fe(e){for(var t=0;t<e.length;t++)e[t]=0}e.lowlevel={crypto_core_hsalsa20:A,crypto_stream_xor:I,crypto_stream:E,crypto_stream_salsa20_xor:b,crypto_stream_salsa20:w,crypto_onetimeauth:P,crypto_onetimeauth_verify:k,crypto_verify_16:g,crypto_verify_32:m,crypto_secretbox:O,crypto_secretbox_open:C,crypto_scalarmult:H,crypto_scalarmult_base:G,crypto_box_beforenm:q,crypto_box_afternm:W,crypto_box:function(e,t,r,n,s,i){var o=new Uint8Array(32);return q(o,s,i),W(e,t,r,n,o)},crypto_box_open:function(e,t,r,n,s,i){var o=new Uint8Array(32);return q(o,s,i),K(e,t,r,n,o)},crypto_box_keypair:Q,crypto_hash:Y,crypto_sign:oe,crypto_sign_keypair:re,crypto_sign_open:ae,crypto_secretbox_KEYBYTES:32,crypto_secretbox_NONCEBYTES:24,crypto_secretbox_ZEROBYTES:32,crypto_secretbox_BOXZEROBYTES:16,crypto_scalarmult_BYTES:32,crypto_scalarmult_SCALARBYTES:32,crypto_box_PUBLICKEYBYTES:32,crypto_box_SECRETKEYBYTES:32,crypto_box_BEFORENMBYTES:32,crypto_box_NONCEBYTES:24,crypto_box_ZEROBYTES:32,crypto_box_BOXZEROBYTES:16,crypto_sign_BYTES:ce,crypto_sign_PUBLICKEYBYTES:le,crypto_sign_SECRETKEYBYTES:ue,crypto_sign_SEEDBYTES:32,crypto_hash_BYTES:64},e.util||(e.util={},e.util.decodeUTF8=e.util.encodeUTF8=e.util.encodeBase64=e.util.decodeBase64=function(){throw new Error("nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js")}),e.randomBytes=function(e){var t=new Uint8Array(e);return n(t,e),t},e.secretbox=function(e,t,r){de(e,t,r),he(r,t);for(var n=new Uint8Array(32+e.length),s=new Uint8Array(n.length),i=0;i<e.length;i++)n[i+32]=e[i];return O(s,n,n.length,t,r),s.subarray(16)},e.secretbox.open=function(e,t,r){de(e,t,r),he(r,t);for(var n=new Uint8Array(16+e.length),s=new Uint8Array(n.length),i=0;i<e.length;i++)n[i+16]=e[i];return!(n.length<32)&&0===C(s,n,n.length,t,r)&&s.subarray(32)},e.secretbox.keyLength=32,e.secretbox.nonceLength=24,e.secretbox.overheadLength=16,e.scalarMult=function(e,t){if(de(e,t),32!==e.length)throw new Error("bad n size");if(32!==t.length)throw new Error("bad p size");var r=new Uint8Array(32);return H(r,e,t),r},e.scalarMult.base=function(e){if(de(e),32!==e.length)throw new Error("bad n size");var t=new Uint8Array(32);return G(t,e),t},e.scalarMult.scalarLength=32,e.scalarMult.groupElementLength=32,e.box=function(t,r,n,s){var i=e.box.before(n,s);return e.secretbox(t,r,i)},e.box.before=function(e,t){de(e,t),function(e,t){if(32!==e.length)throw new Error("bad public key size");if(32!==t.length)throw new Error("bad secret key size")}(e,t);var r=new Uint8Array(32);return q(r,e,t),r},e.box.after=e.secretbox,e.box.open=function(t,r,n,s){var i=e.box.before(n,s);return e.secretbox.open(t,r,i)},e.box.open.after=e.secretbox.open,e.box.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(32);return Q(e,t),{publicKey:e,secretKey:t}},e.box.keyPair.fromSecretKey=function(e){if(de(e),32!==e.length)throw new Error("bad secret key size");var t=new Uint8Array(32);return G(t,e),{publicKey:t,secretKey:new Uint8Array(e)}},e.box.publicKeyLength=32,e.box.secretKeyLength=32,e.box.sharedKeyLength=32,e.box.nonceLength=24,e.box.overheadLength=e.secretbox.overheadLength,e.sign=function(e,t){if(de(e,t),t.length!==ue)throw new Error("bad secret key size");var r=new Uint8Array(ce+e.length);return oe(r,e,e.length,t),r},e.sign.open=function(e,t){if(2!==arguments.length)throw new Error("nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?");if(de(e,t),t.length!==le)throw new Error("bad public key size");var r=new Uint8Array(e.length),n=ae(r,e,e.length,t);if(n<0)return null;for(var s=new Uint8Array(n),i=0;i<s.length;i++)s[i]=r[i];return s},e.sign.detached=function(t,r){for(var n=e.sign(t,r),s=new Uint8Array(ce),i=0;i<s.length;i++)s[i]=n[i];return s},e.sign.detached.verify=function(e,t,r){if(de(e,t,r),t.length!==ce)throw new Error("bad signature size");if(r.length!==le)throw new Error("bad public key size");var n,s=new Uint8Array(ce+e.length),i=new Uint8Array(ce+e.length);for(n=0;n<ce;n++)s[n]=t[n];for(n=0;n<e.length;n++)s[n+ce]=e[n];return ae(i,s,s.length,r)>=0},e.sign.keyPair=function(){var e=new Uint8Array(le),t=new Uint8Array(ue);return re(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(de(e),e.length!==ue)throw new Error("bad secret key size");for(var t=new Uint8Array(le),r=0;r<t.length;r++)t[r]=e[32+r];return{publicKey:t,secretKey:new Uint8Array(e)}},e.sign.keyPair.fromSeed=function(e){if(de(e),32!==e.length)throw new Error("bad seed size");for(var t=new Uint8Array(le),r=new Uint8Array(ue),n=0;n<32;n++)r[n]=e[n];return re(t,r,!0),{publicKey:t,secretKey:r}},e.sign.publicKeyLength=le,e.sign.secretKeyLength=ue,e.sign.seedLength=32,e.sign.signatureLength=ce,e.hash=function(e){de(e);var t=new Uint8Array(64);return Y(t,e,e.length),t},e.hash.hashLength=64,e.verify=function(e,t){return de(e,t),0!==e.length&&0!==t.length&&e.length===t.length&&0===_(e,0,t,0,e.length)},e.setPRNG=function(e){n=e},function(){var t="undefined"!=typeof self?self.crypto||self.msCrypto:null;t&&t.getRandomValues?e.setPRNG(function(e,r){var n,s=new Uint8Array(r);for(n=0;n<r;n+=65536)t.getRandomValues(s.subarray(n,n+Math.min(r-n,65536)));for(n=0;n<r;n++)e[n]=s[n];fe(s)}):(t=r(6982))&&t.randomBytes&&e.setPRNG(function(e,r){var n,s=t.randomBytes(r);for(n=0;n<r;n++)e[n]=s[n];fe(s)})}()}(e.exports?e.exports:self.nacl=self.nacl||{})},8404(e,t,r){"use strict";var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&s(t,e,r[o]);return i(t,e),t}),a=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.WorkingDir=t.SSH_SCHEME=t.SSH_DEFAULT_PORT=t.FENCE_RE=t.CODE_EXTENSION_LANGUAGE_MAP=t.IMAGE_EXTENSION_MIME_MAP=t.PURE_TEXT_EXTENSION_MIME_MAP=t.TEXT_EXTENSION_MIME_MAP=t.ExecutionResponse=void 0,t.extractJson=function(e){if("object"==typeof e&&null!==e)return e;if("string"!=typeof e)return null;let r=e.trim();const n=t.FENCE_RE.exec(r);if(n&&(r=n[1].trim()),!r.startsWith("{")){const e=r.indexOf("{"),t=r.lastIndexOf("}");-1!==e&&t>e&&(r=r.substring(e,t+1))}try{return JSON.parse(r)}catch(e){return{properties:[{name:"output",value:r}]}}},t.getSequential=function(e){const t=e.sequential;let r=!1,n="";if(t){r=!0;const e=t.prompt;e&&(n=e)}return[r,n]},t.buildConnectConfig=function(e,r){const n=r.host||e,s=r.port?parseInt(r.port,10):t.SSH_DEFAULT_PORT,i=r.user_name||r.userName||r.user||"",o=(r.auth_type||r.authType||"").toLowerCase(),a={host:n,port:isNaN(s)?t.SSH_DEFAULT_PORT:s,username:i,readyTimeout:2e4},c=r.key_file||r.keyFile;if("key"===o&&c)try{a.privateKey=l.readFileSync(c),r.pass&&(a.passphrase=r.pass)}catch(e){}else if(r.pass)a.password=r.pass;else if(c)try{a.privateKey=l.readFileSync(c)}catch(e){}return a},t.connect=function(e){return new Promise((t,r)=>{const n=new c.Client;n.on("ready",()=>t(n)),n.on("error",e=>r(e));try{n.connect(e)}catch(e){r(e)}})},t.execCommand=h,t.shellQuote=d,t.getSftp=function(e){return new Promise((t,r)=>{e.sftp((e,n)=>{e?r(e):t(n)})})},t.sftpStat=f,t.sftpReadFile=function(e,t){return new Promise((r,n)=>{e.readFile(t,(e,t)=>{e?n(e):r(t.toString("utf8"))})})},t.sftpWriteFile=function(e,t,r){return new Promise((n,s)=>{e.writeFile(t,r,e=>{e?s(e):n()})})},t.sftpMkdir=function(e,t){return new Promise(r=>{e.mkdir(t,{recursive:!0},()=>{r()})})},t.remoteFileExists=function(e,t){return a(this,void 0,void 0,function*(){try{return(yield f(e,t)).isFile()}catch(e){return!1}})},t.remoteIsInGitRepo=function(e,t,r){return a(this,void 0,void 0,function*(){return 0===(yield h(e,"git --version")).code&&(0===(yield h(e,`cd ${d(t)} && git rev-parse --show-toplevel`)).code&&0===(yield h(e,`cd ${d(t)} && git ls-files --error-unmatch ${d(r)}`)).code)})},t.isProbablyTextFile=p,t.parseDelimitedLine=_,t.escapeMarkdownCell=g,t.delimitedToMarkdownTable=m,t.sliceText=y,t.buildTextContentResult=A,t.buildImageContentResult=v,t.isProbablyTextBuffer=b,t.buildFileResultFromBuffer=function(e,r,n=0,s=0,i=0){if(t.IMAGE_EXTENSION_MIME_MAP[e])return v(e,r);if(t.CODE_EXTENSION_LANGUAGE_MAP[e]||t.TEXT_EXTENSION_MIME_MAP[e]||t.PURE_TEXT_EXTENSION_MIME_MAP[e])return A(e,y(r.toString("utf-8"),n,s,i));if(b(r))return A(e,y(r.toString("utf-8"),n,s,i));throw new Error(`Unsupported (binary) file format: ${e||"(no extension)"}`)},t.sftpReadFileBuffer=function(e,t){return new Promise((r,n)=>{e.readFile(t,(e,t)=>{e?n(e):r(t)})})},t.readTextFile=w,t.readFile=function(e,r=0,n=0,s=0){const i=u.extname(e).toLowerCase();if(t.IMAGE_EXTENSION_MIME_MAP[i])return E(e);if(t.CODE_EXTENSION_LANGUAGE_MAP[i]||t.TEXT_EXTENSION_MIME_MAP[i]||t.PURE_TEXT_EXTENSION_MIME_MAP[i])return w(e,r,n,s);if(p(e))return w(e,r,n,s);throw new Error(`Unsupported (binary) file format for ${e}: ${i||"(no extension)"}`)},t.readImageFile=E,t.buildImageUri=function(e,t){return`data:${e};base64,${t}`},t.fenceCode=function(e,t){return`\`\`\`${e}\n${t}\n\`\`\`\n`},t.isImageFile=I,t.isKnownTextExtension=S,t.isTextFile=P,t.fileViewKind=function(e){return I(e)?"image":P(e)?"text":""};const c=r(3365),l=o(r(9896)),u=o(r(6760));function h(e,t){return new Promise(r=>{e.exec(t,(e,t)=>{if(e)return void r({code:1,stdout:""});let n="",s=0;t.on("close",e=>{s="number"==typeof e?e:0,r({code:s,stdout:n})}),t.on("data",e=>{n+=e.toString()}),t.on("error",()=>r({code:1,stdout:n}))})})}function d(e){return"'"+e.replace(/'/g,"'\\''")+"'"}function f(e,t){return new Promise((r,n)=>{e.stat(t,(e,t)=>{e?n(e):r(t)})})}function p(e){let t;try{const r=l.openSync(e,"r");try{const e=Buffer.alloc(8192),n=l.readSync(r,e,0,8192,0);t=e.subarray(0,n)}finally{l.closeSync(r)}}catch(e){return!1}return b(t)}function _(e,t){const r=[];let n="",s=!1;for(let i=0;i<e.length;i++){const o=e[i];s?'"'===o?'"'===e[i+1]?(n+='"',i++):s=!1:n+=o:'"'===o?s=!0:o===t?(r.push(n),n=""):n+=o}return r.push(n),r}function g(e){return e.replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function m(e,t){const r=e.split(/\r?\n/);for(;r.length>0&&""===r[r.length-1].trim();)r.pop();if(0===r.length)return"";const n=r.map(e=>_(e,t)),s=n.reduce((e,t)=>Math.max(e,t.length),0),i=e=>{const t=e.slice();for(;t.length<s;)t.push("");return t},o=i(n[0]),a=n.slice(1).map(i),c=[];c.push("| "+o.map(g).join(" | ")+" |"),c.push("| "+o.map(()=>"---").join(" | ")+" |");for(const e of a)c.push("| "+e.map(g).join(" | ")+" |");return c.join("\n")}function y(e,t=0,r=0,n=0){if(r>0||t>1){const n=e.split(/\r?\n/),s=Math.max(1,t),i=r>0?r:n.length,o=Math.min(i,n.length);return n.slice(s-1,o).join("\n")}return n>0?e.substring(0,n):e}function A(e,r){const n=t.CODE_EXTENSION_LANGUAGE_MAP[e]||"";let s;return s=".csv"===e||".tsv"===e?m(r,".tsv"===e?"\t":","):".svg"===e||".md"===e?r:"```"+n+"\n"+r+"\n```",{content:s,format:"md",mimeType:t.TEXT_EXTENSION_MIME_MAP[e]||t.PURE_TEXT_EXTENSION_MIME_MAP[e]||"text/plain"}}function v(e,r){const n=t.IMAGE_EXTENSION_MIME_MAP[e];if(!n)throw new Error(`Unsupported image format: ${e||"(no extension)"}`);return{content:r.toString("base64"),format:"image",mimeType:n.mimeType}}function b(e){if(0===e.length)return!0;if(e.includes(0))return!1;const t=e.toString("utf-8");let r=0;for(const e of t)"�"===e&&r++;return t.length>0&&r/t.length<.1}function w(e,t=0,r=0,n=0){const s=u.extname(e).toLowerCase();let i;try{i=l.readFileSync(e,"utf-8")}catch(t){throw new Error(`Failed to read file ${e}: ${t}`)}return A(s,y(i,t,r,n))}function E(e){const r=u.extname(e).toLowerCase(),n=t.IMAGE_EXTENSION_MIME_MAP[r];if(!n)throw new Error(`Unsupported image format for file ${e}: ${r||"(no extension)"}`);let s;try{s=l.readFileSync(e)}catch(t){throw new Error(`Failed to read image file ${e}: ${t}`)}return{content:s.toString("base64"),format:"image",mimeType:n.mimeType}}function I(e){const r=u.extname(e).toLowerCase();return Boolean(t.IMAGE_EXTENSION_MIME_MAP[r])}function S(e){const r=u.extname(e).toLowerCase();return!!r&&Boolean(t.CODE_EXTENSION_LANGUAGE_MAP[r]||t.TEXT_EXTENSION_MIME_MAP[r]||t.PURE_TEXT_EXTENSION_MIME_MAP[r])}function P(e){return!I(e)&&(!!S(e)||p(e))}t.ExecutionResponse=class{constructor(e,t,r=!1,n=!1,s="",i="",o=!1){this.kind="execution",this.content=e,this.prompt=t,this.sequential=r,this.print=n,this.format=s,this.mimeType=i,this.persist=o,this.misc={}}static isExecutionResponse(e){if(null===e||"object"!=typeof e)return!1;const t=e;return"execution"===t.kind||"string"==typeof t.content&&"string"==typeof t.prompt&&"boolean"==typeof t.sequential&&"boolean"==typeof t.print&&"string"==typeof t.format}},t.TEXT_EXTENSION_MIME_MAP={".json":"application/json",".xml":"application/xml",".dtd":"application/xml",".xsd":"application/xml",".html":"text/html",".htm":"text/html",".css":"text/css",".csv":"text/csv",".md":"text/markdown",".yaml":"text/yaml",".yml":"text/yaml",".svg":"image/svg+xml"},t.PURE_TEXT_EXTENSION_MIME_MAP={".txt":"text/plain",".text":"text/plain",".log":"text/plain",".csv":"text/csv",".tsv":"text/tab-separated-values",".ini":"text/plain",".cfg":"text/plain",".conf":"text/plain",".properties":"text/plain",".env":"text/plain",".toml":"text/plain",".rst":"text/x-rst",".nfo":"text/plain",".list":"text/plain",".diff":"text/x-diff",".patch":"text/x-diff"},t.IMAGE_EXTENSION_MIME_MAP={".png":{format:"png",mimeType:"image/png"},".apng":{format:"apng",mimeType:"image/apng"},".jpg":{format:"jpeg",mimeType:"image/jpeg"},".jpeg":{format:"jpeg",mimeType:"image/jpeg"},".jpe":{format:"jpeg",mimeType:"image/jpeg"},".jfif":{format:"jpeg",mimeType:"image/jpeg"},".gif":{format:"gif",mimeType:"image/gif"},".bmp":{format:"bmp",mimeType:"image/bmp"},".webp":{format:"webp",mimeType:"image/webp"},".tif":{format:"tiff",mimeType:"image/tiff"},".tiff":{format:"tiff",mimeType:"image/tiff"},".ico":{format:"ico",mimeType:"image/x-icon"},".cur":{format:"ico",mimeType:"image/x-icon"},".avif":{format:"avif",mimeType:"image/avif"},".heic":{format:"heic",mimeType:"image/heic"},".heif":{format:"heif",mimeType:"image/heif"}},t.CODE_EXTENSION_LANGUAGE_MAP={".java":"java",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".h":"cpp",".hpp":"cpp",".c":"c",".py":"python",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".ts":"typescript",".tsx":"typescript",".go":"go",".rs":"rust",".rb":"ruby",".php":"php",".cs":"csharp",".kt":"kotlin",".swift":"swift",".scala":"scala",".sh":"bash",".json":"json",".xml":"xml",".html":"html",".css":"css",".sql":"sql",".yaml":"yaml",".yml":"yaml",".dtd":"xml",".xsd":"xml",".svg":"xml"},t.FENCE_RE=/```(?:[a-zA-Z0-9_\-]+)?\s*\n([\s\S]*?)\n```/,t.SSH_DEFAULT_PORT=22,t.SSH_SCHEME=/^ssh:\/\//i,t.WorkingDir=class{constructor(e="",t="",r="",n={}){this.kind="",this.path="",this.serverName="",this.server={},this.kind=e,this.path=t,this.serverName=r,this.server=n}}},2038(e,t,r){"use strict";var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&s(t,e,r[o]);return i(t,e),t}),a=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressionParser=t.EXEC_PLACEHOLDER=t.FindError=t.MINUTE_SECONDS=t.DAY_SECONDS=t.PERM_ALL=void 0,t.isGlobPattern=v,t.globToRegExp=b,t.matchesNamePattern=w,t.padLeft=E,t.padRight=I,t.ceilDiv=S,t.pad2=P,t.compareNumber=k,t.statFileType=O,t.fileTypeName=function(e){switch(e){case"f":return"regular file";case"d":return"directory";case"l":return"symbolic link";case"b":return"block special file";case"c":return"character special file";case"p":return"fifo";case"s":return"socket";case"D":return"door";default:return"unknown"}},t.formatMode=C,t.normalizeStat=R,t.formatCtime=T,t.formatLsTime=N,t.compileMode=F,t.adjustMode=M,t.parsePermSpec=L,t.permMatches=U,t.parseComparisonPrefix=D,t.parseUintArg=$,t.parseNumberSpec=j,t.parseSizeSpec=G,t.sizeMatches=Q,t.parseTimeSpec=q,t.timeWindowMatches=W,t.currentUserId=K,t.currentUserName=X,t.startOfToday=z,t.userNameOf=ee,t.groupNameOf=te,t.resolveUid=re,t.resolveGid=ne,t.strftime=ae,t.formatTimeValue=ce,t.dirNameOf=le,t.formatPrintf=ue,t.formatLsLine=he,t.reportError=de,t.execTerminator=fe,t.replacePlaceholder=pe,t.spawnCommand=_e,t.runExec=ge,t.flushExecBatches=me,t.breToJs=Ee,t.compilePathRegex=Ie,t.parseExpression=Oe,t.statEntry=Re,t.resolveOptions=Ne,t.optionsToArgv=Ue,t.runFind=De,t.find=$e,t.findFiles=je,t.findFilesByName=function(e,t,r){return a(this,void 0,void 0,function*(){const n=r?Object.assign({},r):{};return n.paths=null!=e&&""!==e?e:".",void 0===n.name&&(n.name=t),je(n)})},t.findFilesRegex=function(e,t,r){return a(this,void 0,void 0,function*(){const n=r?Object.assign({},r):{};return n.paths=null!=e&&""!==e?e:".",t instanceof RegExp?t.ignoreCase?n.iregex=t.source:n.regex=t.source:n.regex=String(t),je(n)})},t.findPaths=function(e,t){return a(this,void 0,void 0,function*(){const r=yield $e(e,t),n=[];for(let e=0;e<r.entries.length;e++)n.push(r.entries[e].path);return n})};const c=o(r(9896)),l=o(r(6760)),u=o(r(8161)),h=r(5317),d=String.fromCharCode(92),f=String.fromCharCode(0),p="\n";t.PERM_ALL=4095,t.DAY_SECONDS=86400,t.MINUTE_SECONDS=60;class _ extends Error{constructor(e,t="EFIND"){super(e),this.kind="find-error",this.name="FindError",this.code=t,Object.setPrototypeOf(this,_.prototype)}}t.FindError=_;const g=d+"^$.*+?()[]{}|/",m=new Map;function y(e){return 1===e.length&&-1!==g.indexOf(e)?d+e:e}function A(e){return"]"===e||e===d||"^"===e||"["===e?d+e:e}function v(e){for(let t=0;t<e.length;t++){const r=e.charAt(t);if("*"===r||"?"===r||"["===r||"]"===r||r===d)return!0}return!1}function b(e,t=!1){const r=(t?"i:":"s:")+e,n=m.get(r);if(n)return n;let s="^",i=0;for(;i<e.length;){const t=e.charAt(i);if("*"!==t)if("?"!==t){if("["===t){let t=i+1,r=!1;"!"!==e.charAt(t)&&"^"!==e.charAt(t)||(r=!0,t++);let n="",o=!1;for("]"===e.charAt(t)&&(n+=d+"]",t++);t<e.length;){const r=e.charAt(t);if("]"===r){o=!0,t++;break}r===d&&t+1<e.length?(n+=d+e.charAt(t+1),t+=2):"-"!==r?(n+=A(r),t++):(n+="-",t++)}if(!o){s+=d+"[",i++;continue}s+="["+(r?"^":"")+n+"]",i=t;continue}if(t===d){const t=e.charAt(i+1);t?(s+=y(t),i+=2):(s+=y(d),i++);continue}s+=y(t),i++}else s+="[^]",i++;else s+="[^]*",i++}s+="$";const o=new RegExp(s,t?"i":"");return m.set(r,o),o}function w(e,t,r="auto",n=!1){return"glob"===("auto"===r?v(t)?"glob":"substring":r)?b(t,n).test(e):n?-1!==e.toLowerCase().indexOf(t.toLowerCase()):-1!==e.indexOf(t)}function E(e,t,r=" "){let n=e;for(;n.length<t;)n=r+n;return n}function I(e,t,r=" "){let n=e;for(;n.length<t;)n+=r;return n}function S(e,t){return t<=0?e:Math.floor(e/t)+(e%t===0?0:1)}function P(e){return e<10?"0"+String(e):String(e)}function k(e,t,r){return"gt"===e?t>r:"lt"===e?t<r:t===r}function O(e){switch(61440&e){case 16384:return"d";case 32768:return"f";case 40960:return"l";case 24576:return"b";case 8192:return"c";case 4096:return"p";case 49152:return"s";default:return"?"}}function C(e){const t=O(e);let r="f"===t?"-":"?"===t?"?":t;const n=(t,r)=>0!==(e&t)?r:"-";return r+=n(256,"r")+n(128,"w"),r+=2048&e?64&e?"s":"S":n(64,"x"),r+=n(32,"r")+n(16,"w"),r+=1024&e?8&e?"s":"S":n(8,"x"),r+=n(4,"r")+n(2,"w"),r+=512&e?1&e?"t":"T":n(1,"x"),r}function R(e){const t=e.mode,r=O(t),n=e,s="number"==typeof n.blocks?n.blocks:S(e.size,512);return{mode:t,ino:e.ino,dev:e.dev,nlink:e.nlink,uid:e.uid,gid:e.gid,rdev:e.rdev,size:e.size,blocks:s,atimeMs:e.atimeMs,mtimeMs:e.mtimeMs,ctimeMs:e.ctimeMs,birthtimeMs:"number"==typeof n.birthtimeMs?n.birthtimeMs:0,fileType:r,isDirectory:"d"===r,isFile:"f"===r,isSymbolicLink:"l"===r,isBlockDevice:"b"===r,isCharacterDevice:"c"===r,isFIFO:"p"===r,isSocket:"s"===r}}const B=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],x=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function T(e){if(!isFinite(e)||0===e)return"Thu Jan 1 00:00:00.0000000000 1970";const t=new Date(e);return B[t.getDay()]+" "+x[t.getMonth()]+" "+E(String(t.getDate()),2)+" "+P(t.getHours())+":"+P(t.getMinutes())+":"+P(t.getSeconds())+"."+E(String((e%1e3+1e3)%1e3*1e6),9,"0")+" "+String(t.getFullYear())}function N(e,t){if(!isFinite(e)||0===e)return"Jan 1 1970";const r=new Date(e),n=x[r.getMonth()],s=E(String(r.getDate()),2);return e>t-157248e5&&e<t+36e5?n+" "+s+" "+P(r.getHours())+":"+P(r.getMinutes()):n+" "+s+" "+String(r.getFullYear())}function F(e){if(!e)throw new _("invalid file mode: empty mode string");const t=[],r=e.split(",");for(let n=0;n<r.length;n++){let s=r[n];if(!s)throw new _("invalid file mode: "+e);let i=0,o=!1;for(;s.length>0&&-1!=="ugoa".indexOf(s.charAt(0));){const e=s.charAt(0);o=!0,i|="u"===e?2496:"g"===e?1080:"o"===e?519:4095,s=s.slice(1)}o||(i=4095);const a=s.charAt(0);if("+"!==a&&"-"!==a&&"="!==a)throw new _("invalid file mode: "+e);s=s.slice(1);let c=0,l=0,u=!1;for(let t=0;t<s.length;t++){const r=s.charAt(t);if("r"===r)c|=292&i;else if("w"===r)c|=146&i;else if("x"===r)c|=73&i,l|=73&i;else if("X"===r)u=!0,l|=73&i;else if("s"===r)c|=3072&i;else{if("t"!==r)throw new _("u"===r||"g"===r||"o"===r?"copying permissions is not supported in -perm mode: "+e:"invalid file mode: "+e);c|=512&i}}t.push({op:a,who:i,perms:c,execMask:l,conditionalX:u})}return t}function M(e,r,n){let s=r;for(let t=0;t<e.length;t++){const i=e[t];let o=i.perms;if(0!==i.execMask){const e=0!==(o&i.execMask),t=i.conditionalX&&(n||!!(73&r));e||t?o|=i.execMask:o&=~i.execMask}"+"===i.op?s|=o:"-"===i.op?s&=~o:s=s&~i.who|o&i.who}return s&t.PERM_ALL}function L(e){let r="exact",n=e;if("-"===e.charAt(0)?(r="atleast",n=e.slice(1)):"/"===e.charAt(0)&&(r="any",n=e.slice(1)),!n)throw new _("invalid file mode: "+e);if(/^[0-7]+$/.test(n)){const s=parseInt(n,8)&t.PERM_ALL;return{kind:r,value:s,valueDir:s,raw:e}}const s=F(n),i=M(s,0,!1),o=M(s,0,!0);let a=r;return"any"===a&&0===i&&0===o&&(a="atleast"),{kind:a,value:i,valueDir:o,raw:e}}function U(e,r){const n="d"===O(r)?e.valueDir:e.value;return"atleast"===e.kind?(r&n)===n:"any"===e.kind?0===n||0!==(r&n):(r&t.PERM_ALL)===n}function D(e){const t=e.charAt(0);return"+"===t?{cmp:"gt",rest:e.slice(1)}:"-"===t?{cmp:"lt",rest:e.slice(1)}:{cmp:"eq",rest:e}}function $(e,t){if(!e)throw new _("missing numeric argument for "+t);if(!/^[0-9]+$/.test(e))throw new _("non-numeric argument to "+t+": "+e);const r=Number(e);if(!isFinite(r)||r>Number.MAX_SAFE_INTEGER)throw new _("numeric argument too large for "+t+": "+e);return r}function j(e,t){const{cmp:r,rest:n}=D(e);return{cmp:r,value:$(n,t)}}const H={b:512,c:1,w:2,k:1024,M:1048576,G:1073741824};function G(e){let t=e,r=512;if(!t)throw new _("invalid null argument to -size");const n=t.charAt(t.length-1);if(n>="0"&&n<="9");else{if(void 0===H[n])throw new _("invalid -size type '"+n+"'");r=H[n],t=t.slice(0,t.length-1)}const{cmp:s,rest:i}=D(t);return{cmp:s,blocks:$(i,"-size"),blockSize:r}}function Q(e,t){return k(e.cmp,S(t,e.blockSize),e.blocks)}function q(e,t,r,n){const{cmp:s,rest:i}=D(e);let o=r;n&&"lt"===s&&(o+=1e3*t-1e3);const a=1e3*t;return{cmp:s,refMs:o-$(i,"time predicate")*a,windowMs:a}}function W(e,t){if("gt"===t.cmp)return e>t.refMs;if("lt"===t.cmp)return e<t.refMs;const r=e-t.refMs;return r>0&&r<=t.windowMs}function K(){const e=process.getuid;if("function"==typeof e)try{return e()}catch(e){return-1}return-1}function X(){try{const e=u.userInfo();return e&&e.username?e.username:""}catch(e){return""}}function z(e){const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}let Y=null,J=null;function V(){if(Y)return Y;const e=[];try{const t=c.readFileSync("/etc/passwd","utf8").split(p);for(let r=0;r<t.length;r++){const n=t[r].split(":");if(n.length>=4){const t=parseInt(n[2],10),r=parseInt(n[3],10);isNaN(t)||isNaN(r)||e.push({name:n[0],uid:t,gid:r})}}}catch(e){}return Y=e,e}function Z(){if(J)return J;const e=[];try{const t=c.readFileSync("/etc/group","utf8").split(p);for(let r=0;r<t.length;r++){const n=t[r].split(":");if(n.length>=3){const t=parseInt(n[2],10);isNaN(t)||e.push({name:n[0],gid:t})}}}catch(e){}return J=e,e}function ee(e){const t=V();for(let r=0;r<t.length;r++)if(t[r].uid===e)return t[r].name;return e===K()?X():""}function te(e){const t=Z();for(let r=0;r<t.length;r++)if(t[r].gid===e)return t[r].name;return""}function re(e){if("number"==typeof e)return e;const t=String(e);if(/^[0-9]+$/.test(t))return parseInt(t,10);const r=V();for(let e=0;e<r.length;e++)if(r[e].name===t)return r[e].uid;const n=X();if(n&&n.toLowerCase()===t.toLowerCase())return K();throw new _("'"+t+"' is not the name of a known user")}function ne(e){if("number"==typeof e)return e;const t=String(e);if(/^[0-9]+$/.test(t))return parseInt(t,10);const r=Z();for(let e=0;e<r.length;e++)if(r[e].name===t)return r[e].gid;throw new _("'"+t+"' is not the name of a known group")}const se=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],ie=["January","February","March","April","May","June","July","August","September","October","November","December"];function oe(e){const t=new Date(e.getFullYear(),0,1);return Math.floor((e.getTime()-t.getTime())/864e5)+1}function ae(e,t){const r=new Date(e),n=r.getFullYear(),s=r.getMonth(),i=r.getDate(),o=r.getHours(),a=r.getMinutes(),c=r.getSeconds(),l=r.getDay(),u=o%12==0?12:o%12,h=function(e){const t=new Date(e.getFullYear(),e.getMonth(),e.getDate()),r=(t.getDay()+6)%7;t.setDate(t.getDate()-r+3);const n=t.getFullYear(),s=new Date(n,0,4),i=(s.getDay()+6)%7;return s.setDate(s.getDate()-i+3),{year:n,week:1+Math.round((t.getTime()-s.getTime())/6048e5)}}(r);switch(t){case"a":return B[l];case"A":return se[l];case"b":case"h":return x[s];case"B":return ie[s];case"c":return T(e);case"C":return E(String(Math.floor(n/100)),2,"0");case"d":return P(i);case"D":case"x":return P(s+1)+"/"+P(i)+"/"+E(String(n%100),2,"0");case"e":return E(String(i),2);case"F":return String(n)+"-"+P(s+1)+"-"+P(i);case"g":return E(String(h.year%100),2,"0");case"G":return String(h.year);case"H":return P(o);case"I":return P(u);case"j":return E(String(oe(r)),3,"0");case"k":return E(String(o),2);case"l":return E(String(u),2);case"m":return P(s+1);case"M":return P(a);case"n":return p;case"p":return o<12?"AM":"PM";case"r":return P(u)+":"+P(a)+":"+P(c)+(o<12?" AM":" PM");case"S":return P(c);case"t":return"\t";case"T":case"X":return P(o)+":"+P(a)+":"+P(c);case"u":return String(0===l?7:l);case"U":return P(function(e){const t=oe(e)-1;return Math.floor((t+7-e.getDay())/7)}(r));case"V":return P(h.week);case"w":return String(l);case"W":return P(function(e){const t=oe(e)-1;return Math.floor((t+7-(e.getDay()+6)%7)/7)}(r));case"y":return E(String(n%100),2,"0");case"Y":return String(n);case"Z":return function(e){const t=-e.getTimezoneOffset(),r=t>=0?"+":"-",n=Math.abs(t);return"GMT"+r+P(Math.floor(n/60))+":"+P(n%60)}(r);default:return""}}function ce(e,t){const r=Math.floor(e/1e3),n=Math.round(1e6*(e-1e3*r));return"@"===t?String(r)+"."+E(String(n),10,"0"):"+"===t?ae(e,"F")+"+"+ae(e,"T")+"."+E(String(n),10,"0"):ae(e,t)}function le(e){const t=l.dirname(e);return""===t?".":t}function ue(e,r){const n=r.stat;let s="",i=0;for(;i<e.length;){const o=e.charAt(i);if("%"!==o){s+=o,i++;continue}if(i++,i>=e.length){s+="%";break}if("%"===e.charAt(i)){s+="%",i++;continue}let a="";for(;i<e.length&&-1!=="-+ 0#".indexOf(e.charAt(i));)a+=e.charAt(i),i++;let c="";for(;i<e.length&&e.charAt(i)>="0"&&e.charAt(i)<="9";)c+=e.charAt(i),i++;let l="";if(i<e.length&&"."===e.charAt(i))for(i++;i<e.length&&e.charAt(i)>="0"&&e.charAt(i)<="9";)l+=e.charAt(i),i++;const u=e.charAt(i);i++;let h="",d=!1;switch(u){case"a":h=T(n.atimeMs);break;case"A":{const t=e.charAt(i);i++,h=ce(n.atimeMs,t);break}case"b":h=String(n.blocks),d=!0;break;case"c":h=T(n.ctimeMs);break;case"C":{const t=e.charAt(i);i++,h=ce(n.ctimeMs,t);break}case"d":h=String(r.depth),d=!0;break;case"D":h=String(n.dev),d=!0;break;case"f":h=r.name;break;case"F":h=r.fsType||"";break;case"g":h=te(n.gid);break;case"G":h=String(n.gid),d=!0;break;case"h":h=le(r.path);break;case"H":h=r.startPath;break;case"i":h=String(n.ino),d=!0;break;case"k":h=String(S(n.size,1024)),d=!0;break;case"l":h=r.linkTarget||"";break;case"m":h=(n.mode&t.PERM_ALL).toString(8);break;case"M":h=C(n.mode);break;case"n":h=String(n.nlink),d=!0;break;case"p":h=r.path;break;case"P":h=r.relativePath;break;case"s":h=String(n.size),d=!0;break;case"t":h=T(n.mtimeMs);break;case"T":{const t=e.charAt(i);i++,h=ce(n.mtimeMs,t);break}case"u":h=ee(n.uid);break;case"U":h=String(n.uid),d=!0;break;case"y":h=n.fileType;break;case"Y":h=r.targetType||"N";break;case"Z":h="";break;default:h="%"+u}if(l){const e=parseInt(l,10);!isNaN(e)&&h.length>e&&(h=h.slice(0,e))}if(c){const e=parseInt(c,10);!isNaN(e)&&h.length<e&&(h=-1!==a.indexOf("-")?I(h,e):d&&-1!==a.indexOf("0")?E(h,e,"0"):E(h,e))}s+=h}return s}function he(e,t){const r=e.stat,n=ee(r.uid)||String(r.uid),s=te(r.gid)||String(r.gid);let i=e.path;return e.linkTarget&&(i=i+" -> "+e.linkTarget),[E(String(r.ino),8),E(String(r.blocks),6),C(r.mode),E(String(r.nlink),3),I(n,8),I(s,8),E(String(r.size),8),N(r.mtimeMs,t),i].join(" ")+p}function de(e,t,r,n){const s={path:t,code:r,message:n};e.errors.push(s),e.exitCode=1,e.options.onError&&e.options.onError(s)}function fe(e){return";"===e||e===d+";"?"semicolon":"+"===e?"plus":null}function pe(e,r){return e===t.EXEC_PLACEHOLDER?r:-1!==e.indexOf(t.EXEC_PLACEHOLDER)?e.split(t.EXEC_PLACEHOLDER).join(r):e}function _e(e,t,r,n){return new Promise(s=>{let i;try{i=(0,h.spawn)(e,t,{cwd:r,windowsHide:!0,stdio:n?["ignore","pipe","pipe"]:["ignore","inherit","inherit"]})}catch(e){return void s({status:1,stdout:"",stderr:"",error:String(e)})}let o="",a="";n&&i.stdout&&i.stdout.on("data",e=>{o+=e.toString()}),n&&i.stderr&&i.stderr.on("data",e=>{a+=e.toString()}),i.on("error",e=>{s({status:1,stdout:o,stderr:a,error:e.message})}),i.on("close",e=>{s({status:null===e?1:e,stdout:o,stderr:a})})})}function ge(e,r){return a(this,void 0,void 0,function*(){const n=r.state,s=r.options;if(0===e.template.length)throw new _("-exec requires a command");if(e.interactive){const t=e.template.join(" ")+" "+r.path;let n=!1;if(s.confirm&&(n=yield s.confirm(t)),!n)return!1}const i=e.execdir?"./"+r.name:r.path,o=e.execdir?le(r.path):process.cwd();if(e.batch){const r=[];for(let n=0;n<e.template.length;n++){const s=e.template[n];if(s===t.EXEC_PLACEHOLDER)break;r.push(pe(s,i))}if(0===r.length)throw new _("-exec requires a command");let s=null;for(let t=0;t<n.execBatches.length;t++){const i=n.execBatches[t];if(i.dir!==o||i.execdir!==e.execdir)continue;if(i.argv.length<r.length)continue;let a=!0;for(let e=0;e<r.length;e++)if(i.argv[e]!==r[e]){a=!1;break}if(a){s=i;break}}return s||(s={argv:r.slice(),dir:o,execdir:e.execdir},n.execBatches.push(s)),s.argv.push(i),!0}const a=[];for(let t=0;t<e.template.length;t++)a.push(pe(e.template[t],i));const c=a[0],l=a.slice(1),u="capture"===s.execStdio,h=yield _e(c,l,o,u);return u&&(h.stdout&&r.write(h.stdout),h.stderr&&r.write(h.stderr)),h.error?(de(n,r.path,"EPATHEXEC",h.error),!1):0===h.status})}function me(e){return a(this,void 0,void 0,function*(){const t=e.execBatches;e.execBatches=[];for(let r=0;r<t.length;r++){const n=t[r];if(0===n.argv.length)continue;const s=n.argv[0],i=n.argv.slice(1),o="capture"===e.options.execStdio,a=yield _e(s,i,n.dir,o);o&&(a.stdout&&e.outputChunks.push(a.stdout),a.stderr&&e.outputChunks.push(a.stderr)),a.error?de(e,n.argv.join(" "),"EPATHEXEC",a.error):0!==a.status&&(e.exitCode=1)}})}t.EXEC_PLACEHOLDER="{}";const ye={name:"true",evaluate:()=>a(void 0,void 0,void 0,function*(){return!0})},Ae={name:"false",evaluate:()=>a(void 0,void 0,void 0,function*(){return!1})};function ve(e,t){return{name:"and",evaluate:r=>a(this,void 0,void 0,function*(){return!!(yield e.evaluate(r))&&t.evaluate(r)})}}function be(e,t){return{name:"or",evaluate:r=>a(this,void 0,void 0,function*(){return!!(yield e.evaluate(r))||t.evaluate(r)})}}function we(e,t){return{name:"comma",evaluate:r=>a(this,void 0,void 0,function*(){return yield e.evaluate(r),t.evaluate(r)})}}function Ee(e){let t="",r=0;const n="(){}+?|";for(;r<e.length;){const s=e.charAt(r);if(s===d){const s=e.charAt(r+1);if(!s){t+=d+d,r++;continue}-1!==n.indexOf(s)?t+=s:t+=d+s,r+=2;continue}-1===n.indexOf(s)?(t+=s,r++):(t+=d+s,r++)}return t}function Ie(e,t,r){const n="posix-basic"===r?Ee(e):e;try{return new RegExp("^(?:"+n+")$",t?"i":"")}catch(t){throw new _("failed to compile regular expression "+e+": "+String(t))}}function Se(e){return")"!==e&&","!==e&&"-o"!==e&&"-or"!==e&&"-a"!==e&&"-and"!==e}function Pe(e){try{return c.statSync(e)}catch(t){throw new _("cannot stat `"+e+"': "+String(t.message||t))}}class ke{constructor(e,t){this.tokens=e,this.pos=0,this.options=t,this.noDefaultPrint=!1,this.hasAction=!1}parse(){if(0===this.tokens.length)return ye;const e=this.parseComma();if(this.pos<this.tokens.length)throw new _("paths must precede expression: `"+this.tokens[this.pos]+"'");return e}peek(){return this.pos<this.tokens.length?this.tokens[this.pos]:void 0}advance(){if(this.pos>=this.tokens.length)throw new _("unexpected end of expression");const e=this.tokens[this.pos];return this.pos++,e}argument(e){if(this.pos>=this.tokens.length)throw new _("missing argument to `"+e+"'");const t=this.tokens[this.pos];return this.pos++,t}parseComma(){let e=this.parseOr();for(;","===this.peek();)this.advance(),e=we(e,this.parseOr());return e}parseOr(){let e=this.parseAnd(),t=this.peek();for(;"-o"===t||"-or"===t;)this.advance(),e=be(e,this.parseAnd()),t=this.peek();return e}parseAnd(){let e=this.parseUnary(),t=this.peek();for(;void 0!==t&&("-a"===t||"-and"===t||Se(t));)"-a"!==t&&"-and"!==t||this.advance(),e=ve(e,this.parseUnary()),t=this.peek();return e}parseUnary(){const e=this.peek();return"!"===e||"-not"===e?(this.advance(),function(e){return{name:"not",evaluate:t=>a(this,void 0,void 0,function*(){return!(yield e.evaluate(t))})}}(this.parseUnary())):this.parsePrimary()}parsePrimary(){const e=this.peek();if(void 0===e)throw new _("unexpected end of expression");if("("===e){this.advance();const e=this.parseComma();if(")"!==this.peek())throw new _("missing closing parenthesis");return this.advance(),e}if(")"===e)throw new _("unexpected closing parenthesis");return this.advance(),this.buildPredicate(e)}buildPredicate(e){const r=this.options;switch(e){case"-name":case"-iname":{const t=this.argument(e),n="-iname"===e,s=r.nameMatchMode;return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return w(e.name,t,s,n)})}}case"-path":case"-wholename":case"-ipath":case"-iwholename":{const t=this.argument(e),n="-ipath"===e||"-iwholename"===e,s=r.nameMatchMode;return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return w(e.path,t,s,n)})}}case"-lname":case"-ilname":{const t=this.argument(e),r="-ilname"===e;return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return!!e.linkTarget&&b(t,r).test(e.linkTarget)})}}case"-regex":case"-iregex":{const t=Ie(this.argument(e),"-iregex"===e,r.regextype);return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return t.test(e.path)})}}case"-type":case"-xtype":{const t=this.argument(e),r={},n=t.split(",");for(let e=0;e<n.length;e++){const t=n[e].trim();if(0!==t.length){if(1!==t.length||-1==="fdlbcpsD".indexOf(t))throw new _("Unknown file type `"+t+"'");r[t]=!0}}const s="-xtype"===e;return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){const t=s?e.targetType||"N":e.stat.fileType;return!0===r[t]})}}case"-size":{const t=G(this.argument(e));return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return Q(t,e.stat.size)})}}case"-perm":{const t=L(this.argument(e));return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return U(t,e.stat.mode)})}}case"-user":{const t=re(this.argument(e));return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return e.stat.uid===t})}}case"-group":{const t=ne(this.argument(e));return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return e.stat.gid===t})}}case"-uid":{const t=j(this.argument(e),"-uid");return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return k(t.cmp,e.stat.uid,t.value)})}}case"-gid":{const t=j(this.argument(e),"-gid");return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return k(t.cmp,e.stat.gid,t.value)})}}case"-links":{const t=j(this.argument(e),"-links");return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return k(t.cmp,e.stat.nlink,t.value)})}}case"-inum":{const t=j(this.argument(e),"-inum");return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return k(t.cmp,e.stat.ino,t.value)})}}case"-empty":return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){if(e.stat.isDirectory)try{return 0===(yield c.promises.readdir(e.path)).length}catch(t){return de(e.state,e.path,"EREADDIR",String(t.message||t)),!1}return!!e.stat.isFile&&0===e.stat.size})};case"-readable":case"-writable":case"-executable":{const t="-readable"===e?c.constants.R_OK:"-writable"===e?c.constants.W_OK:c.constants.X_OK;return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){try{return yield c.promises.access(e.path,t),!0}catch(e){return!1}})}}case"-mtime":case"-atime":case"-ctime":{const n=q(this.argument(e),t.DAY_SECONDS,r.curDayStartMs,!0);return this.buildTimePredicate(e,n)}case"-mmin":case"-amin":case"-cmin":{const n=q(this.argument(e),t.MINUTE_SECONDS,r.startTimeMs,!1);return this.buildTimePredicate(e,n)}case"-newer":case"-anewer":case"-cnewer":{const t=Pe(this.argument(e)),r="-anewer"===e?t.atimeMs:"-cnewer"===e?t.ctimeMs:t.mtimeMs;return{name:e,evaluate:t=>a(this,void 0,void 0,function*(){return("-anewer"===e?t.stat.atimeMs:"-cnewer"===e?t.stat.ctimeMs:t.stat.mtimeMs)>r})}}case"-samefile":{const t=Pe(this.argument(e));return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return e.stat.dev===t.dev&&e.stat.ino===t.ino})}}case"-true":case"-noleaf":case"-warn":case"-nowarn":case"-nouser":case"-nogrp":return ye;case"-false":return Ae;case"-prune":return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return!e.options.depth&&e.stat.isDirectory&&e.prune(),!0})};case"-quit":return this.hasAction=!0,{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return e.requestQuit(),!0})};case"-print":return this.hasAction=!0,this.noDefaultPrint=!0,{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return e.write(e.path+p),!0})};case"-print0":return this.hasAction=!0,this.noDefaultPrint=!0,{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return e.write(e.path+f),!0})};case"-printf":{const t=this.argument(e);return this.hasAction=!0,this.noDefaultPrint=!0,{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return e.write(ue(t,e)),!0})}}case"-ls":return this.hasAction=!0,this.noDefaultPrint=!0,{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return e.write(he(e,e.options.startTimeMs)),!0})};case"-fprint":case"-fprint0":{const t=this.argument(e),r="-fprint0"===e?f:p;return this.hasAction=!0,this.noDefaultPrint=!0,{name:e,evaluate:e=>a(this,void 0,void 0,function*(){try{return yield c.promises.appendFile(t,e.path+r),!0}catch(t){return de(e.state,e.path,"EWRITE",String(t.message||t)),!1}})}}case"-fprintf":{const t=this.argument(e),r=this.argument(e);return this.hasAction=!0,this.noDefaultPrint=!0,{name:e,evaluate:e=>a(this,void 0,void 0,function*(){try{return yield c.promises.appendFile(t,ue(r,e)),!0}catch(t){return de(e.state,e.path,"EWRITE",String(t.message||t)),!1}})}}case"-delete":return this.hasAction=!0,this.noDefaultPrint=!0,r.depth=!0,{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return e.remove()})};case"-exec":case"-execdir":case"-ok":case"-okdir":{const t=this.collectExecWords(e);return this.hasAction=!0,this.noDefaultPrint=!0,{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return ge(t,e)})}}case"-maxdepth":return r.maxdepth=$(this.argument(e),"-maxdepth"),ye;case"-mindepth":return r.mindepth=$(this.argument(e),"-mindepth"),ye;case"-depth":case"-d":return r.depth=!0,r.explicitDepth=!0,ye;case"-follow":case"-L":return r.symlink="L",ye;case"-H":return r.symlink="H",ye;case"-P":return r.symlink="P",ye;case"-xdev":case"-mount":return r.xdev=!0,ye;case"-daystart":return r.daystart=!0,r.curDayStartMs=z(r.startTimeMs),ye;case"-regextype":return r.regextype=this.argument(e),ye;case"-ignore_readdir_race":return r.ignoreReaddirRace=!0,ye}if(8===e.length&&0===e.indexOf("-newer"))return this.buildNewerXY(e);throw new _("unknown predicate `"+e+"'")}buildTimePredicate(e,t){return{name:e,evaluate:r=>a(this,void 0,void 0,function*(){let n;return n="-atime"===e||"-amin"===e?r.stat.atimeMs:"-ctime"===e||"-cmin"===e?r.stat.ctimeMs:r.stat.mtimeMs,W(n,t)})}}buildNewerXY(e){const t=e.charAt(6),r=e.charAt(7),n=this.argument(e);let s;if("t"===r){const t=Date.parse(n);if(isNaN(t))throw new _("invalid date `"+n+"' for "+e);s=t}else{if("a"!==r&&"B"!==r&&"c"!==r&&"m"!==r)throw new _("unknown predicate `"+e+"'");{const e=Pe(n);s="a"===r?e.atimeMs:"c"===r?e.ctimeMs:"m"===r?e.mtimeMs:e.birthtimeMs}}return{name:e,evaluate:e=>a(this,void 0,void 0,function*(){return("a"===t?e.stat.atimeMs:"c"===t?e.stat.ctimeMs:"B"===t?e.stat.birthtimeMs:e.stat.mtimeMs)>s})}}collectExecWords(e){const t=[];let r=null,n=!0;for(;n;){const s=this.peek();if(void 0===s)throw new _("missing argument to `"+e+"'");this.advance();const i=fe(s);i?(r=i,n=!1):t.push(s)}if(0===t.length)throw new _("missing argument to `"+e+"'");return{template:t,execdir:"-execdir"===e||"-okdir"===e,batch:"plus"===r,interactive:"-ok"===e||"-okdir"===e}}}function Oe(e,t){const r=new ke(e,t);return{root:r.parse(),noDefaultPrint:r.noDefaultPrint,hasAction:r.hasAction}}function Ce(e,t){return""===e?t:e.charAt(e.length-1)===l.sep?e+t:e+l.sep+t}function Re(e,t,r,n,s,i){return a(this,void 0,void 0,function*(){let o=null;if("L"===n.symlink||"H"===n.symlink&&s)try{o=yield c.promises.stat(e)}catch(e){if(!function(e){const t=e.code;return"ENOENT"===t||"ELOOP"===t||"ENOTDIR"===t}(e))throw e;o=null}o||(o=yield c.promises.lstat(e));const u=R(o),h=l.basename(e);let d,f="";if(t>0){const t=r.charAt(r.length-1)===l.sep?r:r+l.sep;f=0===e.indexOf(t)?e.slice(t.length):e}return u.isSymbolicLink&&(d=void 0!==i?i:yield function(e){return a(this,void 0,void 0,function*(){try{const t=yield c.promises.readlink(e);return"string"==typeof t?t:void 0}catch(e){return}})}(e)),{path:e,name:h,depth:t,startPath:r,relativePath:f,stat:u,linkTarget:d,isStart:s}})}t.ExpressionParser=ke;class Be{constructor(e,t){this.path=e.path,this.name=e.name,this.depth=e.depth,this.stat=e.stat,this.isStart=e.isStart,this.startPath=e.startPath,this.relativePath=e.relativePath,this.linkTarget=e.linkTarget,this.options=t.options,this.state=t}prune(){this.state.stopAtCurrentLevel=!0}requestQuit(){this.state.quit=!0}write(e){e&&(this.state.outputChunks.push(e),this.state.options.onOutput&&this.state.options.onOutput(e))}remove(){return a(this,void 0,void 0,function*(){const e=this.state;try{return this.stat.isDirectory?yield c.promises.rmdir(this.path):yield c.promises.unlink(this.path),e.deleted.push(this.path),!0}catch(t){return!("ENOENT"!==t.code||!e.options.ignoreReaddirRace)||(de(e,this.path,"EDELETE","cannot delete "+this.path+": "+String(t.message||t)),!1)}})}}function xe(e,t,r,n,s,i,o,l){return a(this,void 0,void 0,function*(){const u=o.options;if(o.quit)return;if(u.signal&&u.signal.aborted)return void(o.quit=!0);if(u.maxResults>0&&o.entries.length>=u.maxResults)return void(o.quit=!0);let h;try{h=yield Re(e,t,r,u,n)}catch(t){const r=t.code||"ESTAT";return void("ENOENT"===r&&u.ignoreReaddirRace||de(o,e,r,"cannot stat '"+e+"': "+String(t.message||t)))}if(!h)return;o.visited++,l.haveStartDev||(l.startDev=h.stat.dev,l.haveStartDev=!0);const d=new Be(h,o);d.targetType=yield function(e){return a(this,void 0,void 0,function*(){if(!e.stat.isSymbolicLink)return e.stat.fileType;try{return O((yield c.promises.stat(e.path)).mode)}catch(e){return"N"}})}(h);const f=t>=u.mindepth,_=h.stat.isDirectory&&(u.maxdepth<0||t<u.maxdepth)&&!(u.xdev&&h.stat.dev!==l.startDev),g=h.stat.dev+":"+h.stat.ino;let m=_;if(m&&l.ancestors[g]&&(m=!1),!u.depth){if(o.stopAtCurrentLevel=!1,f){let e;try{e=yield s.evaluate(d)}catch(t){de(o,h.path,"EEVAL",String(t.message||t)),e=!1}e&&(i&&d.write(h.path+p),Te(o,h))}o.stopAtCurrentLevel&&(m=!1)}if(!o.quit){if(m){l.ancestors[g]=!0;let e=[];try{e=yield function(e){return a(this,void 0,void 0,function*(){const t=[],r=c.promises.readdir;try{const n=yield r(e,{withFileTypes:!0});for(let e=0;e<n.length;e++){const r=n[e];"string"!=typeof r?t.push({name:r.name,isDirectory:r.isDirectory(),isFile:r.isFile(),isSymbolicLink:r.isSymbolicLink()}):t.push({name:r})}return t}catch(e){}const n=yield c.promises.readdir(e);for(let e=0;e<n.length;e++)t.push({name:String(n[e])});return t})}(h.path)}catch(t){const r=t.code||"EREADDIR";"ENOENT"===r&&u.ignoreReaddirRace||de(o,h.path,r,"cannot read directory '"+h.path+"': "+String(t.message||t)),e=[]}for(let n=0;n<e.length&&!o.quit;n++){const a=e[n],c=Ce(h.path,a.name);yield xe(c,t+1,r,!1,s,i,o,l)}delete l.ancestors[g]}if(!o.quit&&u.depth&&f){let e;o.stopAtCurrentLevel=!1;try{e=yield s.evaluate(d)}catch(t){de(o,h.path,"EEVAL",String(t.message||t)),e=!1}e&&(i&&d.write(h.path+p),Te(o,h))}}})}function Te(e,t){e.entries.push(t),e.options.onMatch&&e.options.onMatch(t)}function Ne(e){const r=e||{},n=Date.now();let s=["."];r.paths&&(s=Array.isArray(r.paths)?r.paths.slice():[r.paths]),0===s.length&&(s=["."]);let i="P";r.follow&&(i="L"),r.symlink&&(i=r.symlink);const o=!0===r.daystart;return{paths:s,maxdepth:void 0===r.maxdepth?-1:r.maxdepth,mindepth:void 0===r.mindepth?0:r.mindepth,depth:!0===r.depth,explicitDepth:!0===r.depth,symlink:i,xdev:!0===r.xdev,daystart:o,ignoreReaddirRace:!0===r.ignoreReaddirRace,nameMatchMode:r.nameMatchMode||"auto",regextype:r.regextype||"findutils-default",startTimeMs:n,curDayStartMs:o?z(n):n-1e3*t.DAY_SECONDS,outputBlockSize:1024,maxResults:void 0===r.maxResults?0:r.maxResults,execStdio:r.execStdio||"inherit",signal:r.signal,onError:r.onError,onOutput:r.onOutput,onMatch:r.onMatch,confirm:r.confirm}}function Fe(e,t){e.push(t)}function Me(e,t,r){void 0!==r&&(e.push(t),e.push(String(r)))}function Le(e,t,r){if(void 0===r)return;const n=Array.isArray(r)?r:[r];for(let r=0;r<n.length;r++)e.push(t),e.push(n[r])}function Ue(e){const t=[];return Le(t,"-name",e.name),Le(t,"-iname",e.iname),Le(t,"-path",e.path),Le(t,"-ipath",e.ipath),void 0!==e.regex&&(t.push("-regex"),t.push(e.regex instanceof RegExp?e.regex.source:String(e.regex))),void 0!==e.iregex&&(t.push("-iregex"),t.push(e.iregex instanceof RegExp?e.iregex.source:String(e.iregex))),Me(t,"-type",e.type),Me(t,"-xtype",e.xtype),Me(t,"-size",e.size),Me(t,"-perm",e.perm),Me(t,"-user",e.user),Me(t,"-group",e.group),Me(t,"-uid",e.uid),Me(t,"-gid",e.gid),Me(t,"-links",e.links),Me(t,"-inum",e.inum),e.empty&&Fe(t,"-empty"),e.readable&&Fe(t,"-readable"),e.writable&&Fe(t,"-writable"),e.executable&&Fe(t,"-executable"),Me(t,"-mtime",e.mtime),Me(t,"-mmin",e.mmin),Me(t,"-atime",e.atime),Me(t,"-amin",e.amin),Me(t,"-ctime",e.ctime),Me(t,"-cmin",e.cmin),void 0!==e.newer&&(t.push("-newer"),t.push(e.newer instanceof Date?e.newer.toISOString():String(e.newer))),void 0!==e.anewer&&(t.push("-anewer"),t.push(e.anewer instanceof Date?e.anewer.toISOString():String(e.anewer))),void 0!==e.cnewer&&(t.push("-cnewer"),t.push(e.cnewer instanceof Date?e.cnewer.toISOString():String(e.cnewer))),void 0!==e.newermt&&(t.push("-newermt"),t.push(e.newermt instanceof Date?e.newermt.toISOString():String(e.newermt))),function(e,t){t.print&&Fe(e,"-print"),t.print0&&Fe(e,"-print0"),void 0!==t.printf&&(e.push("-printf"),e.push(t.printf)),t.ls&&Fe(e,"-ls"),t.delete&&Fe(e,"-delete");const r=t.exec;if(void 0!==r){const t=Array.isArray(r)?r:[r];e.push("-exec");for(let r=0;r<t.length;r++)e.push(t[r]);e.push(";")}const n=t.execdir;if(void 0!==n){const t=Array.isArray(n)?n:[n];e.push("-execdir");for(let r=0;r<t.length;r++)e.push(t[r]);e.push(";")}t.quitOnFirstMatch&&Fe(e,"-quit")}(t,e),t}function De(e,t,r){return a(this,void 0,void 0,function*(){const n=Ne(r);e&&e.length>0&&(n.paths=e.slice());const s=Oe(t,n),i=function(e){return{options:e,outputChunks:[],entries:[],errors:[],deleted:[],exitCode:0,quit:!1,stopAtCurrentLevel:!1,visited:0,uid:K(),username:X(),execBatches:[]}}(n),o=!s.noDefaultPrint,a={ancestors:{},startDev:0,haveStartDev:!1};for(let e=0;e<n.paths.length&&!i.quit;e++){const t=n.paths[e];a.haveStartDev=!1,a.ancestors={},yield xe(t,0,t,!0,s.root,o,i,a)}return yield me(i),{entries:i.entries,output:i.outputChunks.join(""),errors:i.errors,deleted:i.deleted,exitCode:i.exitCode,stopped:i.quit,visited:i.visited}})}function $e(e,t){return a(this,void 0,void 0,function*(){const r=[],n=[];let s=0;for(;s<e.length;){const t=e[s];if("("===t||"!"===t||")"===t)break;if(t.length>0&&"-"===t.charAt(0))break;r.push(t),s++}for(;s<e.length;)n.push(e[s]),s++;return 0===r.length&&r.push("."),De(r,n,t)})}function je(e){return a(this,void 0,void 0,function*(){const t=e||{},r=t.paths?Array.isArray(t.paths)?t.paths.slice():[t.paths]:["."],n=[],s=Ue(t);for(let e=0;e<s.length;e++)n.push(s[e]);if(t.expression)for(let e=0;e<t.expression.length;e++)n.push(t.expression[e]);return De(r.length>0?r:["."],n,t)})}},7576(e,t){"use strict";t.generateMessageId=function(){const e=Date.now(),t=(e,t)=>(e>>>0).toString(16).padStart(t,"0").slice(-t),n=e>>>0,s=Math.floor(e/4294967296),i=function(){const e=globalThis.crypto;if(e&&"function"==typeof e.randomUUID){const t=String(e.randomUUID()).replace(/-/g,"");let r="";for(let e=0;e<t.length&&r.length<20;e+=1)12!==e&&16!==e&&(r+=t[e]);if(20===r.length)return r}r||(r=!0,console.warn("id.ts: crypto.randomUUID is unavailable, falling back to Math.random; message ids stay unique but are no longer collision-resistant."));let t="";for(;t.length<20;)t+=Math.floor(16*Math.random()).toString(16);return t.slice(0,20)}(),o=(8|3&parseInt(i[0],16)).toString(16);return t(n,8)+"-"+t(s,4)+"-4"+i.slice(1,4)+"-"+o+i.slice(4,7)+"-"+i.slice(7,19)};let r=!1},2578(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.AxleAgent=void 0;const s=r(6418),i=r(5214),o=r(8404),a=r(7576),c=r(8404),l=r(2201),u=r(8515),h=r(651),d=r(9237),f=r(4859);t.AxleAgent=class{constructor(e,t){var r,n,o;this._stopRequested=!1,this.name=e.name,this.modelName=e.model,this.skillsFolder=null!==(r=e.skillsFolder)&&void 0!==r?r:"skills",this.prompt=new d.AxlePrompt(this.skillsFolder),this.model=new s.Model(e.key,e.url,e.model,this.prompt,void 0,void 0,null!==(n=e.responses)&&void 0!==n&&n),h.logger.log(`starting ${this.modelName}`),this.executors=(0,i.discoverExecutors)(this.skillsFolder),this.conduit=t;const a=null!==(o=e.workingDir)&&void 0!==o?o:process.cwd();this.cd(a)}buildRuntime(){this.workingDir&&(this.runtime={workingDir:this.workingDir,fullSkillConfig:(0,l.getFullSkillConfig)()})}cd(e){return n(this,void 0,void 0,function*(){const t=(0,l.parsePath)(e);"remote"===t.kind?t.server?(this.workingDir=t,yield this.prompt.buildOsPrompt(t),h.logger.log(`[${this.name}]: Working directory changed to remote server '${t.serverName}' at '${t.path}' (config resolved)`),this.conduit.sendMessage("",`Working on remote directory: ${t.serverName}:${t.path}`)):(h.logger.log(`[${this.model}]: Working directory changed to remote server '${t.serverName}' at '${t.path}' but no 'ssh'/'scp' config was found`),this.conduit.sendMessage("",`Working on remote directory: ${t.serverName}:${t.path} (warning: no matching server configuration found)`)):(this.workingDir=t,yield this.prompt.buildOsPrompt(t),h.logger.log(`[${this.name}]: Working directory changed to local path '${t.path}'`),this.conduit.sendMessage("",`Working on directory: ${t.path}`)),this.buildRuntime()})}getCwd(){return(0,l.getFullWorkingPath)(this.workingDir)}getRemoteConfig(){return this.workingDir&&"remote"===this.workingDir.kind?this.workingDir.server:null}getWorkingDir(){var e;return null!==(e=this.workingDir)&&void 0!==e?e:null}getFullSkillConfig(){var e,t;return this.runtime||this.buildRuntime(),null!==(t=null===(e=this.runtime)||void 0===e?void 0:e.fullSkillConfig)&&void 0!==t?t:(0,l.getFullSkillConfig)()}getAllSessions(e){var t;return(null!==(t=this.session)&&void 0!==t?t:new f.AxleSession(this.name)).getAll(e)}readSession(e,t){var r;return(null!==(r=this.session)&&void 0!==r?r:new f.AxleSession(this.name)).read(e,t)}loadSession(e){var t;const r=null!==(t=this.session)&&void 0!==t?t:new f.AxleSession(this.name);if(!r.read(e))return!1;if(this.clear(),!r.load(e))return!1;this.session=r,this.model.clear();for(const e of r.conversations)for(const t of e.turns){const e=t.request?t.request.content:"",r=t.response?t.response.content:"";e.length>0&&this.model.conversationHistory.push({role:"user",content:e,id:t.msgId}),r.length>0&&this.model.conversationHistory.push({role:"assistant",content:r,id:t.msgId})}return h.logger.log(`[${this.name}]: loaded session ${e} with ${this.model.conversationHistory.length} history entr${1===this.model.conversationHistory.length?"y":"ies"}`),this.conduit.sendMessage("","\nSession loaded. The conversation continues from it.\n"),!0}requestStop(){this._stopRequested=!0,h.logger.log(`[${this.name}]: Stop requested for ${this.modelName}`)}stop(){this.requestStop()}isStopping(){return this._stopRequested}reload(){this.prompt.reloadSkills(),this.workingDir&&this.prompt.buildOsPrompt(this.workingDir),this.session&&this.session.flush(),this.model.clear(),this.conduit.sendMessage("","\nSkills reloaded and conversation reset.\n")}deleteMessage(e){return n(this,void 0,void 0,function*(){let t=yield this.model.deleteMessage(e);const r=this.session;if(r)try{r.deleteTurn(e)&&(t=!0)}catch(t){const r=t instanceof Error?t.message:String(t);h.logger.log(`[${this.name}]: Failed to delete message ${e} from the session: ${r}`)}return h.logger.log(`[${this.name}]: Delete message ${e}: ${t?"done":"nothing to delete"}`),t})}clear(){this.session&&this.session.flush(),this.model.clear(),this.conduit.sendMessage("","\nConversation history cleared.\n")}getSkills(){const e=this.prompt.getSkillsSummary();return this.conduit.sendMessage("",e),e}talk(e,t,r){return n(this,void 0,void 0,function*(){var n;let s=e.userinput,i=r,o=null===(n=e.attachments)||void 0===n?void 0:n.slice(0,5),a=!0;h.logger.log(`[${this.name}]: ${s}`);let c=0;this._stopRequested=!1,this.conduit.send({id:"",message:"running",content:"",format:"",signal:"state",misc:{}}),this.session||(this.session=new f.AxleSession(this.name)),this.session.newConversation();let l=!1,u=!0,d=t;try{for(;a;){if(this._stopRequested){h.logger.log(`[${this.name}]: Task loop stopped by user request.`),this.conduit.sendMessage("","The task was stopped by user request.","md",void 0,this.session);break}this.session.appendRequest(i,s,null!=o?o:null,u?"user":"auto");const e=yield this.model.chat({userinput:s,attachments:o,prevRespId:d,messageId:i});d=void 0,u=!1;const t=e.text;let r,n=null;e.binary&&(n={type:"image/png",content:e.binary}),this.session.appendResponse(i,e.respId,t,n),({result:r,attempt:c}=yield this.processLlmResponse(e,i,t,c)),({msgId:i,followup:a,userInput:s,currentAttachments:o}=this.processActionCall(r,i,a,s,o))}}catch(e){const t=e instanceof Error?e.message:String(e);h.logger.log(`[${this.name}]: Task loop failed: ${t}`),this.conduit.sendMessage(i,`Task failed: ${t}`,"md",void 0,this.session)}finally{l=this._stopRequested,this._stopRequested=!1;const e={id:"",message:"idle",content:"",format:"",signal:"state",misc:{}};this.conduit.send(e)}if(!l){const e=this.session?this.session.conversations:[],t=e[e.length-1],r=t?t.turns.length:0;h.logger.log(`[${this.name}]: The requested task is completed.`),this.conduit.sendMessage(i,`Conversation is completed in ${r} turns.`)}s="",i="",a=!0})}processActionCall(e,t,r,n,s){if(c.ExecutionResponse.isExecutionResponse(e)){h.logger.log(`[${this.name}]: continue: ${e.sequential}`);const i=e.print,c=e.persist;let l;if(i&&!0===i&&e.content)if("image"===e.format)l=(0,o.buildImageUri)(e.mimeType,e.content),this.conduit.sendMessage(t,"",e.format,l,this.session);else if("svg"===e.format)this.conduit.sendMessage(t,"",e.format,e.content,this.session);else{const r=e.format?e.format:"md",n={id:t,message:e.content,content:"",format:r,signal:c?"Persistable":"",misc:e.misc};this.conduit.send(n,this.session)}if(r=e.sequential){let r;n=e.prompt+"\n\n","image"===e.format?(s=[{format:e.mimeType,content:e.content}],r=(0,o.buildImageUri)(e.mimeType,e.content)):(n+=e.content,s=void 0),t=(0,a.generateMessageId)(),this.conduit.sendMessage(t,n,e.format,r)}}else if(r=!1,e){const r={id:t,message:JSON.stringify(e),content:"",format:"md",signal:"Persistable",misc:{}};this.conduit.send(r,this.session)}else h.logger.log(`[${this.name}]: Empty result`),this.conduit.sendMessage(t,"No response","",void 0,this.session);return{msgId:t,followup:r,userInput:n,currentAttachments:s}}processLlmResponse(e,t,r,s){return n(this,void 0,void 0,function*(){if(e.binary){const r=(0,o.buildImageUri)("image/png",e.binary);this.conduit.sendMessage(t,"","image",r,this.session)}const[n,a,l]=(0,i.validate)(r);h.logger.log(`[${this.name}]: Response format: ${n}`);let d=null;if(n===u.TextType.TRUNCATED_JSON)if(h.logger.log(`[${this.name}]: JSON response is truncated. attempt = ${s}. Truncated JSON:\n${r}`),s<3){const e="The previous response is truncated, please regenerate the response and consider seperate the response into smaller pieces.";d=new c.ExecutionResponse("",e,!0,!1),s+=1}else d=new c.ExecutionResponse("Unrecognized response","",!1,!0);else if(n===u.TextType.MALFORMATED_JSON)if(h.logger.log(`[${this.name}]: JSON response format is incorrect. attempt = ${s}. Malformed JSON:\n${r}`),s<3){const e="The JSON format of the previous response is incorrect, please correct the JSON format and regenerate the response.";d=new c.ExecutionResponse("",e,!0,!1),s+=1}else d=new c.ExecutionResponse("Unrecognized response","",!1,!0);else n===u.TextType.JSON||n==u.TextType.TRAILING_JSON?(d=yield this.execute(a,t),l&&this.conduit.sendMessage(t,`${l}`,"md",void 0,this.session)):d=new c.ExecutionResponse(r,"",!1,!0,"md","",!0);return{result:d,attempt:s}})}execute(e,t){return n(this,void 0,void 0,function*(){var r;try{const n=yield this.executors,s=(0,i.parseActionJson)(e),a=null==s?void 0:s.action,l=null==s?void 0:s.thinking;if(l&&this.conduit.sendMessage(t,l,"reasoning",void 0,this.session),!(a in n)){h.logger.log("[${this.name}]: no action is defined");const r=(0,o.extractJson)(e);if(r){const e={};for(const t of r.properties||[])e[t.name]=t.value;let n="";for(const r in e)"svg"===r?(h.logger.log(`[${this.name}]: receiving svg image...`),this.conduit.sendMessage(t,"","svg",e[r],this.session)):n+=`### ${r}:\n\n${e[r]}\n\n`;let s=!1;return Object.keys(e).length>0&&(s=!0),new c.ExecutionResponse(n,"",!1,s,"md","",!0)}return new c.ExecutionResponse("","",!1,!0)}{h.logger.log(`[${this.name}]: find executor for action ${a}`);const i=null!==(r=null==s?void 0:s.properties)&&void 0!==r?r:[],o=300,l=i.filter(e=>null!=e&&"string"==typeof e.name).map(e=>{var t;const r="string"==typeof e.value?e.value:void 0===e.value?"":null!==(t=JSON.stringify(e.value))&&void 0!==t?t:"",n=r.length>o?`${r.slice(0,o)}...`:r;return`${e.name}: ${n}`});this.conduit.sendMessage(t,`Executing ${a}...`,"exec_action",l.join("\n"),this.session);const u=n[a];try{return yield u(e,this.runtime)}catch(e){const r=e instanceof Error?e.message:String(e);return h.logger.log(`[${this.name}]: executor ${a} failed: ${r}`),this.conduit.sendMessage(t,`Error executing ${a}: ${r}`,"md",void 0,this.session),new c.ExecutionResponse(`Error executing ${a}: ${r}`,"",!1,!0)}}}catch(e){const t=e instanceof Error?e.message:String(e);h.logger.log(`[${this.name}]: execute() failed: ${t}`);const r=`The previous action JSON is malformed: ${t}. Please regenerate a valid action JSON with the correct schema (action, thinking, need sequential(?), properties as a list of {name, value} pairs).`;return new c.ExecutionResponse("",r,!0,!1)}})}}},7201(e,t){"use strict";var r=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.ConsoleConduit=t.QueuedConduit=t.Conduit=void 0;class n{constructor(){this._isSet=!1,this._waiters=[]}isSet(){return this._isSet}set(){this._isSet=!0;for(const e of this._waiters)e();this._waiters=[]}clear(){this._isSet=!1}wait(){return this._isSet?Promise.resolve():new Promise(e=>{this._waiters.push(e)})}}class s{}t.Conduit=s,t.QueuedConduit=class extends s{constructor(){super(...arguments),this._queue=[],this._event=new n,this._subscribers=[],this._running=!1,this._task=null}sendMessage(e,t,r="",n="",s=null){const i={id:e,message:t,format:r,content:n,signal:"",misc:{}};null!=s&&s.appendMessage(Object.assign(Object.assign({},i),{misc:Object.assign({},i.misc)})),this.enqueue(i)}send(e,t=null){null!=t&&t.appendMessage(Object.assign(Object.assign({},e),{misc:Object.assign({},e.misc)})),this.enqueue(e)}sendAsync(e){return r(this,arguments,void 0,function*(e,t=null){null!=t&&t.appendMessage(Object.assign(Object.assign({},e),{misc:Object.assign({},e.misc)})),yield this.enqueueAsync(e)})}sendMessageAsync(e,t){return r(this,arguments,void 0,function*(e,t,r="",n="",s=null){const i={id:e,message:t,format:r,content:n,signal:"",misc:{}};null!=s&&s.appendMessage(Object.assign(Object.assign({},i),{misc:Object.assign({},i.misc)})),yield this.enqueueAsync(i)})}enqueue(e){this._queue.push(e),this._event.set()}enqueueAsync(e){return r(this,void 0,void 0,function*(){this._queue.push(e),this._event.set()})}subscribe(e){this._subscribers.push(e)}start(){this._running||(this._running=!0,this._task=this._processLoop())}stop(){this._running=!1,this._event.set()}_processLoop(){return r(this,void 0,void 0,function*(){for(;this._running;){if(0===this._queue.length){this._event.clear(),yield this._event.wait();continue}const e=this._queue.shift();for(const t of this._subscribers)try{yield t(e)}catch(e){console.log(`QueuedConduit: subscriber error: ${e}`)}}})}},t.ConsoleConduit=class extends s{send(e,t=null){null!=t&&t.appendMessage(Object.assign(Object.assign({},e),{misc:Object.assign({},e.misc)})),e.message&&console.log(e.message)}sendAsync(e){return r(this,arguments,void 0,function*(e,t=null){null!=t&&t.appendMessage(Object.assign(Object.assign({},e),{misc:Object.assign({},e.misc)})),e.message&&console.log(e.message)})}sendMessage(e,t,r="",n="",s=null){const i={id:e,message:t,format:r,content:n,signal:"",misc:{}};null!=s&&s.appendMessage(Object.assign(Object.assign({},i),{misc:Object.assign({},i.misc)})),t&&console.log(t)}sendMessageAsync(e,t){return r(this,arguments,void 0,function*(e,t,r="",n="",s=null){const i={id:e,message:t,format:r,content:n,signal:"",misc:{}};null!=s&&s.appendMessage(Object.assign(Object.assign({},i),{misc:Object.assign({},i.misc)})),t&&console.log(t)})}}},2201(e,t,r){"use strict";var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&s(t,e,r[o]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.LlmConfig=void 0,t.getAppHome=p,t.parsePath=g,t.getSkillConfig=m,t.getFullSkillConfig=function(){const e=p();let t=l.join(e,".skill.config"),r={skill_configs:[]};if(c.existsSync(t)){let e;try{e=JSON.parse(c.readFileSync(t,"utf-8"))}catch(e){u.logger.log("Failed to read skill config")}e&&(r={skill_configs:e.skill_configs||[]})}return r},t.getFullWorkingPath=y;const a=o(r(857)),c=o(r(9896)),l=o(r(6760)),u=r(651),h=r(8404);function d(e){return e.replace(/\/{2,}/g,"/")}function f(e){return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function p(){const e=".axle",t=a.homedir(),r=l.join(t,e),n=process.cwd(),s=l.join(n,e);let i="";return _(s)?i=s:(_(r)||c.mkdirSync(r,{recursive:!0}),i=r),i}function _(e){try{return c.statSync(e).isDirectory()}catch(e){return!1}}function g(e){if(null==e)throw new Error("parsePath: path must not be null or undefined.");const t=e.trim();if(""===t)throw new Error("parsePath: path must not be empty.");if(h.SSH_SCHEME.test(t)){const r=t.replace(h.SSH_SCHEME,""),n=r.indexOf("/");let s,i;if(-1===n?(s=r,i="/"):(s=r.slice(0,n),i=r.slice(n)),s=s.trim(),""===s)throw new Error(`parsePath: remote path '${e}' is missing a server name.`);const o=s;i=d(i.trim()),""===i||"/"===i?i="/":(i.startsWith("/")||(i="/"+i),i=f(i));let a=m("ssh",o);a&&0!==Object.keys(a).length||(a=m("scp",o));const c=a&&Object.keys(a).length>0?a:null;return new h.WorkingDir("remote",i,o,c)}const r=f(d(t));return new h.WorkingDir("local",r,null,null)}function m(e,t){const r=p();let n=l.join(r,".skill.config"),s={};if(c.existsSync(n)){let r;try{r=JSON.parse(c.readFileSync(n,"utf-8"))}catch(e){u.logger.log("Failed to read skill config")}if(r){const n=r.skill_configs||[];for(const r of n)if(r.skill===e){const e=r.config_items||[];for(const r of e)if(r.name===t){s=r.value;break}break}}}return s}function y(e){let t="";return t="remote"===(null==e?void 0:e.kind)?`ssh://${e.serverName}/${e.path}`:`${null==e?void 0:e.path}`,t}t.LlmConfig=class{constructor(){var e;this.config=null,this.configPath=null;const t=p();if(this.configPath=l.join(t,".llm.config"),c.existsSync(this.configPath)){u.logger.log(`Reading LLM configuration from ${t}`);const r=c.readFileSync(this.configPath,"utf-8"),n=JSON.parse(r);if(n&&n.models&&Array.isArray(n.models)||u.logger.log("No model is defined."),this.config=n,null===(e=this.config)||void 0===e?void 0:e.models)for(const e of this.config.models)if(e.workingDir){const t=g(e.workingDir);"local"!==t.kind||_(t.path)?e.workingDir=y(t):e.workingDir=process.cwd()}}}getConfig(){return this.config}getModels(){var e;return null===(e=this.config)||void 0===e?void 0:e.models}getActiveModels(){var e,t;return(null!==(t=null===(e=this.config)||void 0===e?void 0:e.models)&&void 0!==t?t:[]).filter(e=>!1!==e.active)}getModel(e){var t,r;return null===(r=null===(t=this.config)||void 0===t?void 0:t.models)||void 0===r?void 0:r.find(t=>t.name===e)}getConfigPath(){return this.configPath}addModel(e){var t;this.config||(this.config={models:[]});const r=Object.assign(Object.assign({},e),{active:null===(t=e.active)||void 0===t||t}),n=this.config.models.findIndex(e=>e.name===r.name);n>=0?this.config.models[n]=r:this.config.models.push(r),this.save()}updateModel(e,t){var r,n;const s=null===(n=null===(r=this.config)||void 0===r?void 0:r.models)||void 0===n?void 0:n.find(t=>t.name===e);return s?(void 0!==t.url&&(s.url=String(t.url)),void 0!==t.key&&(s.key=String(t.key)),void 0!==t.model&&(s.model=String(t.model)),void 0!==t.skillsFolder&&(s.skillsFolder=String(t.skillsFolder)),void 0!==t.responses&&(s.responses=Boolean(t.responses)),this.save(),s):null}setActive(e,t){var r,n;const s=null===(n=null===(r=this.config)||void 0===r?void 0:r.models)||void 0===n?void 0:n.find(t=>t.name===e);return!!s&&(s.active=t,this.save(),!0)}getWorkingDir(e){var t,r,n;return(null===(n=null===(r=null===(t=this.config)||void 0===t?void 0:t.models)||void 0===r?void 0:r.find(t=>t.name===e))||void 0===n?void 0:n.workingDir)||process.cwd()}setWorkingDir(e,t){var r,n;const s=null===(n=null===(r=this.config)||void 0===r?void 0:r.models)||void 0===n?void 0:n.find(t=>t.name===e);return!!s&&(s.workingDir=t,this.save(),!0)}save(){if(!this.config)return;const e=this.configPath||l.join(p(),".llm.config"),t=JSON.stringify(this.config,null,2);c.writeFileSync(e,t,"utf-8"),this.configPath=e}}},5214(e,t,r){"use strict";var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&s(t,e,r[o]);return i(t,e),t}),a=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.parseActionJson=function(e){let t=!1,r={};if("object"==typeof e&&null!==e)r=e,t=!0;else{if("string"!=typeof e)throw new Error("Unsupported payload type: "+typeof e);{let n=function(e){const t=_.FENCE_RE.exec(e);return t?t[1].trim():e.trim()}(e);if(!n.startsWith("{")){const e=n.indexOf("{"),t=n.lastIndexOf("}");-1!==e&&t>e&&(n=n.substring(e,t+1))}try{r=JSON.parse(n),t=!0}catch(e){throw f.logger.log(`not json: ${e}`),new Error(`Malformed action JSON: ${e instanceof Error?e.message:String(e)}`)}}}return r},t.discoverExecutors=function(){return a(this,arguments,void 0,function*(e=l.join(__dirname,"skills")){const t={};let r=e;const n=process.env.AXLE_SKILLS_DIR;if(n&&""!==n.trim()?r=l.resolve(n.trim()):l.isAbsolute(r)||(r=d.app.isPackaged?l.join(process.resourcesPath,e):l.join(d.app.getAppPath(),"dist",e)),!c.existsSync(r)||!c.statSync(r).isDirectory())return f.logger.log(`The skills directory ${r} is not found`),t;const s=m(r);for(const e of s)try{const r=l.resolve(e),n=(0,u.createRequire)(__filename)(r),s=n.ACTION_NAME;if("string"!=typeof s||""===s.trim())continue;const i=g(n);if("function"!=typeof i)continue;if(t[s]){f.logger.log(`Duplicate ACTION_NAME '${s}' found in ${e}; keeping first registration.`);continue}f.logger.log(`find executor ${e} for ${s}`),t[s]=i}catch(e){console.error(e),f.logger.log(`Error loading executors: ${e}`);continue}return t})},t.getRemoteServers=function(){const e=(0,p.getAppHome)(),t=l.join(e,".skill.config"),r=[],n=new Set;if(!c.existsSync(t))return r;let s;try{s=JSON.parse(c.readFileSync(t,"utf-8"))}catch(e){return f.logger.log("Failed to read skill config for remote servers"),r}if(!s)return r;const i=["ssh","scp"],o=s.skill_configs||[];for(const e of o){if(!i.includes(e.skill))continue;const t=e.config_items||[];for(const s of t){const t=s.name;if(!t||n.has(t))continue;n.add(t);const i=s.value||{};r.push({name:t,skill:e.skill,host:i.host,port:i.port,userName:i.user_name,authType:i.auth_type})}}return r},t.validate=function(e){const t=e.trim();try{const e=new h.JsonParser;e.parse(t);const r=e.getTextType();let n="",s="";if(r==h.TextType.JSON||r==h.TextType.TRAILING_JSON){const r=e.getStartPos(),i=e.getEndPos(),o=t.substring(0,r).trim(),a=t.substring(i).trim();n=t.substring(r,i).trim(),o&&(s+=`${o}\n`),a&&(s+=a)}return[r,n,s.trim()]}catch(e){return[h.TextType.MALFORMATED_JSON,"",""]}},t.resolveSkillConfig=function(e,t,r){let n=null;if(e){const s=e.skill_configs||[];for(const e of s)if(e.skill===t){const t=e.config_items||[];for(const e of t)if(e.name===r){n=e.value;break}break}}return n};const c=o(r(9896)),l=o(r(6928)),u=r(3339),h=r(8515),d=r(4157),f=r(651),p=r(2201),_=r(8404);function g(e){return"function"==typeof e.execute?e.execute:null}function m(e,t=[]){let r;try{r=c.readdirSync(e,{withFileTypes:!0})}catch(e){return t}for(const n of r){const r=l.join(e,n.name);if(n.isDirectory()){if(["node_modules",".git","dist","build","__pycache__"].includes(n.name))continue;m(r,t)}else n.isFile()&&n.name.endsWith(".js")&&t.push(r)}return t}},651(e,t,r){"use strict";var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&s(t,e,r[o]);return i(t,e),t}),a=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.logger=t.AxleLogger=void 0,t.truncateLogContent=function(e){const t=(new TextEncoder).encode(e);if(t.length<=5e4)return e;const r=t.slice(0,5e4);return new TextDecoder("utf-8",{fatal:!1}).decode(r)+"\n\n<content truncated>\n"};const c=o(r(9896)),l=o(r(6928)),u=r(2201),h=r(7201),d=r(7576);class f{constructor(e){this.conduit=new h.QueuedConduit;const t=l.join(e,"logs");let r="axle.log";c.existsSync(t)||c.mkdirSync(t,{recursive:!0});const n=new Date;r=`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}-${r}`;const s=l.join(t,r);c.existsSync(s)||c.writeFileSync(s,""),this.logFilePath=s,this.conduit.subscribe(e=>a(this,void 0,void 0,function*(){var t;const r="string"==typeof e?e:String(null!==(t=null==e?void 0:e.message)&&void 0!==t?t:"");r&&(yield c.promises.appendFile(this.logFilePath,r,"utf8"))})),this.conduit.start(),this.log(`Logging in ${t}`)}log(e){const t=`${this.formatTimestamp(new Date)}: ${e}\n`;this.conduit.sendMessage((0,d.generateMessageId)(),t)}formatTimestamp(e){const t=e=>String(e).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}}t.AxleLogger=f,t.logger=new f((0,u.getAppHome)())},6418(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Model=t.MAX_ATTACHMENTS=void 0,t.toDataUrl=a,t.limitAttachments=c,t.buildUserContent=l,t.buildResponsesInput=u,t.buildResponsesHistoryInput=d,t.stripDataUrl=f;const i=s(r(7032)),o=r(651);function a(e){return`data:image/${e.format||"png"};base64,${e.content}`}function c(e){return e&&0!==e.length?e.filter(e=>e&&e.content).slice(0,t.MAX_ATTACHMENTS):[]}function l(e,t){const r=c(t);return 0===r.length?e:[{type:"text",text:e},...r.map(e=>({type:"image_url",image_url:{url:a(e)}}))]}function u(e,t){const r=c(t);return 0===r.length?e:[{role:"user",content:[{type:"input_text",text:e},...r.map(e=>({type:"input_image",image_url:a(e)}))]}]}function h(e){var t;if("string"==typeof e)return e.length>0?[{type:"input_text",text:e}]:[];const r=[];for(const n of e)"image_url"===(null==n?void 0:n.type)&&(null===(t=n.image_url)||void 0===t?void 0:t.url)?r.push({type:"input_image",image_url:n.image_url.url}):"string"==typeof(null==n?void 0:n.text)&&n.text.length>0&&r.push({type:"input_text",text:n.text});return r}function d(e,t,r){const n=[];for(const t of e){const e=h(t.content);0!==e.length&&n.push({role:"assistant"===t.role?"assistant":"user",content:e})}const s=c(r);return 0===s.length?n.push({role:"user",content:[{type:"input_text",text:t}]}):n.push({role:"user",content:[{type:"input_text",text:t},...s.map(e=>({type:"input_image",image_url:a(e)}))]}),n}function f(e){if(!e)return e;const t=e.indexOf(";base64,");return e.startsWith("data:")&&t>=0?e.slice(t+8):e}t.MAX_ATTACHMENTS=5,t.Model=class{recordResponse(e,t,r){e&&t&&(this.dropEntriesAfter(r),this.respIdByMessageId.set(e,t))}dropEntriesAfter(e){let t=null===e;for(const[r,n]of Array.from(this.respIdByMessageId))t?this.respIdByMessageId.delete(r):n===e&&(t=!0)}responseIdBefore(e){let t=null;for(const[r,n]of this.respIdByMessageId){if(r===e)return t;t=n}return null}constructor(e,t="https://api.openai.com/v1",r="gpt-3.5-turbo",n,s=.7,a=131072,c=!1){this.previousRespId=null,this.conversationHistory=[],this.respIdByMessageId=new Map,this.apiKey=e,this.baseUrl=t.replace(/\/+$/,""),this.modelName=r,this.maxTokens=a,this.responses=c,this.previousRespId=null,this.prompt=n,o.logger.log(`Using ${this.responses?"responses":"completions"} API`),this.responsesClient=new i.default({baseURL:this.baseUrl,apiKey:this.apiKey})}get systemPrompt(){return this.prompt.getSystemPrompt()}chat(e){return n(this,void 0,void 0,function*(){const t=e.userinput,r=e.attachments,n=e.prevRespId,s=e.messageId;n&&(o.logger.log("User sets previous response id: "+n),this.previousRespId=n);let i=1;for(;;){i>1&&o.logger.log("Retrying...");try{if(this.responses)return yield this._callLlmResponsesApi(t,r,s);{const e=[{role:"system",content:this.systemPrompt}];for(const t of this.conversationHistory)e.push({role:t.role,content:t.content});e.push({role:"user",content:l(t,r)});const n=yield this._callLlmCompletionApi(e);return this.recordTurn(t,r,n.text,s),n}}catch(e){if(o.logger.log(`Communication error: ${String(e)}`),i++,i>3){const n=`Error communicating with LLM: ${String(e)}`,i={text:n,binary:null,respId:null};return this.responses||this.recordTurn(t,r,n,s),i}}}})}_callLlmCompletionApi(e){return n(this,void 0,void 0,function*(){var t;const r=yield null===(t=this.responsesClient)||void 0===t?void 0:t.chat.completions.create({model:this.modelName,messages:e});if((null==r?void 0:r.choices)&&(null==r?void 0:r.choices.length)>0){const e=null==r?void 0:r.choices[0];if(e.message&&e.message.content)return{text:e.message.content,binary:null,respId:null}}throw new Error(`Unexpected API response format: ${JSON.stringify(r)}`)})}_callLlmResponsesApi(e,t,r){return n(this,void 0,void 0,function*(){const n=this.conversationHistory.length>0;n&&o.logger.log(`loading conversation history, size: ${this.conversationHistory.length}`);const s={model:this.modelName,instructions:this.systemPrompt,input:n?d(this.conversationHistory,e,t):u(e,t),tools:[{type:"call",action:"action_name, please generate the action STRICTLY following the name inthe skills",thinking:"the think trace of LLM",sequential:{prompt:"prompt used as input for all of following tasks, NOT JUST next task, so that all of the following tasks are not missed."},properties:[{name:"property1",value:"value1"},{name:"property2",value:"value2"}]}]};this.previousRespId?(o.logger.log(`Previous response id: ${this.previousRespId}`),s.previous_response_id=this.previousRespId):o.logger.log("Previous response id is empty");const i=yield this.responsesClient.responses.create(s);n&&(this.conversationHistory=[],o.logger.log("Responses API: seeded conversation history sent and cleared"));const a=this.previousRespId;return this.previousRespId=i.id,o.logger.log(`Response id: ${this.previousRespId}`),this.recordResponse(r,i.id,a),{text:this.extractResponsesText(i),binary:this.extractResponsesImage(i),respId:this.previousRespId}})}extractResponsesText(e){var t,r;if(e&&"string"==typeof e.output_text&&e.output_text.length>0)return e.output_text;let n="";for(const s of null!==(t=null==e?void 0:e.output)&&void 0!==t?t:[]){const e=null!==(r=null==s?void 0:s.content)&&void 0!==r?r:[];for(const t of e)"string"==typeof(null==t?void 0:t.text)?n+=t.text:"string"==typeof(null==t?void 0:t.output_text)&&(n+=t.output_text)}return n}extractResponsesImage(e){var t,r,n;for(const s of null!==(t=null==e?void 0:e.output)&&void 0!==t?t:[]){if("image_generation_call"===(null==s?void 0:s.type)&&"string"==typeof s.result)return f(s.result);for(const e of null!==(r=null==s?void 0:s.content)&&void 0!==r?r:[]){const t="string"==typeof(null==e?void 0:e.type)?e.type:"";if("string"==typeof(null==e?void 0:e.b64))return f(e.b64);if("string"==typeof(null==e?void 0:e.data)&&t.includes("image"))return f(e.data);if("string"==typeof(null==e?void 0:e.result)&&t.includes("image"))return f(e.result);if("string"==typeof(null===(n=null==e?void 0:e.image_url)||void 0===n?void 0:n.url))return f(e.image_url.url);if(t.includes("image")&&"string"==typeof(null==e?void 0:e.image_url))return f(e.image_url)}}return null}recordTurn(e,t,r,n){this.conversationHistory.push({role:"user",content:l(e,t),id:n}),this.conversationHistory.push({role:"assistant",content:r,id:n})}getRespIdForMessage(e){var t;return e&&null!==(t=this.respIdByMessageId.get(e))&&void 0!==t?t:null}deleteMessage(e){return n(this,void 0,void 0,function*(){var t,r;if(!e)return!1;if(!this.responses){const t=this.conversationHistory.length;this.conversationHistory=this.conversationHistory.filter(t=>t.id!==e);const r=t-this.conversationHistory.length;return o.logger.log(`Deleted ${r} conversation entr${1===r?"y":"ies"} of message ${e}`),r>0}const n=null!==(t=this.respIdByMessageId.get(e))&&void 0!==t?t:null;if(!n)return o.logger.log(`No response id is recorded for message ${e}; nothing to delete`),!1;const s=this.previousRespId===n,i=s?this.responseIdBefore(e):null;try{yield this.responsesClient.responses.delete(n),o.logger.log(`Deleted response ${n} of message ${e}`)}catch(e){return o.logger.log(`Failed to delete response ${n}: ${String(e)}`),!1}return this.respIdByMessageId.delete(e),s&&(this.previousRespId=i,o.logger.log(`Previous response id is now ${null!==(r=this.previousRespId)&&void 0!==r?r:"empty"}`)),!0})}clear(){o.logger.log(`Clearing messages of ${this.modelName}`),this.previousRespId=null,this.respIdByMessageId.clear(),this.conversationHistory=[]}}},8515(e,t){"use strict";var r;t.JsonParser=t.TextType=void 0,function(e){e[e.JSON=1]="JSON",e[e.TRAILING_JSON=2]="TRAILING_JSON",e[e.TRUNCATED_JSON=3]="TRUNCATED_JSON",e[e.MALFORMATED_JSON=4]="MALFORMATED_JSON",e[e.TEXT=5]="TEXT"}(r||(t.TextType=r={}));class n extends Error{constructor(e,t=0){super(`InvalidFormatError: ${r[e]}`),this.errorType=e,this.errorPos=t}getErrorType(){return this.errorType}getErrorPos(){return this.errorPos}}const s=new Set(["0","1","2","3","4","5","6","7","8","9"]),i=",";t.JsonParser=class{constructor(){this.pos=0,this.len=0,this.json="",this.startPos=0,this.textType=r.JSON}getStartPos(){return this.startPos}getEndPos(){return this.pos}getTextType(){return this.textType}parse(e){if(this.json=e,this.len=e.length,this.len<1)this.textType=r.MALFORMATED_JSON;else if(this._walkToJsonStart(),this.pos>=this.len)this.textType=r.TEXT;else try{this._parse(),this._walkThroughEmpty(),this.pos<this.len&&(this.textType=r.TRAILING_JSON)}catch(e){e instanceof n||(this.textType=r.MALFORMATED_JSON)}}_parse(){if(this._walkThroughEmpty(),this.pos>=this.len)throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON);const e=this.json.charAt(this.pos);if(s.has(e)||"-"===e)return this._parseNumber();if('"'===e||"'"===e)return this._parseString(e);if("{"===e)return this._parseObject();if("["===e)return this._parseArray();if("t"===e)return this._parseTrue();if("f"===e)return this._parseFalse();if("n"===e)return this._parseNull();throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON)}_walkToJsonStart(){this._walkThroughEmpty(),this.pos>=this.len&&(this.textType=r.MALFORMATED_JSON);let e=this.json.charAt(this.pos),t=!1;for(;this.pos<this.len&&("{"!==e&&"["!==e||t);){if(t&&"`"!==e){if(this._movePositionNonJson()){e=this.json.charAt(this.pos);continue}break}if("`"==e){let r=0;for(;"`"===e&&this._movePositionNonJson();)e=this.json.charAt(this.pos),r++;r>2&&(t=!t)}else{if(!this._movePositionNonJson())break;e=this.json.charAt(this.pos)}}this.pos<this.len&&("{"===e||"["===e)&&(this.startPos=this.pos)}_parseNumber(){let e=!1;const t=this.pos;let s=this.json.charAt(this.pos);if("-"===s){if(this._movePosition(),!this._isDigit(this.json.charAt(this.pos))||"0"===this.json.charAt(this.pos))throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON)}else if("0"===s&&this.pos<this.len-1&&(this.pos+=1,this._isDigit(this.json.charAt(this.pos))))throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON);for(;this.pos<this.len&&this._isDigit(this.json.charAt(this.pos));)this.pos+=1;if(this.pos<this.len&&"."===this.json.charAt(this.pos)&&(e=!0,this._movePosition(),!this._isDigit(this.json.charAt(this.pos))))throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON);for(;this.pos<this.len&&this._isDigit(this.json.charAt(this.pos));)this.pos+=1;if(this.pos<this.len&&"e"===this.json.charAt(this.pos).toLowerCase()){e=!0,this._movePosition();const t=this.json.charAt(this.pos);if(this._isDigit(t))for(;this.pos<this.len&&this._isDigit(this.json.charAt(this.pos));)this.pos+=1;else{if("+"!==t&&"-"!==t)throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON);if(this._movePosition(),!this._isDigit(this.json.charAt(this.pos)))throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON);for(;this.pos<this.len&&this._isDigit(this.json.charAt(this.pos));)this.pos+=1}}const i=this.json.substring(t,this.pos);return e?parseFloat(i):parseInt(i,10)}_parseString(e){this.pos+=1;const t=this.pos;let s=!1;for(;this.pos<this.len&&(this.json.charAt(this.pos)!==e||s);)"\\"===this.json.charAt(this.pos)?s=!s:s&&(s=!1),this.pos+=1;if(this.pos<=t&&this.pos>=this.len||this.pos>=this.len&&this.json.charAt(this.pos-1)!==e)throw this.textType=r.TRUNCATED_JSON,new n(r.TRUNCATED_JSON);const i=this.json.substring(t,this.pos);return this.pos+=1,i}_parseObject(){if(this.pos+=1,this._walkThroughEmpty(),this.pos>=this.len)throw this.textType=r.TRUNCATED_JSON,new n(r.TRUNCATED_JSON);const e={};for(;this.pos<this.len&&"}"!==this.json.charAt(this.pos);){if(this._walkThroughEmpty(),this.pos>=this.len)throw this.textType=r.TRUNCATED_JSON,new n(r.TRUNCATED_JSON);if('"'!==this.json.charAt(this.pos)&&"'"!==this.json.charAt(this.pos))throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON);const t=this._parse();if(this._walkThroughEmpty(),this.pos>=this.len)throw this.textType=r.TRUNCATED_JSON,new n(r.TRUNCATED_JSON);if(":"!==this.json.charAt(this.pos))throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON);this._movePosition();const s=this._parse();if(this._walkThroughEmpty(),this.pos>=this.len)throw this.textType=r.TRUNCATED_JSON,new n(r.TRUNCATED_JSON);if(this.json.charAt(this.pos)!==i&&"}"!==this.json.charAt(this.pos))throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON);e[t]=s,this.json.charAt(this.pos)===i&&this._movePosition()}if(this.pos>=this.len&&"}"!==this.json.charAt(this.pos-1))throw this.textType=r.TRUNCATED_JSON,new n(r.TRUNCATED_JSON);return this.pos+=1,e}_parseArray(){if(this.pos+=1,this._walkThroughEmpty(),this.pos>=this.len)throw this.textType=r.TRUNCATED_JSON,new n(r.TRUNCATED_JSON);const e=[];for(;this.pos<this.len&&"]"!==this.json.charAt(this.pos);){const t=this._parse();if(this._walkThroughEmpty(),this.pos>=this.len)throw this.textType=r.TRUNCATED_JSON,new n(r.TRUNCATED_JSON);if(this.json.charAt(this.pos)!==i&&"]"!==this.json.charAt(this.pos))throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON);e.push(t),this.json.charAt(this.pos)===i&&this._movePosition(),this._walkThroughEmpty()}if(this.pos>=this.len&&"]"!==this.json.charAt(this.pos-1))throw this.textType=r.TRUNCATED_JSON,new n(r.TRUNCATED_JSON);return this.pos+=1,e}_parseTrue(){if(this._movePosition(),"r"===this.json.charAt(this.pos)){if(this._movePosition(),"u"===this.json.charAt(this.pos)){if(this._movePosition(),"e"===this.json.charAt(this.pos))return this.pos+=1,!0;throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON)}throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON)}throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON)}_parseFalse(){if(this._movePosition(),"a"===this.json.charAt(this.pos)){if(this._movePosition(),"l"===this.json.charAt(this.pos)){if(this._movePosition(),"s"===this.json.charAt(this.pos)){if(this._movePosition(),"e"===this.json.charAt(this.pos))return this.pos+=1,!1;throw new n(r.MALFORMATED_JSON)}throw new n(r.MALFORMATED_JSON)}throw new n(r.MALFORMATED_JSON)}throw new n(r.MALFORMATED_JSON)}_parseNull(){if(this._movePosition(),"u"===this.json.charAt(this.pos)){if(this._movePosition(),"l"===this.json.charAt(this.pos)){if(this._movePosition(),"l"===this.json.charAt(this.pos))return this.pos+=1,null;throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON)}throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON)}throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON)}_walkThroughEmpty(){for(;this.pos<this.len&&/\s/.test(this.json.charAt(this.pos));)this.pos+=1}_isDigit(e){return s.has(e)}_movePosition(){if(this.pos+=1,this.pos>=this.len)throw this.textType=r.MALFORMATED_JSON,new n(r.MALFORMATED_JSON);return this.json.charAt(this.pos)}_movePositionNonJson(){return this.pos+=1,this.pos<this.len}}},9237(e,t,r){"use strict";var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&s(t,e,r[o]);return i(t,e),t}),a=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.AxlePrompt=void 0;const c=o(r(9896)),l=o(r(6928)),u=o(r(857)),h=r(4157),d=r(651),f=r(8404),p=r(8404),_=r(7373);t.AxlePrompt=class{constructor(e="skills"){if(this.skillsContent={},this.selectedSkills=[],this.osPrompt=null,this._cachedSystemPrompt=null,this.local={projectPrompts:[]},this.skillsFolder=e,!l.isAbsolute(this.skillsFolder))if(h.app.isPackaged)this.skillsFolder=l.join(process.resourcesPath,this.skillsFolder);else{const e=l.join(h.app.getAppPath(),"src",this.skillsFolder);this.skillsFolder=e}this.skillsContent={},this._loadSkills(),this.osPrompt=`${u.type()} ${u.release()}`}_loadSkills(){if(this.skillsContent={},!c.existsSync(this.skillsFolder)||!c.statSync(this.skillsFolder).isDirectory())return d.logger.log(`Skills folder '${this.skillsFolder}' not found.`),void this._invalidateCache();const e=c.readdirSync(this.skillsFolder).sort();for(const t of e){const e=l.join(this.skillsFolder,t);if(!c.statSync(e).isDirectory())continue;if(t.startsWith("__")||t.startsWith("."))continue;const r=this._readSkillContent(t);null!==r&&(this.skillsContent[t]=r,this.selectedSkills.push(t))}this._invalidateCache(),d.logger.log(`Loaded ${Object.keys(this.skillsContent).length} skill(s) from '${this.skillsFolder}/'`)}_readSkillContent(e){const t=l.join(this.skillsFolder,e),r=l.join(t,"SKILL.md");if(c.existsSync(r)&&c.statSync(r).isFile())try{return c.readFileSync(r,"utf8")}catch(t){d.logger.log(`Error loading skill '${e}': ${t}`)}return null}buildOsPrompt(e){return a(this,void 0,void 0,function*(){e&&"local"!==e.kind?this.osPrompt=yield this._detectRemoteOsPrompt(e):this.osPrompt=`${u.type()} ${u.release()}`,d.logger.log(`Current OS: ${this.osPrompt}`),this.buildDirPrompt(e),this._invalidateCache()})}_toSshTarget(e,t){return{host:t.host||e,port:t.port?parseInt(t.port,10):22,user:t.user_name||t.userName||t.user||"",authType:(t.auth_type||t.authType||"password").toLowerCase(),keyFile:t.key_file||t.keyFile||"",password:t.pass||""}}_detectRemoteOsPrompt(e){return a(this,void 0,void 0,function*(){var t;const r=null!==(t=e.serverName)&&void 0!==t?t:"",n=e.server;if(!n)return d.logger.log(`No SSH server configuration found for '${r}'.`),`remote server '${r}' (OS unknown)`;try{const e=this._toSshTarget(r,n),t=yield(0,_.getSshConn)((0,_.buildSshCacheKey)(e),(0,_.buildSshConnectConfig)(e));let s="";const i=yield(0,f.execCommand)(t,"grep '^PRETTY_NAME=' /etc/os-release 2>/dev/null || true");if(0===i.code){const e=i.stdout.trim(),t=e.indexOf("=");if(-1!==t){let r=e.substring(t+1).trim();r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),s=r}}if(!s){const e=yield(0,f.execCommand)(t,"head -n1 /etc/issue 2>/dev/null || true");0===e.code&&(s=e.stdout.trim())}const o=yield(0,f.execCommand)(t,"uname -s"),a=yield(0,f.execCommand)(t,"uname -r"),c=`${0===o.code?o.stdout.trim():""} ${0===a.code?a.stdout.trim():""}`.trim();return s&&c?`${s} (${c})`:s||c||`remote server '${r}' (OS unknown)`}catch(e){return d.logger.log(`Failed to detect OS on remote server '${r}': ${e}`),""}})}get projectPrompts(){return this.local.projectPrompts}buildDirPrompt(e){return a(this,void 0,void 0,function*(){this.local.projectPrompts=[];try{if(e&&"local"!==e.kind)this.local.projectPrompts=yield this._readRemoteProjectPrompts(e);else{const t=e&&e.path?e.path:process.cwd();this.local.projectPrompts=this._readLocalProjectPrompts(l.join(t,".axle","skills"))}}catch(e){d.logger.log(`Error loading project prompts: ${e}`),this.local.projectPrompts=[]}d.logger.log(`Loaded ${this.local.projectPrompts.length} project prompt(s).`)})}_readLocalProjectPrompts(e){const t=[];if(!c.existsSync(e)||!c.statSync(e).isDirectory())return d.logger.log(`Project prompt folder '${e}' not found.`),t;const r=c.readdirSync(e).sort();for(const n of r){if(".md"!==l.extname(n).toLowerCase())continue;const r=l.join(e,n);if(c.statSync(r).isFile())try{t.push({name:n,content:c.readFileSync(r,"utf8")})}catch(e){d.logger.log(`Error reading project prompt '${r}': ${e}`)}}return t}_readRemoteProjectPrompts(e){return a(this,void 0,void 0,function*(){var t;const r=[],n=null!==(t=e.serverName)&&void 0!==t?t:"",s=e.server;if(!s)return d.logger.log(`No SSH server configuration found for '${n}'.`),r;const i=`${(e.path||".").replace(/\/+$/,"")}/.axle/skills`,o="<<<AXLE_PROJECT_PROMPT>>>";try{const e=this._toSshTarget(n,s),t=yield(0,_.getSshConn)((0,_.buildSshCacheKey)(e),(0,_.buildSshConnectConfig)(e)),a=(0,p.shellQuote)(i),c=`if [ -d ${a} ]; then for f in ${a}/*.md; do [ -f "$f" ] || continue; echo "${o}$(basename "$f")"; cat "$f"; echo ""; done; fi`,l=yield(0,f.execCommand)(t,c);if(0!==l.code)return d.logger.log(`Failed to list remote project prompts in '${i}' (exit code ${l.code}).`),r;const u=l.stdout.split(o);for(let e=1;e<u.length;e++){const t=u[e],n=t.indexOf("\n");if(-1===n)continue;const s=t.substring(0,n).trim();let i=t.substring(n+1);i.endsWith("\n")&&(i=i.slice(0,-1)),s&&r.push({name:s,content:i})}}catch(e){return d.logger.log(`Failed to read project prompts on remote server '${n}': ${e}`),r}return r})}loadSkills(e){if(e&&0!==e.length){this.selectedSkills=[];for(const t of e)this.skillsContent[t]&&this.selectedSkills.push(t);this._invalidateCache(),d.logger.log(`Loaded ${e.length} requested skill(s); total ${Object.keys(this.skillsContent).length} skill(s).`)}}_invalidateCache(){this._cachedSystemPrompt=null}getSystemPrompt(){return null===this._cachedSystemPrompt&&(this._cachedSystemPrompt=this._buildSystemPrompt()),this._cachedSystemPrompt}_buildSystemPrompt(){d.logger.log("Creating system prompt...");const e=[];if(e.push("You are an intelligent AI assistant equipped with specialized skills, and always generate formatted output in JSON. You should use these skills when appropriate to help the user effectively.\n\n## Your Capabilities\n\nBelow are the skills available to you. Each skill has a description and guidelines for when and how to use it.\n"),d.logger.log(`OS: ${this.osPrompt}`),this.osPrompt&&e.push(`The current operating system is ${this.osPrompt}. You should provide operating system specific commands and analysis for operating system related tasks.\n`),this.selectedSkills.length>0)for(const t of this.selectedSkills){const r=this.skillsContent[t];e.push(`\n---\n### Skill: \`${t}\`\n\n${r}\n`)}else e.push("\n(No skills are currently loaded. Respond using your general knowledge.)\n");e.push("\n---\n## General Guidelines\n\n- Use skills when the user's request matches a skill's trigger conditions.\n- If no skill is relevant, respond using your general knowledge.\n- Be concise, accurate, and helpful.\n- When executing skill-related tasks, follow the skill's documented patterns.\n");const t=l.join(this.skillsFolder,"SYSTEM.md");if(c.existsSync(t)&&c.statSync(t).isFile())try{const r=c.readFileSync(t,"utf8");e.push(`\n---\n${r}\n`),d.logger.log(`Loaded system instructions from '${t}'`)}catch(e){d.logger.log(`Error loading SYSTEM.md: ${e}`)}if(this.local.projectPrompts.length>0){e.push("\n---\n## Project Prompts\n");for(const t of this.local.projectPrompts)e.push(`\n### ${t.name}\n\n${t.content}\n`);d.logger.log(`Appended ${this.local.projectPrompts.length} project prompt(s) to the system prompt.`)}return e.join("")}reloadSkills(){d.logger.log("\nReloading skills..."),this.selectedSkills=[],this._loadSkills(),d.logger.log("Skills reloaded successfully.")}getSkillsSummary(){const e=this.selectedSkills,t=this.local.projectPrompts;if(0===e.length&&0===t.length)return"No skills loaded.";const r=[];if(e.length>0){r.push("Loaded Skills:"),r.push("-".repeat(40));let t=1;for(const n of e)r.push(` ${t}. ${n}`),t++;r.push("-".repeat(40)),r.push(`Total: ${e.length} skill(s)`)}else r.push("No skills loaded.");if(t.length>0){r.length>0&&r.push(""),r.push("Loaded Project Prompts:"),r.push("-".repeat(40));let e=1;for(const n of t)r.push(` ${e}. ${n.name}`),e++;r.push("-".repeat(40)),r.push(`Total: ${t.length} project prompt(s)`)}return r.join("\n")}}},7373(e,t,r){"use strict";var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&s(t,e,r[o]);return i(t,e),t}),a=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.SSH_IDLE_TIMEOUT_MS=void 0,t.buildSshCacheKey=u,t.isSshConnAlive=h,t.evictSshConn=d,t.sweepSshConns=f,t.closeAllSshConns=function(){for(const e of Array.from(l.keys()))d(e)},t.buildSshConnectConfig=p,t.getSshConn=_,t.isSshConnLostError=g,t.sshExec=function e(t,r){return a(this,arguments,void 0,function*(t,r,n=!1){const s=u(t),i=p(t),o=yield _(s,i);try{const e=yield new Promise((e,t)=>{o.exec(r,(r,n)=>{if(r)return void t(r);let s="",i="",o=!1;const a=e=>{o||(o=!0,e())};n.on("close",r=>{a(()=>{!r||0===r||s?e(s):t(new Error(i||`Remote command exited with code ${r}`))})}),n.on("data",e=>{s+=e.toString()}),n.on("error",e=>{a(()=>t(e))}),n.stderr.on("data",e=>{i+=e.toString()})})}),t=l.get(s);return t&&(t.lastUsed=Date.now()),e}catch(i){if(!n&&g(i))return d(s),e(t,r,!0);throw i}})};const c=o(r(9896)),l=new Map;function u(e){var t,r,n,s;const i=null!==(t=e.port)&&void 0!==t?t:"22",o=null!==(r=e.user)&&void 0!==r?r:"",a=null!==(n=e.authType)&&void 0!==n?n:"password",c=null!==(s=e.keyFile)&&void 0!==s?s:"";return`${e.host}|${i}|${o}|${a}|${c}`}function h(e){try{if(!e)return!1;const t=e._sock;return!(!t||t.destroyed)&&!1!==t.readable&&!1!==t.writable}catch(e){return!1}}function d(e){const t=l.get(e);if(t){l.delete(e),t.dead=!0;try{t.client.end()}catch(e){}try{"function"==typeof t.client.destroy&&t.client.destroy()}catch(e){}}}function f(){const e=Date.now();for(const[r,n]of Array.from(l.entries()))(n.dead||!h(n.client)||e-n.lastUsed>t.SSH_IDLE_TIMEOUT_MS)&&d(r)}function p(e){var t,r,n,s,i;const o={host:e.host,port:Number(null!==(t=e.port)&&void 0!==t?t:22)||22,username:null!==(r=e.user)&&void 0!==r?r:"",readyTimeout:2e4,keepaliveInterval:15e3,keepaliveCountMax:3},a=null!==(n=e.authType)&&void 0!==n?n:"password",l=null!==(s=e.keyFile)&&void 0!==s?s:"",u=null!==(i=e.password)&&void 0!==i?i:"";return"key"===a&&l?(o.privateKey=c.readFileSync(l),u&&(o.passphrase=u)):o.password=u,o}function _(e,t){return a(this,void 0,void 0,function*(){f();const n=l.get(e);if(n)if(!n.dead&&h(n.client))try{return yield n.ready,n.lastUsed=Date.now(),n.client}catch(t){d(e)}else d(e);const{Client:s}=r(3365),i=new s,o={client:i,dead:!1,lastUsed:Date.now(),ready:Promise.resolve(i)},a=()=>{o.dead=!0,l.get(e)===o&&l.delete(e)};i.on("close",a),i.on("end",a),i.on("error",a),o.ready=new Promise((e,r)=>{let n=!1;i.once("ready",()=>{n=!0,e(i)}),i.once("error",e=>{n||(n=!0,r(e))}),i.once("close",()=>{n||(n=!0,r(new Error("SSH connection closed before becoming ready")))}),i.connect(t)}),l.set(e,o);try{yield o.ready}catch(t){throw d(e),t}return o.lastUsed=Date.now(),i})}function g(e){var t;const r=String(null!==(t=null==e?void 0:e.code)&&void 0!==t?t:"").toUpperCase();if(["ECONNRESET","ETIMEDOUT","EPIPE","ECONNABORTED","EHOSTUNREACH","ENETUNREACH"].includes(r))return!0;const n=String(e instanceof Error?e.message:null!=e?e:"").toLowerCase();return/client is not connected|not connected|channel closed|connection lost|connection closed|socket hang up|remote end closed|no response from server|timed out while waiting|ssh connection closed/.test(n)}t.SSH_IDLE_TIMEOUT_MS=3e5},4859(e,t,r){"use strict";var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&s(t,e,r[o]);return i(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.AxleSession=void 0;const a=o(r(9896)),c=o(r(6760)),l=o(r(8522)),u=r(7576),h=r(2201),d=r(651),f="b64:";class p{constructor(e,t){this.model=e,this.session=null!=t?t:p.createSession()}get modelName(){return this.model}get sessionId(){return this.session.sessionId}get conversations(){return this.session.conversations}newConversation(){const e={cvsId:p.generateId("cvs"),turns:[]};return this.session.conversations.push(e),d.logger.log(`[${this.model}]: [session] ${this.sessionId}: new conversation ${e.cvsId}`),e}appendConversation(e){return this.session.conversations.push(e),d.logger.log(`[${this.model}]: [session] ${this.sessionId}: appended conversation ${e.cvsId} (${e.turns.length} turn(s))`),e}appendRequest(e,t,r,n){var s;const i=null!==(s=this.latestConversation())&&void 0!==s?s:this.newConversation(),o={msgId:e,request:{content:t,attachments:null!=r?r:null,from:n},response:{respId:null,content:"",binary:null},messages:[]};return i.turns.push(o),d.logger.log(`[${this.model}]: [session] ${this.sessionId}: append request ${e} to ${i.cvsId} (${t.length} chars)`),o}appendResponse(e,t,r,n){this.requireTurn(e).response={respId:t,content:r,binary:n},d.logger.log(`[${this.model}]: [session] ${this.sessionId}: append response ${e} (respId=${null!=t?t:"none"}, ${r.length} chars${n?", with binary":""})`)}appendMessage(e){e.id&&(this.requireTurn(e.id).messages.push(e),d.logger.log(`[${this.model}]: [session] ${this.sessionId}: append message ${e.id} (format=${e.format||"none"})`))}deleteTurn(e){for(const t of this.session.conversations){const r=t.turns.findIndex(t=>t.msgId===e);if(-1!==r)return t.turns.splice(r,1),d.logger.log(`[${this.model}]: [session] ${this.sessionId}: deleted turn ${e} from ${t.cvsId}`),!0}return d.logger.log(`[${this.model}]: [session] ${this.sessionId}: no turn to delete for ${e}`),!1}serialize(){return JSON.stringify(this.session)}flush(){const e=this.firstTurn();if(void 0===e)return void d.logger.log(`[${this.model}]: [session] ${this.sessionId}: flush skipped, the session has no turn`);const t=c.join((0,h.getAppHome)(),".storage");a.existsSync(t)||a.mkdirSync(t,{recursive:!0});const r=Buffer.from(this.model,"utf-8").toString("base64url"),n=c.join(t,`${r}.csv`),s=e.request.content.slice(0,100),i=p.encodeDescription(s),o=p.zip(`${this.sessionId}.json`,this.serialize()).toString("base64"),l=`${[this.sessionId,this.session.timestamp,i,o].map(p.csvField).join(",")}\n`;this.writeRow(n,l),d.logger.log(`[${this.model}]: [session] ${this.sessionId}: flushed to ${n} (description='${s}', ${l.length} chars)`),this.session=p.createSession()}static encodeDescription(e){return`${f}${Buffer.from(e,"utf-8").toString("base64")}`}static decodeDescription(e){if(!e.startsWith(f))return e;const t=e.slice(4);return Buffer.from(t,"base64").toString("utf-8")}writeRow(e,t){this.rollIfNeeded(e),a.existsSync(e)?a.appendFileSync(e,t,"utf-8"):a.writeFileSync(e,`sessionid,timestamp,description,content\n${t}`,"utf-8")}rollIfNeeded(e){if(!a.existsSync(e))return;if(a.statSync(e).size<1048576)return;const t=c.dirname(e),r=c.basename(e),n=this.archiveNumberBelow(t,r,Number.POSITIVE_INFINITY)+1,s=c.join(t,`${r}.${String(n).padStart(7,"0")}`);a.renameSync(e,s),d.logger.log(`[${this.model}]: [session] store ${e} reached 1048576 bytes, archived as ${s}`)}read(e,t){if(e===this.sessionId)return d.logger.log(`[${this.model}]: [session] ${this.model}: read ${e} served from the active session`),this.session;const r=c.join((0,h.getAppHome)(),".storage"),n=`${Buffer.from(this.model,"utf-8").toString("base64url")}.csv`,s=t?c.basename(t):n;if(!s.startsWith(n))return void d.logger.log(`[${this.model}]: [session] ${this.model}: read ${e} skipped, ${s} is not a store of this model`);const i=c.join(r,s);if(!a.existsSync(i))return void d.logger.log(`[${this.model}]: [session] ${this.model}: read ${e} skipped, no store at ${i}`);const o=p.parseCsv(a.readFileSync(i,"utf-8"));let l;for(let t=o.length-1;t>=0;t--){const r=o[t];if(r.length>=4&&r[0]===e){l=r[3];break}}if(void 0===l)return void d.logger.log(`[${this.model}]: [session] ${this.model}: read ${e} skipped, no record with that id in ${i}`);const u=p.unzip(Buffer.from(l,"base64")),f=JSON.parse(u);if(!p.isSession(f))throw new Error("Invalid session JSON: does not match the session scheme.");return d.logger.log(`[${this.model}]: [session] read ${e} from ${i} (${f.conversations.length} conversation(s))`),f}load(e){const t=Buffer.from(this.model,"utf-8").toString("base64url"),r=c.join((0,h.getAppHome)(),".storage",`${t}.csv`);if(!a.existsSync(r))return d.logger.log(`[${this.model}]: [session] load ${e} skipped, no store at ${r}`),!1;const n=p.parseCsv(a.readFileSync(r,"utf-8"));let s;for(let t=n.length-1;t>=0;t--){const r=n[t];if(r.length>=4&&r[0]===e){s=r[3];break}}if(void 0===s)return d.logger.log(`[${this.model}]: [session] load ${e} skipped, no record with that id in ${r}`),!1;const i=p.unzip(Buffer.from(s,"base64")),o=JSON.parse(i);if(!p.isSession(o))throw new Error("Invalid session JSON: does not match the session scheme.");d.logger.log(`[${this.model}]: [session] flushing the current session ${this.sessionId} before loading ${e}`),this.flush();const l=o.conversations.reduce((e,t)=>e+t.turns.length,0);this.session=o;const u=this.session.sessionId;return this.session.sessionId=p.generateId("ssn"),this.session.timestamp=(new Date).toISOString(),d.logger.log(`[${this.model}]: [session] loaded ${u} from ${r} (${o.conversations.length} conversation(s), ${l} turn(s)), continuing as ${this.session.sessionId}`),!0}resolveStoreFile(e,t,r){if(!r)return t;if(r===t){const r=this.archiveNumberBelow(e,t,Number.POSITIVE_INFINITY);if(0===r)return;return`${t}.${String(r).padStart(7,"0")}`}const n=p.archiveNumber(t,r);if(void 0===n)return;const s=this.archiveNumberBelow(e,t,n);return 0!==s?`${t}.${String(s).padStart(7,"0")}`:void 0}static archiveNumber(e,t){const r=`${e}.`;if(!t.startsWith(r))return;const n=t.slice(r.length);return/^\d+$/.test(n)?Number.parseInt(n,10):void 0}archiveNumberBelow(e,t,r){if(!a.existsSync(e))return 0;let n=0;for(const s of a.readdirSync(e)){const e=p.archiveNumber(t,s);void 0!==e&&(e>=r||e>n&&(n=e))}return n}getAll(e){const t=c.join((0,h.getAppHome)(),".storage"),r=`${Buffer.from(this.model,"utf-8").toString("base64url")}.csv`,n=this.resolveStoreFile(t,r,e);if(void 0===n){const t=e||"the live store";return d.logger.log(`[${this.model}]: [session] no older store to list after ${t}`),[]}const s=c.join(t,n),i=n===r?Number.POSITIVE_INFINITY:p.archiveNumber(r,n),o=void 0!==i&&this.archiveNumberBelow(t,r,i)>0,l=c.basename(s),u=new Map;if(a.existsSync(s)){const e=p.parseCsv(a.readFileSync(s,"utf-8"));for(const t of e)t.length<4||"sessionid"===t[0]||u.set(t[0],{sessionId:t[0],timestamp:t[1],description:p.decodeDescription(t[2]),fromFile:l,hasMore:o})}else if(n!==r)return d.logger.log(`[${this.model}]: [session] no session store at ${s}`),[];if(n===r){const e=this.activeSummary(l,o);void 0!==e&&u.set(e.sessionId,e)}const f=Array.from(u.values()).sort((e,t)=>t.timestamp.localeCompare(e.timestamp));return d.logger.log(`[${this.model}]: [session] ${f.length} session(s) listed from ${s}`),f}latestConversation(){const e=this.session.conversations.length;if(0!==e)return this.session.conversations[e-1]}latestTurn(){const e=this.latestConversation();if(void 0===e)return;const t=e.turns.length;return 0!==t?e.turns[t-1]:void 0}firstTurn(){for(const e of this.session.conversations)if(e.turns.length>0)return e.turns[0]}activeSummary(e,t){const r=this.firstTurn();if(void 0===r)return;const n=r.request.content.length>100?r.request.content.slice(0,100)+"...":r.request.content;return{sessionId:this.sessionId,timestamp:this.session.timestamp,description:n,fromFile:e,hasMore:t}}static csvField(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}static zip(e,t){const r=Buffer.from(e,"utf-8"),n=l.deflateRawSync(Buffer.from(t,"utf-8")),s=p.crc32(Buffer.from(t,"utf-8")),i=p.dosTimestamp(new Date),o=Buffer.alloc(30);o.writeUInt32LE(67324752,0),o.writeUInt16LE(20,4),o.writeUInt16LE(2048,6),o.writeUInt16LE(8,8),o.writeUInt16LE(i.time,10),o.writeUInt16LE(i.date,12),o.writeUInt32LE(s,14),o.writeUInt32LE(n.length,18),o.writeUInt32LE(n.length,22),o.writeUInt16LE(r.length,26),o.writeUInt16LE(0,28);const a=o.length+r.length+n.length,c=Buffer.alloc(46);c.writeUInt32LE(33639248,0),c.writeUInt16LE(20,4),c.writeUInt16LE(20,6),c.writeUInt16LE(2048,8),c.writeUInt16LE(8,10),c.writeUInt16LE(i.time,12),c.writeUInt16LE(i.date,14),c.writeUInt32LE(s,16),c.writeUInt32LE(n.length,20),c.writeUInt32LE(n.length,24),c.writeUInt16LE(r.length,28),c.writeUInt16LE(0,30),c.writeUInt16LE(0,32),c.writeUInt16LE(0,34),c.writeUInt16LE(0,36),c.writeUInt32LE(0,38),c.writeUInt32LE(0,42);const u=c.length+r.length,h=Buffer.alloc(22);return h.writeUInt32LE(101010256,0),h.writeUInt16LE(0,4),h.writeUInt16LE(0,6),h.writeUInt16LE(1,8),h.writeUInt16LE(1,10),h.writeUInt32LE(u,12),h.writeUInt32LE(a,16),h.writeUInt16LE(0,20),Buffer.concat([o,r,n,c,r,h])}static unzip(e){if(e.length<30||67324752!==e.readUInt32LE(0))throw new Error("Invalid zip archive: the local file header is missing.");const t=e.readUInt16LE(8),r=e.readUInt32LE(18),n=30+e.readUInt16LE(26)+e.readUInt16LE(28),s=e.subarray(n,n+r);if(0===t)return s.toString("utf-8");if(8===t)return l.inflateRawSync(s).toString("utf-8");throw new Error(`Unsupported zip compression method "${t}".`)}static parseCsv(e){const t=[];let r=[],n="",s=!1,i=0;for(;i<e.length;){const o=e[i];if(s){if('"'===o){if('"'===e[i+1]){n+='"',i+=2;continue}s=!1,i+=1;continue}n+=o,i+=1}else'"'!==o?","!==o?"\n"!==o&&"\r"!==o?(n+=o,i+=1):(r.push(n),t.push(r),r=[],n="",i+="\r"===o&&"\n"===e[i+1]?2:1):(r.push(n),n="",i+=1):(s=!0,i+=1)}return(n.length>0||r.length>0)&&(r.push(n),t.push(r)),t}static dosTimestamp(e){const t=Math.max(e.getFullYear(),1980);return{time:e.getHours()<<11|e.getMinutes()<<5|Math.floor(e.getSeconds()/2),date:t-1980<<9|e.getMonth()+1<<5|e.getDate()}}static crc32(e){const t=p.crcTable();let r=4294967295;for(let n=0;n<e.length;n++)r=t[255&(r^e[n])]^r>>>8;return(4294967295^r)>>>0}static crcTable(){if(void 0!==p.crcLookup)return p.crcLookup;const e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let e=0;e<8;e++)r=1&~r?r>>>1:3988292384^r>>>1;e[t]=r>>>0}return p.crcLookup=e,e}requireTurn(e){const t=this.latestTurn();if(void 0===t)throw new Error("The session has no turn to attach to.");if(t.msgId!==e)throw new Error(`msgId mismatch, the latest turn belongs to "${t.msgId}" but "${e}" was given.`);return t}static isSession(e){if(null==e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.sessionId||"string"!=typeof t.timestamp||!Array.isArray(t.conversations))return!1;for(const e of t.conversations){if(null==e||"string"!=typeof e.cvsId||!Array.isArray(e.turns))return!1;for(const t of e.turns){if(null==t||"string"!=typeof t.msgId)return!1;if(!p.isTurnRequest(t.request)||!p.isTurnResponse(t.response))return!1;if(!Array.isArray(t.messages))return!1}}return!0}static isTurnRequest(e){return null!=e&&"object"==typeof e&&"string"==typeof e.content}static isTurnResponse(e){if(null==e||"object"!=typeof e)return!1;const t=e;return(null===t.respId||"string"==typeof t.respId)&&"string"==typeof t.content}static parse(e,t){const r=JSON.parse(t);if(!p.isSession(r))throw new Error("Invalid session JSON: does not match the session scheme.");return new p(e,r)}static createSession(){return{sessionId:p.generateId("ssn"),timestamp:(new Date).toISOString(),conversations:[]}}static generateId(e){return`${e}-${(0,u.generateMessageId)()}`}}t.AxleSession=p},7841(e,t,r){"use strict";var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&s(t,e,r[o]);return i(t,e),t}),a=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})},c=this&&this.__await||function(e){return this instanceof c?(this.v=e,this):new c(e)},l=this&&this.__asyncGenerator||function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=r.apply(e,t||[]),i=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),n[Symbol.asyncIterator]=function(){return this},n;function o(e,t){s[e]&&(n[e]=function(t){return new Promise(function(r,n){i.push([e,t,r,n])>1||a(e,t)})},t&&(n[e]=t(n[e])))}function a(e,t){try{(r=s[e](t)).value instanceof c?Promise.resolve(r.value.v).then(l,u):h(i[0][2],r)}catch(e){h(i[0][3],e)}var r}function l(e){a("next",e)}function u(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}};Object.defineProperty(t,"__esModule",{value:!0}),t.Tail=void 0;const u=r(8474),h=o(r(3024)),d=o(r(6760)),f=r(7576),p=String.fromCharCode(10),_=String.fromCharCode(13);class g extends u.EventEmitter{constructor(e,t,r={}){var n,s,i,o,a,c;super(),this.position=0,this.closed=!1,this.started=!1,this.watcher=null,this.dirWatcher=null,this.pollTimer=null,this.conduit=null,this.filePath=d.resolve(e),this.conduit=t,this.options={pollInterval:null!==(n=r.pollInterval)&&void 0!==n?n:500,usePolling:null!==(s=r.usePolling)&&void 0!==s&&s,follow:null!==(i=r.follow)&&void 0!==i&&i,encoding:null!==(o=r.encoding)&&void 0!==o?o:"utf8",chunkSize:null!==(a=r.chunkSize)&&void 0!==a?a:65536,initialBytes:null!==(c=r.initialBytes)&&void 0!==c?c:0}}start(){return a(this,void 0,void 0,function*(){if(this.started)return this;if(this.started=!0,!(yield this.exists())){if(!this.options.follow)throw new Error("ENOENT: no such file or directory: "+this.filePath);if(yield this.waitForFile(),this.closed)return this}if(this.options.initialBytes>0){const e=yield this.size();this.position=Math.max(0,e-this.options.initialBytes)}return yield this.flush(),this.closed||this.startWatching(),this})}stop(){return a(this,void 0,void 0,function*(){this.closed||(this.closed=!0,this.stopWatching(),this.emitEvent("close"))})}close(){this.stop()}get offset(){return this.position}lines(){return l(this,arguments,function*(){let e="";const t=[];let r=null,n=!1,s=null;const i=()=>{if(r){const e=r;r=null,e()}},o=r=>{e+=r;let n=e.indexOf(p);for(;-1!==n;){let r=e.slice(0,n);r.endsWith(_)&&(r=r.slice(0,-1)),t.push(r),e=e.slice(n+1),n=e.indexOf(p)}i()},a=e=>{s=e,i()},l=()=>{n=!0,i()};this.on("data",o),this.on("error",a),this.on("close",l);try{for(;;)if(t.length>0)yield yield c(t.shift());else{if(s)throw s;if(n)break;yield c(new Promise(e=>{r=e}))}e.length>0&&(yield yield c(e))}finally{this.off("data",o),this.off("error",a),this.off("close",l)}})}emitEvent(e,t){if(!this.conduit)return;let r="";t instanceof Error?r=t.message:null!=t&&(r=String(t)),this.conduit.sendMessage((0,f.generateMessageId)(),e,"log",r)}exists(){return h.promises.access(this.filePath,h.constants.F_OK).then(()=>!0).catch(()=>!1)}size(){return h.promises.stat(this.filePath).then(e=>e.size).catch(()=>0)}waitForFile(){const e=d.dirname(this.filePath),t=d.basename(this.filePath);return new Promise(r=>{const n=()=>{this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)},s=()=>{if(this.closed)return n(),void r();this.exists().then(e=>{e&&(n(),r())})};try{this.dirWatcher=h.watch(e,(e,r)=>{r&&r.toString()!==t||s()}),this.dirWatcher.on("error",n)}catch(e){this.dirWatcher=null}this.pollTimer=setInterval(s,this.options.pollInterval),s()})}startWatching(){if(this.options.usePolling)this.startPolling();else try{this.watcher=h.watch(this.filePath,{persistent:!0},()=>this.schedule()),this.watcher.on("error",e=>{this.emitEvent("error",e),this.startPolling()}),this.emitEvent("watch","fs.watch")}catch(e){this.emitEvent("error",e),this.startPolling()}}startPolling(){this.pollTimer||this.closed||(this.watcher&&(this.watcher.close(),this.watcher=null),this.pollTimer=setInterval(()=>this.schedule(),this.options.pollInterval))}stopWatching(){this.watcher&&(this.watcher.close(),this.watcher=null),this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}schedule(){this.closed||this.dispatch()}dispatch(){return a(this,void 0,void 0,function*(){try{this.conduit&&(yield this.conduit.sendMessageAsync((0,f.generateMessageId)(),"flush","log","")),yield this.flush()}catch(e){this.emitEvent("error",e)}})}flush(){return a(this,void 0,void 0,function*(){if(this.closed)return;let e;try{e=yield h.promises.stat(this.filePath)}catch(e){if("ENOENT"===e.code)return;throw e}e.size<this.position&&(this.position=0,this.emitEvent("truncate",e.size)),e.size!==this.position&&(yield this.readFromPosition())})}readFromPosition(){return a(this,void 0,void 0,function*(){let e;try{e=yield h.promises.open(this.filePath,"r")}catch(e){if("ENOENT"===e.code)return;throw e}try{const t=Buffer.allocUnsafe(this.options.chunkSize);for(;!this.closed;){const{bytesRead:r}=yield e.read(t,0,t.length,this.position);if(r<=0)break;this.position+=r,this.emitEvent("data",t.toString(this.options.encoding,0,r))}}finally{yield e.close()}})}}t.Tail=g},82(e,t,r){"use strict";var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&s(t,e,r[o]);return i(t,e),t}),a=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0});const c=r(4157),l=o(r(9896)),u=o(r(6928)),h=r(2578),d=r(7201),f=r(2201),p=r(651),_=r(7841),g=r(5214),m=r(2201),y=r(7373),A=r(2038),v=o(r(8611)),b=o(r(5692)),w=r(8404),E=r(7576);function I(){const e=process.env.AXLE_ICON_PATH;return e&&""!==e.trim()?u.resolve(e.trim()):c.app.isPackaged?u.join(process.resourcesPath,"app-icon.png"):u.join(__dirname,"..","..","resources","app-icon.png")}"win32"===process.platform&&c.app.setAppUserModelId("Open-Axle");let S=null;const P=new Map;function k(){for(const e of P.values()){e.timer&&(clearTimeout(e.timer),e.timer=null);try{e.watcher.close()}catch(e){}}P.clear()}const O=new Map;function C(){S=new c.BrowserWindow({width:1e3,height:720,title:"Open Axle",icon:I(),webPreferences:{contextIsolation:!0,nodeIntegration:!1,preload:require("path").resolve(__dirname,"../renderer","main_window","preload.js")}}),S.loadURL(`file://${require("path").resolve(__dirname,"..","renderer","main_window","index.html")}`),S.maximize(),S.on("closed",()=>{k(),S=null})}function R(e){const t=new d.QueuedConduit;return t.subscribe(t=>a(this,void 0,void 0,function*(){null==S||S.webContents.send("axle:broadcast",Object.assign(Object.assign({},t),{modelName:e.name}))})),t.start(),new h.AxleAgent(e,t)}const B=new Map;function x(e,t){var r;if(!e)return{error:"No server name"};const n=null===(r=M(t))||void 0===r?void 0:r.getFullSkillConfig();let s=n?(0,g.resolveSkillConfig)(n,"ssh",e):null;if(s&&0!==Object.keys(s).length||(s=n?(0,g.resolveSkillConfig)(n,"scp",e):null),!s||0===Object.keys(s).length)return{error:`Unknown remote server: ${e}`};const i=s.host||"";if(!i)return{error:`No host configured for server: ${e}`};const o={host:i,port:s.port||"22",user:s.user_name||"",authType:s.auth_type||"password",keyFile:s.key_file||"",password:s.pass||""};return{target:o,key:(0,y.buildSshCacheKey)(o)}}function T(e,t){return a(this,void 0,void 0,function*(){const r=B.get(t);if(r)return r;const n=yield(0,y.getSshConn)(t,(0,y.buildSshConnectConfig)(e)),s=yield(0,w.getSftp)(n);B.set(t,s);const i=()=>{B.get(t)===s&&B.delete(t)};try{s.on("close",i),s.on("end",i),s.on("error",i)}catch(e){}return s})}function N(e){B.delete(e)}function F(){function e(e){return!(!e||"."===e||".."===e||e.indexOf("/")>=0||e.indexOf("\\")>=0)}function t(e,t){return(e||"").replace(/\/+$/,"")+"/"+t}function r(e,t){return new Promise(r=>{e.stat(t,(e,t)=>r(e?null:t))})}function n(e,t){return new Promise((r,n)=>{e.mkdir(t,e=>e?n(e):r())})}function s(e,t){return new Promise((r,n)=>{e.unlink(t,e=>e?n(e):r())})}function i(e,t){return new Promise((r,n)=>{e.readdir(t,(e,t)=>e?n(e):r(t||[]))})}function o(e){try{if(e&&e.attrs&&"function"==typeof e.attrs.isDirectory)return e.attrs.isDirectory()}catch(e){}return"string"==typeof(null==e?void 0:e.longname)&&e.longname.startsWith("d")}function h(e,t){return new Promise((r,n)=>{e.readFile(t,(e,t)=>e?n(e):r(t))})}function I(e,t,r){return new Promise((n,s)=>{e.writeFile(t,r,e=>e?s(e):n())})}function C(e,r){return a(this,void 0,void 0,function*(){var n;const a=yield i(e,r);for(const i of a){const a=String(null!==(n=null==i?void 0:i.filename)&&void 0!==n?n:"");if(!a||"."===a||".."===a)continue;const c=t(r,a);o(i)?yield C(e,c):yield s(e,c)}yield function(e,t){return new Promise((r,n)=>{e.rmdir(t,e=>e?n(e):r())})}(e,r)})}function B(e,t){const r=x(e.serverName,t);return!r.error&&r.target&&r.key?{target:r.target,key:r.key}:{error:r.error||"Unknown remote server"}}function F(e,s,o){return a(this,void 0,void 0,function*(){var a;const c=yield r(e,s);if(c&&"function"==typeof c.isDirectory&&c.isDirectory()){yield n(e,o);const r=yield i(e,s);for(const n of r){const r=String(null!==(a=null==n?void 0:n.filename)&&void 0!==a?a:"");r&&"."!==r&&".."!==r&&(yield F(e,t(s,r),t(o,r)))}return}const l=yield h(e,s);yield I(e,o,l)})}function L(e,n,s){return a(this,void 0,void 0,function*(){var o;const a=yield r(e,n);if(a&&"function"==typeof a.isDirectory&&a.isDirectory()){l.mkdirSync(s);const r=yield i(e,n);for(const i of r){const r=String(null!==(o=null==i?void 0:i.filename)&&void 0!==o?o:"");r&&"."!==r&&".."!==r&&(yield L(e,t(n,r),u.join(s,r)))}return}l.writeFileSync(s,yield h(e,n))})}function U(e,r,s){return a(this,void 0,void 0,function*(){if(l.statSync(r).isDirectory()){yield n(e,s);for(const n of l.readdirSync(r,{withFileTypes:!0}))yield U(e,u.join(r,n.name),t(s,n.name))}else yield I(e,s,l.readFileSync(r))})}function D(e){const t=Buffer.alloc(20);t.writeUInt32LE(20,0),t.writeInt32LE(0,4),t.writeInt32LE(0,8),t.writeInt32LE(0,12),t.writeInt32LE(1,16);const r=[t];for(const t of e)r.push(Buffer.from(t+"\0","utf16le"));return r.push(Buffer.from("\0","utf16le")),Buffer.concat(r)}function $(e){const t=e.trim();if(!t||t.startsWith("#"))return null;if(!/^file:\/\//i.test(t))return u.isAbsolute(t)?t:null;let r=t.replace(/^file:\/\//i,"");/^localhost\//i.test(r)&&(r=r.slice(9));let n=r;try{n=decodeURIComponent(r)}catch(e){n=r}return/^\/[a-zA-Z]:\//.test(n)?n.slice(1).replace(/\//g,"\\"):n.startsWith("/")?n:"/"+n}function j(e){return'electron application/osclipboard;format="'+e+'"'}function H(e){return a(this,void 0,void 0,function*(){try{const t=j(e);if(!(yield c.clipboard.has(t)))return null;const r=yield c.clipboard.read();for(const e of r){const r=e;if(!r||!Array.isArray(r.types)||r.types.indexOf(t)<0)continue;if("function"!=typeof r.getType)continue;const n=yield r.getType(t),s=n;if(s&&"function"==typeof s.arrayBuffer)return Buffer.from(yield s.arrayBuffer());if("string"==typeof n)return Buffer.from(n,"utf8")}return null}catch(e){return null}})}function G(){return a(this,void 0,void 0,function*(){const e=e=>{const t=[];for(const r of e){if("string"!=typeof r)continue;const e=r.replace(/\u0000+$/,"").trim().replace(/^"([\s\S]*)"$/,"$1").trim().replace(/^file:\/\/(?:localhost)?/i,"");if(!e)continue;try{if("remote"===(0,m.parsePath)(e).kind)continue}catch(e){continue}let n=e;try{n=l.realpathSync.native(e.replace(/[\\/]+$/,""))||e}catch(t){n=e}t.includes(n)||t.push(n)}return t};try{if("win32"===process.platform){const t=[],r=yield H("CF_HDROP");if(r){const e=function(e){const t=[];try{if(!e||e.length<=20)return t;const r=e.readUInt32LE(0),n=0!==e.readInt32LE(16);if(r<20||r>=e.length)return t;let s=r,i="";if(n)for(;s+1<e.length;){const r=e.readUInt16LE(s);if(s+=2,0===r){if(!i)break;t.push(i),i=""}else i+=String.fromCharCode(r)}else for(;s<e.length;){const r=e[s];if(s+=1,0===r){if(!i)break;t.push(i),i=""}else i+=String.fromCharCode(r)}}catch(e){}return t}(r);e.length&&t.push(...e)}const n=[];try{const e=yield H("text/uri-list"),t=e&&e.length>0?e.toString("utf8"):yield c.clipboard.readText();if(t&&t.length>0&&t.length<=8192)for(const e of t.split(/\r?\n/)){const t=$(e);if(t){try{if(!l.existsSync(t))continue}catch(e){continue}n.push(t)}}}catch(e){}if(t.length||n.length)return e(t.concat(n));const s=yield H("FileNameW");if(s&&s.length){const t=s.toString("utf16le").replace(/\u0000+$/,"");if(t)return e([t])}const i=yield H("FileName");if(i&&i.length){const t=i.toString("latin1").replace(/\u0000+$/,"");if(t)return e([t])}return[]}const t=yield c.clipboard.readText();if(!t||t.length>8192)return[];const r=[];for(const e of t.split(/\r?\n/)){const t=$(e);if(t){try{if(!l.existsSync(t))continue}catch(e){continue}r.push(t)}}return e(r)}catch(e){return[]}})}c.ipcMain.handle("axle:getModels",()=>{var e;try{return null!==(e=(new f.LlmConfig).getModels())&&void 0!==e?e:[]}catch(e){return[]}}),c.ipcMain.handle("axle:addModel",(e,t)=>{var r,n,s,i,o,a,l,u,h,d;try{const e=new f.LlmConfig,c={name:String(null!==(r=t.name)&&void 0!==r?r:""),url:String(null!==(n=t.url)&&void 0!==n?n:""),key:String(null!==(s=t.key)&&void 0!==s?s:""),model:String(null!==(i=t.model)&&void 0!==i?i:""),skillsFolder:String(null!==(o=t.skillsFolder)&&void 0!==o?o:"skills"),responses:Boolean(null!==(a=t.responses)&&void 0!==a&&a)};if(!(c.name&&c.url&&c.key&&c.model))throw new Error("Incomplete model configuration.");e.addModel(c);const h=null!==(l=e.getModel(c.name))&&void 0!==l?l:c;return!1===h.active||O.has(h.name)||O.set(h.name,R(h)),null!==(u=e.getModels())&&void 0!==u?u:[]}catch(e){return console.error("[axle] Failed to add model:",e),c.dialog.showErrorBox("Error",'Unable to add the LLM "'+(null!==(h=null==t?void 0:t.name)&&void 0!==h?h:"")+'". Check the configuration.'),null!==(d=(new f.LlmConfig).getModels())&&void 0!==d?d:[]}}),c.ipcMain.handle("axle:updateModel",(e,t,r)=>{var n,s,i,o,a;try{const e=new f.LlmConfig,a=String(null!=t?t:"").trim();if(!a)throw new Error("Missing model name.");const c=e.getModel(a);if(!c)throw new Error("Unknown model: "+a);const l={};void 0!==(null==r?void 0:r.url)&&(l.url=String(r.url).trim()),void 0!==(null==r?void 0:r.key)&&(l.key=String(r.key).trim()),void 0!==(null==r?void 0:r.model)&&(l.model=String(r.model).trim()),void 0!==(null==r?void 0:r.skillsFolder)&&(l.skillsFolder=String(r.skillsFolder).trim()||"skills"),void 0!==(null==r?void 0:r.responses)&&(l.responses=Boolean(r.responses));const u=null!==(n=l.url)&&void 0!==n?n:c.url,h=null!==(s=l.key)&&void 0!==s?s:c.key,d=null!==(i=l.model)&&void 0!==i?i:c.model;if(!u||!h||!d)throw new Error("Incomplete model configuration.");const p=e.updateModel(a,l);if(!p)throw new Error("Unable to update the model.");return!1!==p.active&&O.set(a,R(p)),null!==(o=e.getModels())&&void 0!==o?o:[]}catch(e){return console.error("[axle] Failed to update model:",e),c.dialog.showErrorBox("Error",'Unable to update the LLM "'+(null!=t?t:"")+'". Check the configuration.'),null!==(a=(new f.LlmConfig).getModels())&&void 0!==a?a:[]}}),c.ipcMain.handle("axle:listModels",(e,t,r)=>a(this,void 0,void 0,function*(){var e;try{const n=function(e){let t=String(null!=e?e:"").trim();return t=t.replace(/\/+$/,""),t?(/\/v\d+$/.test(t)||(t+="/v1"),t+"/models"):""}(t);if(!n)return{ok:!1,models:[],error:"Please enter a Base URL first."};const s={Accept:"application/json"},i=String(null!=r?r:"").trim();i&&(s.Authorization="Bearer "+i);const o=yield function(e,t){return new Promise(r=>{let n;try{n=new URL(e)}catch(t){return void r({ok:!1,status:0,body:"",error:"Invalid URL: "+e})}const s="http:"===n.protocol?v:b;let i=!1;const o=e=>{i||(i=!0,r(e))},a=s.request(n,{method:"GET",headers:t},e=>{const t=[];e.on("data",e=>t.push(e)),e.on("end",()=>{var r;const n=Buffer.concat(t).toString("utf-8"),s=null!==(r=e.statusCode)&&void 0!==r?r:0;o(s>=200&&s<300?{ok:!0,status:s,body:n}:{ok:!1,status:s,body:n,error:"HTTP "+s})}),e.on("error",e=>{o({ok:!1,status:0,body:"",error:String(e)})})});a.setTimeout(15e3,()=>{a.destroy(),o({ok:!1,status:0,body:"",error:"The request timed out."})}),a.on("error",e=>{o({ok:!1,status:0,body:"",error:String(e)})}),a.end()})}(n,s);if(!o.ok)return{ok:!1,models:[],error:o.error?o.error+" ("+n+")":"Failed to reach "+n};let a;try{a=JSON.parse(o.body)}catch(e){return{ok:!1,models:[],error:"The server did not return valid JSON."}}const c=Array.isArray(null==a?void 0:a.data)?a.data:Array.isArray(null==a?void 0:a.models)?a.models:[],l=[];for(const t of c){const r="string"==typeof t?t:null!==(e=null==t?void 0:t.id)&&void 0!==e?e:null==t?void 0:t.name;r&&"string"==typeof r&&!l.includes(r)&&l.push(r)}return 0===l.length?{ok:!1,models:[],error:"The server returned no models."}:(l.sort((e,t)=>e.localeCompare(t)),{ok:!0,models:l})}catch(e){return console.error("[axle] Failed to list models:",e),{ok:!1,models:[],error:String(e)}}})),c.ipcMain.handle("axle:getActiveModels",()=>{try{return(new f.LlmConfig).getActiveModels()}catch(e){return[]}}),c.ipcMain.handle("axle:setModelActive",(e,t,r)=>{try{const e=new f.LlmConfig,n=e.setActive(t,r);if(r){if(!O.has(t)){const r=e.getModel(t);r&&O.set(t,R(r))}}else{const e=O.get(t);e&&e.clear(),O.delete(t)}return n}catch(e){return console.error("[axle] Failed to set model active:",e),!1}}),c.ipcMain.handle("axle:talk",(e,t,r,n,s,i)=>{const o=M(r);if(o){const e="string"==typeof i&&i.trim()?i.trim():(0,E.generateMessageId)();o.talk({userinput:t,attachments:n},"string"==typeof s?s.trim():"",e)}}),c.ipcMain.handle("axle:deleteMessage",(e,t,r)=>a(this,void 0,void 0,function*(){const e=M(r);return!(!e||"string"!=typeof t||!t)&&(yield e.deleteMessage(t))})),c.ipcMain.handle("axle:saveImage",(e,t,r,n,s)=>{var i,o;try{if(!t||"string"!=typeof t)return{ok:!1,error:"No image data provided"};const e="string"==typeof s?s.trim():"";let a,c,h;if(e){const t=(0,m.parsePath)(e);if("remote"===t.kind)return{ok:!1,error:"Saving images to a remote directory is not supported yet."};let r=!1;try{r=l.statSync(t.path).isDirectory()}catch(e){r=!1}if(!r)return{ok:!1,error:"The target folder no longer exists."};a=t.path}else{const e=null!==(o=null===(i=M(r))||void 0===i?void 0:i.getCwd())&&void 0!==o?o:process.cwd(),t=(0,m.parsePath)(e);if("remote"===t.kind)return{ok:!1,error:"Saving images to a remote working directory is not supported yet."};a=t.path}const d=/^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]*)$/.exec(t);if(d)c=d[1].toLowerCase(),h=d[2].replace(/\s+/g,"");else{const e=/^data:(image\/[a-zA-Z0-9.+-]+)(?:;[^,]*)?,([\s\S]*)$/.exec(t);let r;if(e){c=e[1].toLowerCase();const t=e[2];try{r=decodeURIComponent(t)}catch(e){r=t}}else{if(!t.trim().startsWith("<"))return{ok:!1,error:"Unsupported image format (expected an image data URL or SVG markup)"};c="image/svg+xml",r=t}h=Buffer.from(r,"utf8").toString("base64")}let f="png";f="image/png"===c?"png":"image/jpeg"===c||"image/jpg"===c?"jpg":"image/webp"===c?"webp":"image/gif"===c?"gif":"image/svg+xml"===c?"svg":(c.split("/")[1]||"png").replace(/[^a-z0-9]/g,"")||"png";const p="string"==typeof n?n.trim():"";let _;if(p)_=((e,t)=>{let r=String(e||"");return r=r.split("/").join(""),r=r.split("\\").join(""),r=r.replace(/[<>:"|?*]/g,""),r=r.replace(/[\u0000-\u001f]/g,""),r=r.replace(/^\.+/,"").trim(),r||(r="image."+t),/\.(png|jpe?g|gif|svg|webp|bmp|ico|tiff?|avif)$/i.test(r)||(r+="."+t),r})(p,f);else{const e=new Date,t=e=>String(e).padStart(2,"0"),r=`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`;_=`image-${r}.${f}`}const g=u.join(a,_),y=Buffer.from(h,"base64");if(p){if(u.resolve(u.dirname(g))!==u.resolve(a))return{ok:!1,error:"Invalid image file name."};let e=!1;try{e=l.readdirSync(a).some(e=>e.toLowerCase()===_.toLowerCase())}catch(t){e=!1}if(!e)try{e=l.existsSync(g)}catch(t){e=!1}if(e)return{ok:!1,error:'"'+_+'" already exists in the working directory.'};try{l.writeFileSync(g,y,{flag:"wx"})}catch(e){if("EEXIST"===e.code)return{ok:!1,error:'"'+_+'" already exists in the working directory.'};throw e}}else l.writeFileSync(g,y);return{ok:!0,path:g,fileName:_}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to save image:",t),{ok:!1,error:t}}}),c.ipcMain.handle("axle:switchAgent",(e,t)=>O.has(t)),c.ipcMain.handle("axle:getSkills",(e,t)=>{var r;const n=M(t);return null!==(r=null==n?void 0:n.getSkills())&&void 0!==r?r:"No active model."}),c.ipcMain.handle("axle:reload",(e,t)=>{const r=M(t);null==r||r.reload()}),c.ipcMain.handle("axle:clear",(e,t)=>{const r=M(t);null==r||r.clear()}),c.ipcMain.handle("axle:cd",(e,t,r)=>a(this,void 0,void 0,function*(){const e=M(r);return e&&(yield e.cd(t)),!0})),c.ipcMain.handle("axle:stop",(e,t)=>{const r=M(t);return!!r&&(r.stop(),!0)}),c.ipcMain.handle("axle:validateDir",(e,t)=>{try{const e=(0,m.parsePath)(t);if("remote"===e.kind)return!0;const r=l.existsSync(e.path)&&l.statSync(e.path).isDirectory();return r||c.dialog.showErrorBox("Error","Invalid Directory!"),r}catch(e){return c.dialog.showErrorBox("Error","Invalid Directory!"),!1}}),c.ipcMain.handle("axle:getDefaultDir",()=>process.cwd()),c.ipcMain.handle("axle:listDir",(e,t)=>{try{if(!t)return[];const e=(0,m.parsePath)(t);if("remote"===e.kind)return[];return l.readdirSync(e.path,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch(e){return console.error("[axle] Failed to list dir:",e),[]}}),c.ipcMain.handle("axle:listEntries",(e,t)=>{try{if(!t)return[];const e=(0,m.parsePath)(t);if("remote"===e.kind)return[];const r=l.readdirSync(e.path,{withFileTypes:!0}).map(e=>({name:e.name,type:e.isDirectory()?"folder":"file"}));return r.sort((e,t)=>e.type!==t.type?"folder"===e.type?-1:1:e.name.localeCompare(t.name,void 0,{sensitivity:"base"})),r}catch(e){return console.error("[axle] Failed to list entries:",e),[]}}),c.ipcMain.handle("axle:getWorkingDir",(e,t)=>{var r;try{return null!==(r=(new f.LlmConfig).getWorkingDir(t))&&void 0!==r?r:process.cwd()}catch(e){return""}}),c.ipcMain.handle("axle:getWorkingDirInfo",(e,t)=>{var r;let n;try{const e=new f.LlmConfig;n=null!==(r=t?e.getWorkingDir(t):void 0)&&void 0!==r?r:process.cwd()}catch(e){n=process.cwd()}try{return(0,m.parsePath)(n)}catch(e){return{kind:"local",path:process.cwd()}}}),c.ipcMain.handle("axle:getRemoteServers",()=>{try{return(0,g.getRemoteServers)()}catch(e){return[]}}),c.ipcMain.handle("axle:listRemoteDir",(e,t,r,n,s)=>a(this,void 0,void 0,function*(){try{const e=x(t,s);if(e.error||!e.target)return{path:"",dirs:[],error:e.error||`Unknown remote server: ${t}`};const i=e.target,o=r?"cd "+("'"+r.replace(/'/g,"'\\''")+"'"):"cd",a=n?`${o} && pwd && ls -1Ap`:`${o} && pwd && ls -1Ap | grep '/$' | sed 's#/$##'`,c=(yield(0,y.sshExec)(i,a)).split(/\r?\n/).filter(e=>e.length>0);return{path:c.length>0?c[0]:r||"",dirs:c.slice(1),error:""}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to list remote dir:",t),{path:"",dirs:[],error:t}}})),c.ipcMain.handle("axle:watchDir",(e,t)=>{try{if(!t)return!1;const r=(0,m.parsePath)(t);if("remote"===r.kind)return!1;const n=u.resolve(r.path);if(P.has(n))return!0;const s=e.sender,i=l.watch(n,{persistent:!1},()=>{const e=P.get(n);e&&(e.timer&&clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null,e.webContents.isDestroyed()||e.webContents.send("axle:fsChanged",{dir:e.origDir})},200))});return i.on("error",()=>{const e=P.get(n);if(e){e.timer&&(clearTimeout(e.timer),e.timer=null);try{e.watcher.close()}catch(e){}P.delete(n)}}),P.set(n,{watcher:i,timer:null,webContents:s,origDir:t}),!0}catch(e){return console.error("[axle] Failed to watch dir:",e),!1}}),c.ipcMain.handle("axle:unwatchDir",(e,t)=>{try{if(!t)return!1;const e=(0,m.parsePath)(t);if("remote"===e.kind)return!1;const r=u.resolve(e.path),n=P.get(r);if(n){n.timer&&(clearTimeout(n.timer),n.timer=null);try{n.watcher.close()}catch(e){}P.delete(r)}return!0}catch(e){return console.error("[axle] Failed to unwatch dir:",e),!1}}),c.ipcMain.handle("axle:unwatchAll",()=>(k(),!0)),c.ipcMain.handle("axle:canEditFile",(e,t,r)=>a(this,void 0,void 0,function*(){let e="";try{if(!t)return{editable:!1,reason:"No file selected"};const n=(0,m.parsePath)(t);if("remote"===n.kind){const t=x(n.serverName,r);if(t.error||!t.target||!t.key)return{editable:!1,reason:t.error||"Unknown remote server"};e=t.key;const s=u.posix.extname(n.path).toLowerCase();if(Boolean(w.CODE_EXTENSION_LANGUAGE_MAP[s]||w.TEXT_EXTENSION_MIME_MAP[s]||w.PURE_TEXT_EXTENSION_MIME_MAP[s]))return{editable:!0,reason:""};const i=yield T(t.target,t.key),o=yield function(e,t){return new Promise((r,n)=>{const s=[];let i=!1;const o=e=>{i||(i=!0,e())};let a;try{a=e.createReadStream(t,{start:0,end:Math.max(0,8191)})}catch(e){return void n(e)}a.on("data",e=>{s.push(e)}),a.on("error",e=>o(()=>n(e))),a.on("end",()=>o(()=>r(Buffer.concat(s)))),a.on("close",()=>o(()=>r(Buffer.concat(s))))})}(i,n.path);return(0,w.isProbablyTextBuffer)(o)?{editable:!0,reason:""}:{editable:!1,reason:""}}const s=n.path;if(!l.statSync(s).isFile())return{editable:!1,reason:"Not a file"};const i=u.extname(s).toLowerCase();return Boolean(w.CODE_EXTENSION_LANGUAGE_MAP[i]||w.TEXT_EXTENSION_MIME_MAP[i]||w.PURE_TEXT_EXTENSION_MIME_MAP[i])||(0,w.isProbablyTextFile)(s)?{editable:!0,reason:""}:{editable:!1,reason:""}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to check file editability:",t),{editable:!1,reason:t}}})),c.ipcMain.handle("axle:readFileRaw",(e,t,r)=>a(this,void 0,void 0,function*(){let e="";try{if(!t)return{ok:!1,error:"No file selected"};const n=(0,m.parsePath)(t);if("remote"===n.kind){const t=x(n.serverName,r);if(t.error||!t.target||!t.key)return{ok:!1,error:t.error||"Unknown remote server"};e=t.key;const s=yield T(t.target,t.key);return{ok:!0,content:(yield(0,w.sftpReadFileBuffer)(s,n.path)).toString("utf-8")}}return{ok:!0,content:l.readFileSync(n.path,"utf-8")}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to read file:",t),{ok:!1,error:t}}})),c.ipcMain.handle("axle:writeFileRaw",(e,t,r,n)=>a(this,void 0,void 0,function*(){let e="";try{if(!t)return{ok:!1,error:"No file selected"};const s=(0,m.parsePath)(t);if("remote"===s.kind){const t=x(s.serverName,n);if(t.error||!t.target||!t.key)return{ok:!1,error:t.error||"Unknown remote server"};e=t.key;const i=yield T(t.target,t.key);return yield(0,w.sftpWriteFile)(i,s.path,null!=r?r:""),{ok:!0}}return l.writeFileSync(s.path,null!=r?r:"","utf-8"),{ok:!0}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to write file:",t),{ok:!1,error:t}}})),c.ipcMain.handle("axle:createFile",(t,n,s)=>a(this,void 0,void 0,function*(){let t="";try{if(!n)return{ok:!1,error:"No file selected"};const i=(0,m.parsePath)(n),o="remote"===i.kind?u.posix.basename(i.path):u.basename(i.path);if(!e(o))return{ok:!1,error:"Invalid file name."};if("remote"===i.kind){const e=B(i,s);if(e.error||!e.target||!e.key)return{ok:!1,error:e.error||"Unknown remote server"};t=e.key;const n=yield T(e.target,e.key);return(yield r(n,i.path))?{ok:!1,error:'A file or folder named "'+o+'" already exists.'}:(yield I(n,i.path,Buffer.from("","utf-8")),{ok:!0})}return l.writeFileSync(i.path,"",{encoding:"utf-8",flag:"wx"}),{ok:!0}}catch(e){if(t&&N(t),"EEXIST"===(null==e?void 0:e.code))return{ok:!1,error:"A file or folder with that name already exists."};const r=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to create file:",r),{ok:!1,error:r}}})),c.ipcMain.handle("axle:createFolder",(t,s,i)=>a(this,void 0,void 0,function*(){let t="";try{if(!s)return{ok:!1,error:"No folder selected"};const o=(0,m.parsePath)(s),a="remote"===o.kind?u.posix.basename(o.path):u.basename(o.path);if(!e(a))return{ok:!1,error:"Invalid folder name."};if("remote"===o.kind){const e=B(o,i);if(e.error||!e.target||!e.key)return{ok:!1,error:e.error||"Unknown remote server"};t=e.key;const s=yield T(e.target,e.key);return(yield r(s,o.path))?{ok:!1,error:'A file or folder named "'+a+'" already exists.'}:(yield n(s,o.path),{ok:!0})}return l.mkdirSync(o.path),{ok:!0}}catch(e){if(t&&N(t),"EEXIST"===(null==e?void 0:e.code))return{ok:!1,error:"A file or folder with that name already exists."};const r=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to create folder:",r),{ok:!1,error:r}}})),c.ipcMain.handle("axle:copyFile",(e,t,n,s)=>a(this,void 0,void 0,function*(){let e="";try{if(!t||!n)return{ok:!1,error:"No source or destination given"};const i=(0,m.parsePath)(t),o=(0,m.parsePath)(n);if(i.kind!==o.kind)return{ok:!1,error:"Copying between a local folder and a remote server is not supported."};if("remote"===i.kind){if(i.serverName!==o.serverName)return{ok:!1,error:"Copying between two remote servers is not supported."};const t=B(i,s);if(t.error||!t.target||!t.key)return{ok:!1,error:t.error||"Unknown remote server"};e=t.key;const n=yield T(t.target,t.key),a=yield r(n,i.path);if(!a)return{ok:!1,error:"The file to copy no longer exists."};if("function"==typeof a.isDirectory&&a.isDirectory())return{ok:!1,error:"Only files can be copied."};if(yield r(n,o.path))return{ok:!1,error:"A file or folder with that name already exists."};const c=yield h(n,i.path);return yield I(n,o.path,c),{ok:!0}}return l.statSync(i.path).isDirectory()?{ok:!1,error:"Only files can be copied."}:l.existsSync(o.path)?{ok:!1,error:"A file or folder with that name already exists."}:(l.copyFileSync(i.path,o.path),{ok:!0})}catch(t){e&&N(e);const r=t instanceof Error?t.message:String(t);return console.error("[axle] Failed to copy file:",r),{ok:!1,error:r}}})),c.ipcMain.handle("axle:copyEntry",(e,n,s,i)=>a(this,void 0,void 0,function*(){const e=[];try{if(!n||!s)return{ok:!1,error:"No source or destination given"};const o=(0,m.parsePath)(n),c=(0,m.parsePath)(s);if("remote"===o.kind&&"remote"===c.kind&&o.serverName!==c.serverName)return{ok:!1,error:"Copying between two remote servers is not supported."};const h=e=>e.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase();if(h(c.path).startsWith(h(o.path)+"/"))return{ok:!1,error:"A folder cannot be pasted inside itself."};let d=!1,f=null;if("remote"===o.kind){const t=B(o,i);if(t.error||!t.target||!t.key)return{ok:!1,error:t.error||"Unknown remote server"};e.push(t.key),f=yield T(t.target,t.key);const n=yield r(f,o.path);if(!n)return{ok:!1,error:"The item to copy no longer exists."};d="function"==typeof n.isDirectory&&n.isDirectory()}else{if(!l.existsSync(o.path))return{ok:!1,error:"The item to copy no longer exists."};d=l.statSync(o.path).isDirectory()}let p=null;if("remote"===c.kind)if(f)p=f;else{const t=B(c,i);if(t.error||!t.target||!t.key)return{ok:!1,error:t.error||"Unknown remote server"};e.push(t.key),p=yield T(t.target,t.key)}const _="remote"===c.kind?u.posix.dirname(c.path):u.dirname(c.path),g="remote"===c.kind?u.posix.basename(c.path):u.basename(c.path);if(!g||"."===g||".."===g)return{ok:!1,error:"Invalid destination name."};const y=e=>a(this,void 0,void 0,function*(){return"remote"===c.kind?Boolean(yield r(p,t(_,e))):l.existsSync(u.join(_,e))}),A=yield function(e,t){return a(this,void 0,void 0,function*(){if(!(yield t(e)))return e;const r=e.lastIndexOf("."),n=r>0?e.slice(0,r):e,s=r>0?e.slice(r):"";let i=n+" copy"+s,o=2;for(;yield t(i);)i=n+" copy "+o+s,o+=1;return i})}(g,y),v="remote"===c.kind?t(_,A):u.join(_,A);return"local"===o.kind&&"local"===c.kind?d?l.cpSync(o.path,v,{recursive:!0,errorOnExist:!0,force:!1}):l.copyFileSync(o.path,v):"remote"===o.kind&&"remote"===c.kind?yield F(f,o.path,v):"remote"===o.kind?yield L(f,o.path,v):yield U(p,o.path,v),{ok:!0,path:"remote"===c.kind?"ssh://"+(c.serverName||"")+v:v}}catch(t){for(const t of e)N(t);const r=t instanceof Error?t.message:String(t);return console.error("[axle] Failed to copy entry:",r),{ok:!1,error:r}}})),c.ipcMain.handle("axle:moveEntry",(e,t,n,s)=>a(this,void 0,void 0,function*(){let e="";try{if(!t||!n)return{ok:!1,error:"No source or destination given"};const i=(0,m.parsePath)(t),o=(0,m.parsePath)(n);if(i.kind!==o.kind)return{ok:!1,error:"Moving between a local folder and a remote server is not supported."};if("remote"===i.kind&&i.serverName!==o.serverName)return{ok:!1,error:"Moving between two remote servers is not supported."};const a="remote"===i.kind?u.posix.basename(i.path):u.basename(i.path);if(!a||"."===a||".."===a)return{ok:!1,error:"That entry cannot be moved."};const c="remote"===i.kind?"/":u.sep,h=o.path.replace(/[\\/]+$/,"")+c+a,d=e=>e.replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase();if(d(h)===d(i.path))return{ok:!0,path:t};if(d(h).startsWith(d(i.path)+"/"))return{ok:!1,error:"A folder cannot be moved inside itself."};if("remote"===i.kind){const t=B(i,s);if(t.error||!t.target||!t.key)return{ok:!1,error:t.error||"Unknown remote server"};e=t.key;const n=yield T(t.target,t.key);return(yield r(n,i.path))?(yield r(n,h))?{ok:!1,error:"A file or folder with that name already exists there."}:(yield((e,t,r)=>new Promise((n,s)=>{e.rename(t,r,e=>e?s(e):n())}))(n,i.path,h),{ok:!0,path:"ssh://"+(i.serverName||"")+h}):{ok:!1,error:"The item to move no longer exists."}}return l.existsSync(i.path)?l.existsSync(h)?{ok:!1,error:"A file or folder with that name already exists there."}:(l.renameSync(i.path,h),{ok:!0,path:h}):{ok:!1,error:"The item to move no longer exists."}}catch(t){e&&N(e);const r=t instanceof Error?t.message:String(t);return console.error("[axle] Failed to move entry:",r),{ok:!1,error:r}}})),c.ipcMain.handle("axle:deleteEntry",(e,t,n)=>a(this,void 0,void 0,function*(){let e="";try{if(!t)return{ok:!1,error:"Nothing selected"};const i=(0,m.parsePath)(t);if("remote"===i.kind){const t=B(i,n);if(t.error||!t.target||!t.key)return{ok:!1,error:t.error||"Unknown remote server"};e=t.key;const o=yield T(t.target,t.key),a=yield r(o,i.path);return a?("function"==typeof a.isDirectory&&a.isDirectory()?yield C(o,i.path):yield s(o,i.path),{ok:!0}):{ok:!1,error:"That entry no longer exists."}}return l.statSync(i.path).isDirectory()?l.rmSync(i.path,{recursive:!0,force:!1}):l.unlinkSync(i.path),{ok:!0}}catch(t){e&&N(e);const r=t instanceof Error?t.message:String(t);return console.error("[axle] Failed to delete entry:",r),{ok:!1,error:r}}})),c.ipcMain.handle("axle:getClipboardFiles",()=>a(this,void 0,void 0,function*(){try{return{ok:!0,files:yield G()}}catch(e){return{ok:!1,files:[],error:e instanceof Error?e.message:String(e)}}})),c.ipcMain.handle("axle:setClipboardFiles",(e,t)=>a(this,void 0,void 0,function*(){try{const e=Array.isArray(t)?t:[],r=[];for(const t of e){if("string"!=typeof t||!t)continue;const e=(0,m.parsePath)(t);if("remote"===e.kind)continue;let n=!1;try{n=l.existsSync(e.path)}catch(e){n=!1}n&&(r.includes(e.path)||r.push(e.path))}if(0===r.length)return{ok:!1,error:"Only local files can be placed on the system clipboard."};const n=r.map(e=>{const t=e.replace(/\\/g,"/");return"file://"+(/^[a-zA-Z]:\//.test(t)||t.startsWith("/")?t:"/"+t).split("/").map((e,t)=>t<=1&&/^([a-zA-Z]:)?$/.test(e)?e:encodeURIComponent(e)).join("/")}).join("\r\n")+"\r\n",s=r.join("\r\n");try{const e={"text/uri-list":n,"text/plain":s};if("win32"===process.platform){const t=globalThis.Blob;if(t){const n=j("CF_HDROP");e[n]=new t([D(r)],{type:n})}}return yield c.clipboard.write([new c.ClipboardItem(e)]),{ok:!0}}catch(e){return yield c.clipboard.writeText(s),{ok:!0}}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to set the file clipboard:",t),{ok:!1,error:t}}})),c.ipcMain.handle("axle:savePromptFile",(e,t,s,i,c,h)=>a(this,void 0,void 0,function*(){var e,a;try{if("string"!=typeof t)return{ok:!1,error:"No content provided"};const d="string"==typeof i?i.trim():"";if(!d)return{ok:!1,error:"Please enter a file name."};let f=d.replace(/^.*[\\/]/,"");if(f=f.replace(/[<>:"/\\|?*\u0000-\u001f]/g,""),f=f.replace(/^\.+/,"").trim(),!f)return{ok:!1,error:"Invalid file name."};const p=!0===c,_="string"==typeof h?h.trim():"",g=null!==(a=null===(e=M(s))||void 0===e?void 0:e.getCwd())&&void 0!==a?a:process.cwd(),y=_&&!p?(0,m.parsePath)(_):(0,m.parsePath)(g);if("remote"===y.kind){const e=x(y.serverName,s);if(e.error||!e.target||!e.key)return{ok:!1,error:e.error||"Unknown remote server"};const i=(y.path||".").replace(/\/+$/,""),a=p?`${i}/.axle/skills`:i,c=`${a}/${f}`,l=yield T(e.target,e.key);try{const e=yield r(l,a);if(e){if(!("function"==typeof e.isDirectory?e.isDirectory():o({attrs:e})))return{ok:!1,error:'Cannot save: "'+a+'" exists but is not a folder.'}}else{const e=[];let t=a;for(;t&&"/"!==t&&"."!==t&&!(yield r(l,t));){e.unshift(t);const r=u.posix.dirname(t);if(!r||r===t)break;t=r}for(const t of e)yield n(l,t)}}catch(e){const t=e instanceof Error?e.message:String(e);return{ok:!1,error:'Cannot create the folder "'+a+'" on '+y.serverName+": "+t+"."}}return(yield(0,w.remoteFileExists)(l,c))?{ok:!1,error:'"'+f+'" already exists in '+(p?"the .axle/skills folder":"the working directory")+"."}:(yield(0,w.sftpWriteFile)(l,c,t),{ok:!0,path:c,fileName:f})}const A=y.path,v=p?u.join(A,".axle","skills"):A,b=u.join(v,f);if(u.resolve(u.dirname(b))!==u.resolve(v))return{ok:!1,error:"Invalid file name."};try{if(l.existsSync(v)||l.mkdirSync(v,{recursive:!0}),!l.statSync(v).isDirectory())return{ok:!1,error:'Cannot save: "'+v+'" exists but is not a folder.'}}catch(e){const t=e.code;return{ok:!1,error:'Cannot create the folder "'+v+'": '+("EACCES"===t||"EPERM"===t?"permission denied":"ENOSPC"===t?"the disk is full":"EROFS"===t?"the location is read-only":e instanceof Error?e.message:String(e))+"."}}let E=!1;try{E=l.readdirSync(v).some(e=>e.toLowerCase()===f.toLowerCase())}catch(e){E=!1}if(!E)try{E=l.existsSync(b)}catch(e){E=!1}if(E)return{ok:!1,error:'"'+f+'" already exists in '+(p?"the .axle/skills folder":"the working directory")+"."};try{l.writeFileSync(b,t,{encoding:"utf-8",flag:"wx"})}catch(e){if("EEXIST"===e.code)return{ok:!1,error:'"'+f+'" already exists in '+(p?"the .axle/skills folder":"the working directory")+"."};throw e}return{ok:!0,path:b,fileName:f}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to save prompt file:",t),{ok:!1,error:t}}}));const Q=new Set([".svg"]),q=e=>{const t=w.IMAGE_EXTENSION_MIME_MAP[e];return t?t.mimeType:Q.has(e)?w.TEXT_EXTENSION_MIME_MAP[e]||"image/svg+xml":""};c.ipcMain.handle("axle:canViewFile",(e,t,r)=>a(this,void 0,void 0,function*(){try{if(!t)return{viewable:!1,kind:"",reason:"No file selected"};const e=(0,m.parsePath)(t),r=u.extname(e.path).toLowerCase();return q(r)?{viewable:!0,kind:"image",reason:""}:(e=>Boolean(w.CODE_EXTENSION_LANGUAGE_MAP[e]||w.TEXT_EXTENSION_MIME_MAP[e]||w.PURE_TEXT_EXTENSION_MIME_MAP[e]))(r)||"remote"!==e.kind&&(0,w.isProbablyTextFile)(e.path)?{viewable:!0,kind:"text",reason:""}:"remote"!==e.kind||[".zip",".gz",".tgz",".bz2",".xz",".7z",".rar",".tar",".exe",".dll",".so",".dylib",".bin",".o",".a",".obj",".class",".jar",".war",".pyc",".pyo",".wasm",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".ttf",".otf",".woff",".woff2",".eot",".mp3",".mp4",".wav",".ogg",".flac",".avi",".mov",".mkv",".webm",".sqlite",".db",".iso",".img",".dmg",".msi",".deb",".rpm"].includes(r)?{viewable:!1,kind:"",reason:"Not a viewable file"}:{viewable:!0,kind:"text",reason:""}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to check file previewability:",t),{viewable:!1,kind:"",reason:t}}})),c.ipcMain.handle("axle:readImageFile",(e,t,r)=>a(this,void 0,void 0,function*(){try{if(!t)return{ok:!1,error:"No file selected"};const e=(0,m.parsePath)(t),n=u.extname(e.path).toLowerCase(),s=q(n);if(!s)return{ok:!1,error:"Not a viewable image file: "+(n||"(no extension)")};if("remote"===e.kind){const t=x(e.serverName,r);if(t.error||!t.target||!t.key)return{ok:!1,error:t.error||"Unknown remote server"};const n=yield T(t.target,t.key);return{ok:!0,base64:(yield(0,w.sftpReadFileBuffer)(n,e.path)).toString("base64"),mimeType:s}}return{ok:!0,base64:l.readFileSync(e.path).toString("base64"),mimeType:s}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to read image file:",t),{ok:!1,error:t}}}));const W=1e3,K=/[*?[]/,X=/[.+(){}|^$\\]/,z=e=>"'"+e.replace(/'/g,"'\\''")+"'";c.ipcMain.handle("axle:findFiles",(e,t,r,n)=>a(this,void 0,void 0,function*(){try{const e="string"==typeof r?r:"";if(!t)return{ok:!1,error:"No directory to search"};if(!e)return{ok:!0,paths:[]};const s=(0,m.parsePath)(t),i=(e=>{if(K.test(e))return"glob";if(!X.test(e))return"substring";try{return new RegExp(e),"regex"}catch(e){return"substring"}})(e);if("remote"===s.kind){const t=x(s.serverName,n);if(t.error||!t.target)return{ok:!1,error:t.error||"Unknown remote server"};const r=s.path||".",o="regex"===i?"find "+z(r)+" -type f -regextype posix-extended -iregex "+z(".*"+e+".*"):"find "+z(r)+" -type f -iname "+z("*"+e+"*"),a=yield(0,y.sshExec)(t.target,o),c="ssh://"+s.serverName,l=(s.path||"").replace(/\/+$/,""),u=[],h=a.split(/\r?\n/);for(let e=0;e<h.length&&u.length<W;e++){const t=h[e].trim();if(t)if("/"===t.charAt(0))u.push(c+t);else{const e=t.replace(/^\.\//,""),r="/"===l.charAt(0)?l:"/"+l;u.push(c+r+"/"+e)}}if(0===u.length&&s.path)try{if(-1!==(yield(0,y.sshExec)(t.target,"test -d "+z(s.path)+" || echo AXLE_MISSING_DIR")).indexOf("AXLE_MISSING_DIR"))return{ok:!1,error:"Cannot search "+s.path+" on "+s.serverName+": the directory is missing or unreadable."}}catch(e){}return{ok:!0,paths:u,truncated:u.length>=W}}let o=s.path;try{l.statSync(o).isFile()&&(o=u.dirname(o))}catch(e){}const a={paths:o,type:"f",maxResults:W},c="regex"===i?yield(0,A.findFiles)(Object.assign({},a,{iregex:".*"+e+".*"})):yield(0,A.findFiles)(Object.assign({},a,{iname:e,nameMatchMode:i})),h=[];for(let e=0;e<c.entries.length;e++)h.push(c.entries[e].path);if(0===h.length)try{l.statSync(o)}catch(e){return{ok:!1,error:"Cannot search "+o+": the directory is missing or unreadable."}}return{ok:!0,paths:h,truncated:h.length>=W}}catch(e){const t=e instanceof Error?e.message:String(e);return console.error("[axle] Failed to find files:",t),{ok:!1,error:t}}}));let Y=null,J=null;c.ipcMain.handle("axle:getLogPath",()=>p.logger.logFilePath),c.ipcMain.handle("axle:startLogTail",()=>a(this,void 0,void 0,function*(){Y&&(yield Y.stop(),Y=null),J&&(J.stop(),J=null);const e=new d.QueuedConduit;e.subscribe(e=>a(this,void 0,void 0,function*(){null==S||S.webContents.send("axle:logData",{type:e.message,data:e.content})})),e.start(),J=e;const t=new _.Tail(p.logger.logFilePath,e,{follow:!0,usePolling:!0});Y=t;try{yield t.start()}catch(e){console.error("[axle] Failed to start log tail:",e)}return p.logger.logFilePath})),c.ipcMain.handle("axle:stopLogTail",()=>a(this,void 0,void 0,function*(){return Y&&(yield Y.stop(),Y=null),J&&(J.stop(),J=null),!0})),c.ipcMain.handle("axle:setWorkingDir",(e,t,r)=>{try{return(new f.LlmConfig).setWorkingDir(r,t)}catch(e){return!1}}),c.ipcMain.handle("axle:getAllSessions",(e,t,r)=>{const n=M(t);return n?n.getAllSessions(r):[]}),c.ipcMain.handle("axle:readSession",(e,t,r,n)=>{const s=M(t);if(!s)return{ok:!1,error:"No agent is available for this model."};try{const e=s.readSession(r,n);return e?{ok:!0,session:e}:{ok:!1,error:"The session was not found in the store."}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}),c.ipcMain.handle("axle:loadSession",(e,t,r)=>{const n=M(t);if(!n)return{ok:!1,error:"No agent is available for this model."};if("string"!=typeof r||!r.trim())return{ok:!1,error:"No session id was provided."};try{return n.loadSession(r.trim())?{ok:!0}:{ok:!1,error:"The session was not found in the store."}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}})}function M(e){if(e){let t=O.get(e);if(!t)try{const r=(new f.LlmConfig).getModel(e);r&&!1!==r.active&&(t=R(r),O.set(e,t))}catch(t){console.error("[axle] Failed to lazily create agent for",e,t)}return t}return O.values().next().value}process.on("uncaughtException",e=>{console.error("[axle] uncaughtException",e)}),c.app.whenReady().then(()=>{if("darwin"===process.platform&&c.app.dock)try{c.app.dock.setIcon(I())}catch(e){console.warn("[axle] Failed to set the Dock icon:",e)}C(),function(){try{const e=new f.LlmConfig;for(const t of e.getActiveModels())O.set(t.name,R(t))}catch(e){p.logger.log(`Failed to initilize agents ${e}`),console.error("[axle] Failed to initialize agents:",e)}}(),F(),c.app.on("activate",()=>{0===c.BrowserWindow.getAllWindows().length&&C()})}),c.app.on("window-all-closed",()=>{"darwin"!==process.platform&&c.app.quit()});let L=!1;function U(){if(!L){L=!0;for(const e of O.values())try{e.clear()}catch(e){console.error("[axle] Failed to flush the agent session on exit:",e)}}}process.on("SIGINT",()=>{U(),process.exit(130)}),process.on("SIGTERM",()=>{U(),process.exit(143)}),process.on("exit",()=>{U()}),c.app.on("before-quit",e=>{L||(e.preventDefault(),U(),c.app.quit()),k()})},2613(e){"use strict";e.exports=require("assert")},181(e){"use strict";e.exports=require("buffer")},5317(e){"use strict";e.exports=require("child_process")},6982(e){"use strict";e.exports=require("crypto")},2250(e){"use strict";e.exports=require("dns")},4157(e){"use strict";e.exports=require("electron")},4434(e){"use strict";e.exports=require("events")},9896(e){"use strict";e.exports=require("fs")},8611(e){"use strict";e.exports=require("http")},5692(e){"use strict";e.exports=require("https")},3339(e){"use strict";e.exports=require("module")},9278(e){"use strict";e.exports=require("net")},8474(e){"use strict";e.exports=require("node:events")},3024(e){"use strict";e.exports=require("node:fs")},8161(e){"use strict";e.exports=require("node:os")},6760(e){"use strict";e.exports=require("node:path")},8522(e){"use strict";e.exports=require("node:zlib")},857(e){"use strict";e.exports=require("os")},6928(e){"use strict";e.exports=require("path")},2203(e){"use strict";e.exports=require("stream")},4756(e){"use strict";e.exports=require("tls")},9023(e){"use strict";e.exports=require("util")},3106(e){"use strict";e.exports=require("zlib")},438(e,t){"use strict";t.MalformedJSON=t.partialParse=void 0;class r extends Error{}class n extends Error{}t.MalformedJSON=n;t.partialParse=e=>function(e,t=511){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return((e,t)=>{const s=e.length;let i=0;const o=e=>{throw new r(`${e} at position ${i}`)},a=e=>{throw new n(`${e} at position ${i}`)},c=()=>(f(),i>=s&&o("Unexpected end of input"),'"'===e[i]?l():"{"===e[i]?u():"["===e[i]?h():"null"===e.substring(i,i+4)||16&t&&s-i<4&&"null".startsWith(e.substring(i))?(i+=4,null):"true"===e.substring(i,i+4)||32&t&&s-i<4&&"true".startsWith(e.substring(i))?(i+=4,!0):"false"===e.substring(i,i+5)||32&t&&s-i<5&&"false".startsWith(e.substring(i))?(i+=5,!1):"Infinity"===e.substring(i,i+8)||128&t&&s-i<8&&"Infinity".startsWith(e.substring(i))?(i+=8,1/0):"-Infinity"===e.substring(i,i+9)||256&t&&s-i>1&&s-i<9&&"-Infinity".startsWith(e.substring(i))?(i+=9,-1/0):"NaN"===e.substring(i,i+3)||64&t&&s-i<3&&"NaN".startsWith(e.substring(i))?(i+=3,Number.NaN):d()),l=()=>{const r=i;let n=!1;for(i++;i<s&&('"'!==e[i]||n&&"\\"===e[i-1]);)n="\\"===e[i]&&!n,i++;if('"'===e.charAt(i))try{return JSON.parse(e.substring(r,++i-Number(n)))}catch(e){a(String(e))}else if(1&t)try{return JSON.parse(e.substring(r,i-Number(n))+'"')}catch{return JSON.parse(e.substring(r,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},u=()=>{i++,f();const r={};try{for(;"}"!==e[i];){if(f(),i>=s&&8&t)return r;const n=l();f(),i++;try{const e=c();Object.defineProperty(r,n,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(8&t)return r;throw e}f(),","===e[i]&&i++}}catch{if(8&t)return r;o("Expected '}' at end of object")}return i++,r},h=()=>{i++;const r=[];try{for(;"]"!==e[i];)r.push(c()),f(),","===e[i]&&i++}catch{if(4&t)return r;o("Expected ']' at end of array")}return i++,r},d=()=>{if(0===i){"-"===e&&2&t&&o("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(2&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(r))}}const r=i;for("-"===e[i]&&i++;e[i]&&!",]}".includes(e[i]);)i++;i!==s||2&t||o("Unterminated number literal");const n=e.substring(r,i);try{return JSON.parse(n)}catch{"-"===n&&2&t&&o("Not sure what '-' is");try{return JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch(e){a(String(e))}}},f=()=>{for(;i<s&&" \n\r\t".includes(e[i]);)i++};return c()})(e.trim(),t)}(e,509)},9392(e,t,r){"use strict";t.WorkloadIdentityAuth=void 0;const n=r(6316).__importStar(r(6786)),s=r(144),i={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"};function o(e,t,r){const n=1e3*(r??1200);return e-Math.min(n,1e3*t*.5)}const a=Response.prototype,c=a.arrayBuffer;function l(e,t){const r=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if(t===e||"function"!=typeof r||"Response"!==Object.getOwnPropertyDescriptor(r,"name")?.value||Object.getOwnPropertyDescriptor(r,"prototype")?.value!==t)return!1;const n=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);return("Response"===n?.value||"function"==typeof n?.get)&&"function"==typeof Object.getOwnPropertyDescriptor(t,"headers")?.get&&"function"==typeof Object.getOwnPropertyDescriptor(t,"ok")?.get&&"function"==typeof Object.getOwnPropertyDescriptor(t,"status")?.get}function u(e,t){if(e===t)return!0;const r=Object.getOwnPropertyDescriptor(e,"constructor")?.value;return null!==t&&Object.getPrototypeOf(t)===e&&"function"==typeof r&&"Body"===Object.getOwnPropertyDescriptor(r,"name")?.value&&Object.getOwnPropertyDescriptor(r,"prototype")?.value===e}class h{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl="https://auth.openai.com/oauth/token";const{identityProviderId:r,serviceAccountId:s,clientId:i,refreshBufferSeconds:o,provider:a}=e;this.config={identityProviderId:r,serviceAccountId:s,...void 0===i?{}:{clientId:i},...void 0===o?{}:{refreshBufferSeconds:o},provider:{tokenType:a.tokenType,getToken:a.getToken.bind(a)}},this.fetch=t??n.getDefaultFetch()}async getToken(){if(!this.cachedToken||h.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;const e=this.refreshToken(this.tokenGeneration);this.refreshPromise=e;try{return await e}finally{this.refreshPromise===e&&(this.refreshPromise=null)}}if(h.needsRefresh(this.cachedToken)&&!this.refreshPromise){const e=this.refreshToken(this.tokenGeneration).finally(()=>{this.refreshPromise===e&&(this.refreshPromise=null)});this.refreshPromise=e,e.catch(()=>null)}return this.cachedToken.token}async refreshToken(e){const t={grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:await this.config.provider.getToken(),subject_token_type:i[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);const r=performance.now(),n=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),redirect:"manual"});if(!n.ok){const e=await n.text();let t;try{t=JSON.parse(e)}catch{}if(400===n.status||401===n.status||403===n.status)throw new s.OAuthError(n.status,t,n.headers);throw s.APIError.generate(n.status,t,`Token exchange failed with status ${n.status}`,n.headers)}const h=await async function(e){let t,r=null;for(let n=0,s=e;null!==s&&n<16&&s!==a;s=Object.getPrototypeOf(s),n+=1){l(e,s)&&(r=s);const n=Object.getOwnPropertyDescriptor(s,"json");if(!n)continue;if("function"!=typeof n.value)break;const i=Object.getOwnPropertyDescriptor(s,"text")?.value;if("function"==typeof i&&u(s,r)){t=i;break}return n.value.call(e)}const n=void 0===t?function(e){const t=globalThis;return new TextDecoder("utf-8",{ignoreBOM:"string"==typeof t.Bun?.version}).decode(e)}(await c.call(e)):await t.call(e);try{return JSON.parse(n)}catch{throw new SyntaxError("Token exchange response contains invalid JSON")}}(n),d="object"==typeof h&&null!==h&&"access_token"in h?h.access_token:void 0;if("string"!=typeof d||0===d.trim().length||function(e){const t=globalThis;return"string"==typeof t.Bun?.version?/[^\t\u0020-\u007E]|^[\t ]|[\t ]$/u.test(e):/[^\t\u0020-\u007E\u0080-\u00FF]|^[\t ]|[\t ]$/u.test(e)}(d))throw new s.OpenAIError("Token exchange response missing 'access_token' field");const f=h.expires_in??3600,p=function(e,t){if("number"!=typeof e||!Number.isFinite(e)||e<=0)throw new s.OpenAIError("Token exchange response has invalid 'expires_in' field");const r=Date.now(),n=r+1e3*e;if(!Number.isSafeInteger(n)||n<=r)throw new s.OpenAIError("Token exchange response has invalid 'expires_in' field");const i=n-(performance.now()-t);if(i<=r)throw new s.OpenAIError("Workload identity token expired before its exchange completed.");return i}(f,r);return this.tokenGeneration===e&&(this.cachedToken={token:d,expiresAt:p,refreshAt:o(p,f,this.config.refreshBufferSeconds)}),d}static isTokenExpired(e){return Date.now()>=e.expiresAt}static needsRefresh(e){return Date.now()>=e.refreshAt}invalidateToken(){this.tokenGeneration+=1,this.cachedToken=null,this.refreshPromise=null}}t.WorkloadIdentityAuth=h},847(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AzureOpenAI=void 0;const n=r(6316),s=r(3098),i=n.__importStar(r(2154)),o=r(4737),a=r(8491),c=r(9393),l=r(7699);class u extends c.OpenAI{constructor({baseURL:e=(0,o.readEnv)("OPENAI_BASE_URL"),apiKey:t=(0,o.readEnv)("AZURE_OPENAI_API_KEY"),apiVersion:r=(0,o.readEnv)("OPENAI_API_VERSION"),endpoint:n,deployment:s,azureADTokenProvider:a,dangerouslyAllowBrowser:c,dataResidency:u,...h}={}){if((0,l.assertNoDataResidency)(u,"AzureOpenAI"),!r)throw new i.OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if("function"==typeof a&&(c??(c=!0)),!a&&!t)throw new i.OpenAIError("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new i.OpenAIError("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(h.defaultQuery={...h.defaultQuery,"api-version":r},e){if(n)throw new i.OpenAIError("baseURL and endpoint are mutually exclusive")}else{if(n||(n=process.env.AZURE_OPENAI_ENDPOINT),!n)throw new i.OpenAIError("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let t=n.length;for(;t>0&&"/"===n[t-1];)t--;e=`${n.slice(0,t)}/openai`}super({apiKey:a??t,baseURL:e,...h,...void 0===c?{}:{dangerouslyAllowBrowser:c}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=s}withOptions(e){const t={apiVersion:this.apiVersion,deployment:this.deploymentName,...e};return(0,o.hasOwn)(e,"endpoint")&&void 0!==e.endpoint&&!(0,o.hasOwn)(e,"baseURL")&&(t.baseURL=void 0),super.withOptions(t)}async buildRequest(e,t={}){if(h.has(e.path)&&"post"===e.method&&void 0!==e.body){if(!(0,o.isObj)(e.body))throw new Error("Expected request body to be an object");const t=this.deploymentName||e.body.model||e.__metadata?.model;void 0===t||function(e){try{return new URL(e).pathname.split("/").includes("deployments")}catch{return!1}}(this.baseURL)||(e.path=a.path`/deployments/${t}`+e.path)}const r=await super.buildRequest(e,t);return r.req.headers.has("api-key")&&(r.req.redirect="manual"),r}async fetchWithAuth(e,t,r,n,s){return new Headers(t.headers).has("api-key")&&(t.redirect="manual"),super.fetchWithAuth(e,t,r,n,s)}async authHeaders(e,t){const r=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return r.bearerAuth&&"string"==typeof this._options.apiKey?(0,s.buildHeaders)([{"api-key":this.apiKey}]):super.authHeaders(e,r)}}t.AzureOpenAI=u;const h=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"])},3542(e,t,r){"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.BedrockOpenAI=void 0;const s=r(6316),i=s.__importStar(r(2154)),o=r(9393),a=r(7699),c=r(1958),l=r(3098),u=r(4737),h=r(2987),d=s.__importStar(r(3998));function f(e){const t=new URL(e),r=t.pathname.match(/\/responses(?:\/.*)?$/);return void 0!==r?.index&&(t.pathname=t.pathname.slice(0,r.index)||"/"),t.toString().replace(/\/$/,"")}class p extends o.OpenAI{constructor({baseURL:e=(0,u.readEnv)("AWS_BEDROCK_BASE_URL"),apiKey:t,awsRegion:r=(0,u.readEnv)("AWS_REGION")??(0,u.readEnv)("AWS_DEFAULT_REGION"),bedrockTokenProvider:s,adminAPIKey:o,workloadIdentity:l,x509Transport:p,dataResidency:_,...g}={}){if((0,a.assertNoDataResidency)(_,"BedrockOpenAI"),o||l||p)throw new i.OpenAIError("BedrockOpenAI only supports Bedrock bearer token authentication.");if(void 0!==t||s||(t=(0,u.readEnv)("AWS_BEARER_TOKEN_BEDROCK")??null),"function"==typeof t)throw new i.OpenAIError("Pass refreshable Bedrock credentials via `bedrockTokenProvider`, not `apiKey`.");if(t&&s)throw new i.OpenAIError("The `apiKey` and `bedrockTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(!t&&!s)throw new i.OpenAIError("Missing credentials. Please pass an `apiKey` or `bedrockTokenProvider`, or set the `AWS_BEARER_TOKEN_BEDROCK` environment variable.");const m=e?.trim()?e:function(e){const t=e?.trim();if(!t)throw new i.OpenAIError("Must provide one of the `baseURL` or `awsRegion` arguments, or set the `AWS_BEDROCK_BASE_URL`, `AWS_REGION`, or `AWS_DEFAULT_REGION` environment variable.");if(!/^[a-z]{2,8}(?:-[a-z0-9]+)+-\d+$/u.test(t))throw new i.OpenAIError("The Bedrock AWS `region` is invalid. Use a standard AWS region such as `us-east-1`.");return`https://bedrock-mantle.${t}.api.aws/openai/v1`}(r);super({apiKey:s??t,adminAPIKey:null,baseURL:f(m),...g}),this[n]=!0;let y=this.apiKey;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,get:()=>(null!==y&&(0,c.assertValidBedrockBearerCredential)(y),y),set(e){y=e}});const A=this.baseURL;let v=A;Object.defineProperty(this,"baseURL",{enumerable:!0,configurable:!1,get:()=>v,set(e){(0,c.assertBedrockRequestOrigin)(A,e),v=e}}),this.bedrockTokenProvider=s,this.responses=function(e){const t=e.stream.bind(e);return e.stream=(e,r)=>{const n=t(e,r),s=n.finalResponse.bind(n);return n.finalResponse=async()=>{return e=await s(),Object.getOwnPropertyDescriptor(e,"output_text")||(0,h.addOutputText)(e),e;var e},n},e}(new d.Responses(this))}async prepareOptions(e){const t=this._options.baseURL??this.baseURL;(0,c.assertBedrockRequestOrigin)(t,this.buildURL(e.path,null,e.defaultBaseURL));const r=e.__security??{bearerAuth:!0};r.adminAPIKeyAuth&&!r.bearerAuth&&await this._callApiKey(),await super.prepareOptions(e),(0,c.assertBedrockRequestOrigin)(t,this.buildURL(e.path,null,e.defaultBaseURL))}async prepareRequest(e,t){(0,c.assertBedrockRequestOrigin)(this._options.baseURL??this.baseURL,t.url),await super.prepareRequest(e,t),e.redirect="manual"}async authHeaders(e,t){const r=t??{bearerAuth:!0,adminAPIKeyAuth:!0},n=this.apiKey;if((r.bearerAuth||r.adminAPIKeyAuth)&&null!==n){(0,c.assertValidBedrockBearerCredential)(n);try{return(0,l.buildHeaders)([{Authorization:`Bearer ${n}`}])}catch(e){if(e instanceof TypeError)throw new TypeError("Bedrock bearer credential contains an invalid HTTP header value.");throw e}}return super.authHeaders(e,r)}withOptions(e){const t=void 0===e.apiKey?e.bedrockTokenProvider??this.bedrockTokenProvider:void 0;return super.withOptions({...e,...t?{apiKey:void 0,bedrockTokenProvider:t}:{}})}}t.BedrockOpenAI=p,n=c.brand_privateBedrockClient},9393(e,t,r){"use strict";var n,s,i,o,a,c,l,u,h;Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAI=void 0;const d=r(6316),f=r(5263),p=r(8874),_=r(8233),g=r(7545),m=r(907),y=r(53),A=d.__importStar(r(6786)),v=d.__importStar(r(9462)),b=r(2602),w=r(3284),E=r(7699),I=d.__importStar(r(144)),S=d.__importStar(r(3604)),P=r(9392),k=r(5345),O=r(9523),C=r(8422),R=r(3679),B=r(144),x=d.__importStar(r(7692)),T=d.__importStar(r(3998)),N=r(398),F=r(8398),M=r(2873),L=r(8077),U=r(6566),D=r(7225),$=r(2566),j=r(9662),H=r(1955),G=r(9360),Q=r(2157),q=r(4425),W=r(4395),K=r(6083),X=r(8743),z=r(9609),Y=r(5733),J=r(5857),V=r(4149),Z=r(5819),ee=r(8725),te=r(1713),re=r(6399),ne=r(8667),se=r(4077),ie=r(4953),oe=r(4015),ae=r(53),ce=r(3098),le=r(7659),ue=r(3209),he=r(6048),de=r(8874);function fe(){if((0,ae.isRunningInBrowser)())return!0;const e=globalThis;return"function"==typeof e.WorkerGlobalScope&&e instanceof e.WorkerGlobalScope&&"function"==typeof e.WorkerNavigator&&e.navigator instanceof e.WorkerNavigator&&"string"==typeof e.navigator?.userAgent&&"Cloudflare-Workers"!==e.navigator.userAgent&&void 0===e.process?.versions?.node&&void 0===e.Deno&&void 0===e.Bun&&void 0===e.EdgeRuntime&&void 0===e.WebSocketPair}const pe=Symbol("inheritedDataResidencySelection");class _e{constructor(e={}){n.add(this),i.set(this,void 0),o.set(this,void 0),a.set(this,void 0),c.set(this,void 0),l.set(this,!1),u.set(this,new WeakMap),this.completions=new T.Completions(this),this.chat=new T.Chat(this),this.embeddings=new T.Embeddings(this),this.files=new T.Files(this),this.images=new T.Images(this),this.contentProvenanceChecks=new T.ContentProvenanceChecks(this),this.audio=new T.Audio(this),this.moderations=new T.Moderations(this),this.models=new T.Models(this),this.fineTuning=new T.FineTuning(this),this.graders=new T.Graders(this),this.vectorStores=new T.VectorStores(this),this.safety=new T.Safety(this),this.webhooks=new T.Webhooks(this),this.beta=new T.Beta(this),this.batches=new T.Batches(this),this.uploads=new T.Uploads(this),this.admin=new T.Admin(this),this.responses=new T.Responses(this),this.live=new T.Live(this),this.realtime=new T.Realtime(this),this.conversations=new T.Conversations(this),this.evals=new T.Evals(this),this.containers=new T.Containers(this),this.skills=new T.Skills(this),this.videos=new T.Videos(this);const{credential:t,options:r}=(0,C.normalizeX509CredentialOptions)(e);e=r;const h=(0,E.resolveDataResidency)(e),f=e.provider,{baseURL:p=(f?null:(0,ue.readEnv)("OPENAI_BASE_URL")),dataResidency:_,[pe]:g=!1,apiKey:m=(f?null:(0,ue.readEnv)("OPENAI_API_KEY")??null),adminAPIKey:y=(f?null:(0,ue.readEnv)("OPENAI_ADMIN_KEY")??null),organization:b=(f?null:(0,ue.readEnv)("OPENAI_ORG_ID")??null),project:w=(f?null:(0,ue.readEnv)("OPENAI_PROJECT_ID")??null),webhookSecret:S=(0,ue.readEnv)("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:B,x509Transport:x,credential:N,...F}=e;if(f){const t=["apiKey","adminAPIKey","workloadIdentity","x509Transport","baseURL","dataResidency"].filter(t=>null!=("workloadIdentity"===t?B:e[t]));if(t.length)throw new I.OpenAIError(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}const M=(0,O.isX509WorkloadIdentity)(B)?{x509:B,legacy:void 0}:{x509:void 0,legacy:B},L=M.x509,U=void 0!==L,D=f?(0,le.configureProvider)(f):void 0,$={apiKey:m,adminAPIKey:y,organization:b,project:w,webhookSecret:S,workloadIdentity:B,x509Transport:x,provider:f,...F,baseURL:D?.baseURL??h??(p||(U?k.X509_API_BASE_URL:"https://api.openai.com/v1"))};if(x&&!U)throw new I.OpenAIError("An X.509 transport requires an X.509 workload identity.");if(U){if(void 0!==h||g)throw new I.OpenAIError("X.509 workload identity does not support data residency selection.");if(void 0!==e.fetch)throw new I.OpenAIError("X.509 workload identity does not support a custom fetch implementation.");if((0,k.assertX509APIOrigin)($.baseURL),(0,O.assertX509RequestOptions)($.fetchOptions),this.fetchWithAuth!==s.prototype.fetchWithAuth||this.fetchWithTimeout!==s.prototype.fetchWithTimeout)throw new I.OpenAIError("X.509 workload identity does not support overridden fetch dispatch hooks.")}if(m&&B)throw new I.OpenAIError("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!(D||m||y||B))throw new I.OpenAIError("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!$.dangerouslyAllowBrowser&&fe())throw new I.OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");this.baseURL=$.baseURL,d.__classPrivateFieldSet(this,l,void 0!==h||g,"f"),this.timeout=$.timeout??s.DEFAULT_TIMEOUT,this.logger=$.logger??console;const j="warn";this.logLevel=j,this.logLevel=(0,he.parseLogLevel)($.logLevel,"ClientOptions.logLevel",this)??(0,he.parseLogLevel)((0,ue.readEnv)("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??j,this.fetchOptions=$.fetchOptions,this.maxRetries=$.maxRetries??2,this.fetch=$.fetch??A.getDefaultFetch(),d.__classPrivateFieldSet(this,i,v.FallbackEncoder,"f");const H=f||t?void 0:(0,ue.readEnv)("OPENAI_CUSTOM_HEADERS");if(H){const e={};for(const t of H.split("\n")){const r=t.indexOf(":");r>=0&&(e[t.substring(0,r).trim()]=t.substring(r+1).trim())}$.defaultHeaders=(0,ce.buildHeaders)([e,$.defaultHeaders])}if(this._options=$,this._provider=D,L){const e=new O.X509WorkloadIdentityAuth(L,x,b,w);this._workloadIdentityAuth=e,d.__classPrivateFieldSet(this,o,e,"f"),d.__classPrivateFieldSet(this,a,t,"f"),d.__classPrivateFieldSet(this,c,e.fetch(),"f"),this.fetch=d.__classPrivateFieldGet(this,c,"f"),(0,R.markApprovedX509Client)(this)}else M.legacy&&(this._workloadIdentityAuth=new P.WorkloadIdentityAuth(M.legacy,this.fetch));this.apiKey="string"==typeof m?m:null,this.adminAPIKey=y,this.organization=b,this.project=w,this.webhookSecret=S}withOptions(e){const t=(0,E.resolveDataResidency)(e),r=d.__classPrivateFieldGet(this,o,"f"),n={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:d.__classPrivateFieldGet(this,o,"f")?void 0:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:r?.identitySnapshot()??this._options.workloadIdentity,x509Transport:this._options.x509Transport,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret},{credential:s,provider:i}=(0,C.prepareX509ClientClone)(n,e,d.__classPrivateFieldGet(this,a,"f"),void 0!==r);void 0!==t&&delete n.baseURL;const u={...n,...e,credential:s,provider:i,[pe]:d.__classPrivateFieldGet(this,l,"f")&&void 0===t&&!(0,p.hasOwn)(e,"baseURL")&&void 0===e.credential&&!i},h=new this.constructor(u);return i&&new URL(h.baseURL).origin!==new URL(this.baseURL).origin&&(Object.assign(h._options,{defaultHeaders:e.defaultHeaders,defaultQuery:e.defaultQuery,fetchOptions:e.fetchOptions,fetch:e.fetch}),h.fetchOptions=e.fetchOptions,h.fetch=e.fetch??A.getDefaultFetch(),h.organization=e.organization??null,h.project=e.project??null),d.__classPrivateFieldGet(this,o,"f")&&d.__classPrivateFieldGet(h,o,"f")&&this.baseURL===h.baseURL&&d.__classPrivateFieldGet(this,o,"f").matches(d.__classPrivateFieldGet(h,o,"f"))&&(h._workloadIdentityAuth=d.__classPrivateFieldGet(this,o,"f"),d.__classPrivateFieldSet(h,o,d.__classPrivateFieldGet(this,o,"f"),"f"),d.__classPrivateFieldSet(h,c,d.__classPrivateFieldGet(this,c,"f"),"f")),h}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!e.get("authorization")&&!e.get("api-key")&&!(t.has("authorization")||t.has("api-key")||this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return(d.__classPrivateFieldGet(this,o,"f")??this._workloadIdentityAuth)instanceof O.X509WorkloadIdentityAuth&&t.adminAPIKeyAuth&&null!==this.adminAPIKey?await this.adminAPIKeyAuth(e):(0,ce.buildHeaders)([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){const t=d.__classPrivateFieldGet(this,o,"f")??this._workloadIdentityAuth;if(t){if(t instanceof O.X509WorkloadIdentityAuth){if(t===this._workloadIdentityAuth&&(this.fetchWithAuth!==s.prototype.fetchWithAuth||this.fetchWithTimeout!==s.prototype.fetchWithTimeout))throw new I.OpenAIError("X.509 workload identity does not support overridden fetch dispatch hooks.");const r=t.headerSnapshots();if(!O.X509WorkloadIdentityAuth.shouldAuthenticate(e,r.defaultHeaders,r.requestHeaders))return}const r=t instanceof O.X509WorkloadIdentityAuth?await t.getToken(e,{apiURL:t.requestAPIURL(),...t.headerSnapshots(),...t.requestSnapshot(),signal:t.effectiveSignal(),...t.tenantSnapshot()}):await t.getToken();return(0,ce.buildHeaders)([{Authorization:`Bearer ${r}`}])}if(null!=this.apiKey)return(0,ce.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(null!=this.adminAPIKey)return(0,ce.buildHeaders)([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return(0,b.stringifyQuery)(e)}getUserAgent(){return`${this.constructor.name}/JS ${w.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,f.uuid4)()}`}makeStatusError(e,t,r,n){const s=t&&"object"==typeof t&&null==t.error?{error:t}:t;return I.APIError.generate(e,s,r,n)}async _callApiKey(e){if(this._provider)return e?.(this.apiKey),!1;const t=this._options.apiKey;if("function"!=typeof t)return e?.(this.apiKey),!1;let r;try{r=await t()}catch(e){if(e instanceof I.OpenAIError)throw e;throw new I.OpenAIError(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if("string"!=typeof r||!r)throw new I.OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,e?.(this.apiKey),!0}buildURL(e,t,r){const s=!d.__classPrivateFieldGet(this,n,"m",h).call(this)&&r||this.baseURL,i=(0,p.isAbsoluteURL)(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(0,de.isEmptyObj)(o)&&(0,de.isEmptyObj)(a)||(t={...a,...o,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){this._provider||(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(r=>({method:e,path:t,...r})))}request(e,t=null){const r=d.__classPrivateFieldGet(this,o,"f")??this._workloadIdentityAuth,n=r instanceof O.X509WorkloadIdentityAuth?Promise.resolve(e).then(e=>r.runRequest(()=>this.makeRequest(e,t,void 0),this)):this.makeRequest(e,t,void 0);return this.responsePromise(n)}responsePromise(e,t=(e,t)=>this.parseResponseWithTimeout(e,t)){const r=new N.APIPromise(this,e,(e,r)=>{const n=d.__classPrivateFieldGet(this,u,"f").get(r.controller)?.continueRequest;return n?n(()=>t(e,r)):t(e,r)});return r.withResponse=async()=>{const t=await r,{response:n}=await e;return{data:t,response:n,request_id:n.headers.get("x-request-id")}},r._thenUnwrap=r=>this.responsePromise(e,async(e,n)=>(0,m.addRequestID)(r(await t(e,n),n),n.response)),r}async parseResponseWithTimeout(e,t){if(t.options.stream||t.options.__binaryResponse||204===t.response.status||"0"===t.response.headers.get("content-length"))return(0,m.defaultParseResponse)(e,t);for(;;){const r=d.__classPrivateFieldGet(this,u,"f").get(t.controller),n=r?.timeout??t.options.timeout??this.timeout,s=r?.authentication,i=s?t.controller.signal:t.options.signal,o=()=>s&&i?this._makeUserAbortError(i):new I.APIUserAbortError;let a,c,l;try{a=s?.remainingTimeout(t.options,n)??Math.max(0,t.startTime+n-Date.now())}catch(e){const r=i?.aborted?o():void 0;throw t.controller.abort(),A.CancelReadableStream(t.response.body).catch(()=>{}),r??e}let h=!1;try{if(i?.aborted&&"runTools"!==r?.helperMethod)throw o();const n=new Promise((e,r)=>{c=setTimeout(()=>{h=!0,t.controller.abort(),r(new I.APIConnectionTimeoutError)},a),i&&(l=()=>{h||r(o())},i.addEventListener("abort",l,{once:!0}))});return await Promise.race([(0,m.defaultParseResponse)(e,t),n])}catch(e){if(i?.aborted&&!h)throw o();if(!h){if(s&&e instanceof SyntaxError)throw new SyntaxError("X.509 workload identity API response contains invalid JSON.");if(s&&!(e instanceof I.OpenAIError))throw new I.APIConnectionError({message:"X.509 workload identity API response body could not be read."});throw e}const n=r?.retriesRemaining??0;if(!n||r?.hasStreamingBody||t.options.__metadata?.hasStreamingBody||globalThis.ReadableStream&&t.options.body instanceof globalThis.ReadableStream||"object"==typeof t.options.body&&null!==t.options.body&&(Symbol.asyncIterator in t.options.body||Symbol.iterator in t.options.body&&"next"in t.options.body&&"function"==typeof t.options.body.next))throw new I.APIConnectionTimeoutError;void 0!==c&&clearTimeout(c),l&&i?.removeEventListener("abort",l),l=void 0;const a=await this.retryRequest(t.options,n,t.retryOfRequestLogID??t.requestLogID);Object.assign(t,a)}finally{void 0!==c&&clearTimeout(c),l&&i?.removeEventListener("abort",l)}}}async readX509ResponseError(e,t,r,n,s){const i=new AbortController,o=n.signal;let a=!1;const c=()=>i.abort(o.reason);o.addEventListener("abort",c,{once:!0}),o.aborted&&c();try{const n=s.remainingTimeout(t,r),a=s.waitForRetry(n,i.signal).then(()=>{throw new I.APIConnectionTimeoutError}),c=await Promise.race([e.text().catch(()=>"X.509 workload identity API response body could not be read."),a]);if(o.aborted)throw this._makeUserAbortError(o);return c}catch(t){if(t instanceof I.APIConnectionTimeoutError&&(a=!o.aborted,n.abort(),A.CancelReadableStream(e.body).catch(()=>{})),o.aborted&&!a)throw this._makeUserAbortError(o);throw t}finally{o.removeEventListener("abort",c),i.abort()}}async makeRequest(e,t,r){const n=await e,i=n.maxRetries??this.maxRetries;null==t&&(t=i);const a=d.__classPrivateFieldGet(this,o,"f");let c;a?.beginRequestPreparation(),await this.prepareOptions(n),a?.beginRequestPlanning();try{const e=await this.buildRequest(n,{retryCount:i-t});if(c={req:e.req,url:e.url,timeout:e.timeout},a){(0,p.validatePositiveInteger)("timeout",c.timeout),a.authorizePlannedRequest(c.url,c.req,c.timeout),O.X509WorkloadIdentityAuth.isStreamingRequestBody(c.req.body)&&(n.__metadata={...n.__metadata,hasStreamingBody:!0}),await this.prepareRequest(c.req,{url:c.url,options:n}),await(this._provider?.prepareRequest?.(c.req,{url:c.url,options:n})),a.beginRequestPlanning(),a.authorizePlannedRequest(c.url,c.req,c.timeout,!0),O.X509WorkloadIdentityAuth.isStreamingRequestBody(c.req.body)&&(n.__metadata={...n.__metadata,hasStreamingBody:!0});const e=a.requestSnapshot().signal;if(e?.aborted||c.req.signal?.aborted)throw this._makeUserAbortError(e?.aborted?e:c.req.signal);a.setEffectiveSignal(c.req.signal||e?me(c.req.signal??e,e).signal:void 0),a.beginRequestNetwork();const t=n.__security??{bearerAuth:!0},r=await this.authHeaders(n,t),s=a.headerSnapshots(),i=(0,ce.buildHeaders)([s.defaultHeaders,s.requestHeaders]);for(const[e,t]of r?.values??[])i.nulls.has(e)||c.req.headers.has(e)||c.req.headers.set(e,t);this.validateHeaders((0,ce.buildHeaders)([i,c.req.headers]),t)}}catch(e){if(a?.retireRequestBody(),a&&t&&!n.__metadata?.hasStreamingBody&&O.X509WorkloadIdentityAuth.isRetryableFailure(e))return await this.retryRequest(n,t,r??"x509-token-exchange",O.X509WorkloadIdentityAuth.retryHeaders(e));throw e}const{req:l,url:h}=c,f=a?Math.min(c.timeout,a.requestSnapshot().timeout):c.timeout;a?.bindRequest(n,l,this.adminAPIKey);let _=!0===n.__metadata?.hasStreamingBody;a||(await this.prepareRequest(l,{url:h,options:n}),await(this._provider?.prepareRequest?.(l,{url:h,options:n}))),a?.adoptRequestHeaders(l),a&&O.X509WorkloadIdentityAuth.isStreamingRequestBody(l.body)&&(_=!0);const m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),y=void 0===r?"":`, retryOf: ${r}`,v=a?.requestStartedAt(n)??Date.now();(0,he.loggerFor)(this).debug(`[${m}] sending request`,(0,he.formatRequestDetails)({retryOfRequestLogID:r,method:n.method,url:h,options:a?{body:l.body,...a.requestSnapshot()}:n,headers:l.headers}));const b=a?a.requestSnapshot().signal:n.signal;if(b?.aborted||l.signal?.aborted)throw this._makeUserAbortError(b?.aborted?b:l.signal);const w=n.__security??{bearerAuth:!0},E=a||this.fetchWithTimeout===s.prototype.fetchWithTimeout?me(l.signal??(a?b:void 0),a?b:void 0):new AbortController,S=a?.remainingTimeout(n,f)??f,P=a?s.prototype.fetchWithAuth:this.fetchWithAuth;a?.releaseRequestBody(l.body);const k=await P.call(this,h,l,S,E,w).catch(g.castToError),C=Date.now();if(k instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(b?.aborted||l.signal?.aborted)throw this._makeUserAbortError(b?.aborted?b:l.signal);const s=(0,g.isAbortError)(k)||/timed? ?out/i.test(String(k)+("cause"in k?String(k.cause):""));if(t&&!_&&(!a||(0,R.isTransientX509ConnectionError)(k)))return(0,he.loggerFor)(this).info(`[${m}] connection ${s?"timed out":"failed"} - ${e}`),(0,he.loggerFor)(this).debug(`[${m}] connection ${s?"timed out":"failed"} (${e})`,(0,he.formatRequestDetails)({retryOfRequestLogID:r,url:h,durationMs:C-v,message:a?"X.509 workload identity API connection failed.":k.message})),this.retryRequest(n,t,r??m);const i=_?"error; streaming body cannot be retried":"error; no more retries left";if((0,he.loggerFor)(this).info(`[${m}] connection ${s?"timed out":"failed"} - ${i}`),(0,he.loggerFor)(this).debug(`[${m}] connection ${s?"timed out":"failed"} (${i})`,(0,he.formatRequestDetails)({retryOfRequestLogID:r,url:h,durationMs:C-v,message:a?"X.509 workload identity API connection failed.":k.message})),k instanceof B.OAuthError||k instanceof B.SubjectTokenProviderError)throw k;if(s){const e="cause"in k?k.cause:void 0,t="object"==typeof e&&null!==e&&"code"in e&&"UND_ERR_HEADERS_TIMEOUT"===e.code?new I.APIConnectionTimeoutError({message:"Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout."}):new I.APIConnectionTimeoutError;if(a)throw new I.APIConnectionTimeoutError;throw Object.assign(t,{cause:k})}if(a)throw new I.APIConnectionError({message:"X.509 workload identity API connection failed."});throw new I.APIConnectionError({message:ye(k),cause:k})}const x=`[${m}${y}${[...k.headers.entries()].filter(([e])=>"x-request-id"===e).map(([e,t])=>", "+e+": "+JSON.stringify(t)).join("")}] ${l.method} ${(0,he.redactURL)(h)} ${k.ok?"succeeded":"failed"} with status ${k.status} in ${C-v}ms`;if(!k.ok){const e=401===k.status&&a&&w.bearerAuth&&a.usedWorkloadToken(n);if(e&&a.invalidateToken(),401===k.status&&(a||this._workloadIdentityAuth)&&w.bearerAuth&&(!a||a.usedWorkloadToken(n))&&(!a||t>0)&&!_&&!n.__metadata?.workloadIdentityTokenRefreshed){a?A.CancelReadableStream(k.body).catch(()=>{}):(await A.CancelReadableStream(k.body),this._workloadIdentityAuth?.invalidateToken());const e={...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(e,a?t-1:t,r??m)}const s=(!e||!n.__metadata?.workloadIdentityTokenRefreshed)&&await this.shouldRetry(k);if(t&&s&&!_){const e=`retrying, ${t} attempts remaining`;return a?A.CancelReadableStream(k.body).catch(()=>{}):await A.CancelReadableStream(k.body),(0,he.loggerFor)(this).info(`${x} - ${e}`),(0,he.loggerFor)(this).debug(`[${m}] response error (${e})`,(0,he.formatRequestDetails)({retryOfRequestLogID:r,url:k.url,status:k.status,headers:k.headers,durationMs:C-v})),this.retryRequest(n,t,r??m,k.headers)}const i=s?_?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";(0,he.loggerFor)(this).info(`${x} - ${i}`);const o=a?await this.readX509ResponseError(k,n,f,E,a):await k.text().catch(e=>(0,g.castToError)(e).message),c=(0,p.safeJSON)(o),l=c?void 0:o;throw(0,he.loggerFor)(this).debug(`[${m}] response error (${i})`,(0,he.formatRequestDetails)({retryOfRequestLogID:r,url:k.url,status:k.status,headers:k.headers,message:l,durationMs:Date.now()-v})),this.makeStatusError(k.status,c,l,k.headers)}(0,he.loggerFor)(this).info(x),(0,he.loggerFor)(this).debug(`[${m}] response start`,(0,he.formatRequestDetails)({retryOfRequestLogID:r,url:k.url,status:k.status,headers:k.headers,durationMs:C-v}));const T=a?.continuation();return a?.releaseRequestCredentials(),d.__classPrivateFieldGet(this,u,"f").set(E,{timeout:f,retriesRemaining:t,hasStreamingBody:_,...a?{authentication:a}:{},helperMethod:n.__metadata?.helperMethod,...T?{continueRequest:T}:{}}),{response:k,options:n,controller:E,requestLogID:m,retryOfRequestLogID:r,startTime:v}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(t=>({method:"get",path:e,...t})):{method:"get",path:e,...r})}requestAPIList(e,t){const r=d.__classPrivateFieldGet(this,o,"f")??this._workloadIdentityAuth,n=r instanceof O.X509WorkloadIdentityAuth?Promise.resolve(t).then(e=>r.runRequest(()=>this.makeRequest(e,null,void 0),this)):this.makeRequest(t,null,void 0),s=new S.PagePromise(this,n,e),i=this.responsePromise(n,async(t,r)=>{const n=await this.parseResponseWithTimeout(t,r);return new e(t,r.response,n,r.options)});return s.then=i.then.bind(i),s.catch=i.catch.bind(i),s.finally=i.finally.bind(i),s.withResponse=i.withResponse.bind(i),s._thenUnwrap=i._thenUnwrap.bind(i),s}async fetchWithAuth(e,t,r,n,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!d.__classPrivateFieldGet(this,c,"f")&&i.bearerAuth){const e=t.headers;if("Bearer workload-identity-auth"===e.get("Authorization")){const t=await this._workloadIdentityAuth.getToken();e.set("Authorization",`Bearer ${t}`)}}const o=d.__classPrivateFieldGet(this,c,"f")?s.prototype.fetchWithTimeout:this.fetchWithTimeout;return await o.call(this,e,t,r,n)}async fetchWithTimeout(e,t,r,n){const{signal:s,method:i,...o}=t||{},a=this._makeAbort(n),l=!!s&&ge.get(n)===s;s&&!l&&s.addEventListener("abort",a,{once:!0});const u=setTimeout(a,r),h=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||"object"==typeof o.body&&null!==o.body&&Symbol.asyncIterator in o.body,f={signal:n.signal,...h?{duplex:"half"}:{},method:"GET",...o};i&&(f.method=i.toUpperCase());try{return await(d.__classPrivateFieldGet(this,c,"f")??this.fetch).call(void 0,e,f)}catch(e){throw s&&!l&&s.removeEventListener("abort",a),e}finally{clearTimeout(u)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||e.status>=500)}async retryRequest(e,t,r,n){let s;const i=n?.get("retry-after-ms");if(i){const e=parseFloat(i);Number.isNaN(e)||(s=e)}const a=n?.get("retry-after");if(a&&void 0===s){const e=parseFloat(a);s=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(void 0===s||!Number.isFinite(s)||s<0||s>6e4){const r=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,r)}const c=d.__classPrivateFieldGet(this,o,"f");if(c&&s>=c.remainingTimeout(e,c.requestSnapshot().timeout))throw new I.APIConnectionTimeoutError;return c?await c.waitForRetry(s,c.effectiveSignal()):await(0,_.sleep)(s),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){if(d.__classPrivateFieldGet(this,o,"f")&&!d.__classPrivateFieldGet(this,o,"f").inRequest(this)){const r=d.__classPrivateFieldGet(this,o,"f");return await r.runRequest(async()=>{const n=await s.prototype.buildRequest.call(this,e,{retryCount:t});return r.releaseRequestBody(n.req.body),n},this)}const r={...e},n=d.__classPrivateFieldGet(this,o,"f"),i=n?.snapshotTenant(this.organization,this.project),a=n?.snapshotHeaders(this._options.defaultHeaders,r.headers);a&&(r.headers=a.requestHeaders);const c=n?(0,O.snapshotX509RequestOptions)(this.fetchOptions):void 0,l=n?(0,O.snapshotX509RequestOptions)(r.fetchOptions):void 0,{method:u,path:h,query:f,defaultBaseURL:_}=r,g=this.buildURL(h,f,_);n?.snapshotAPIURL(g);const m="timeout"in r;if(m&&(0,p.validatePositiveInteger)("timeout",r.timeout),r.timeout=r.timeout??this.timeout,n&&l&&n.snapshotRequest(r.signal,r.timeout,l),n){const e=n.requestSnapshot();r.timeout=e.timeout,void 0===e.signal?delete r.signal:r.signal=e.signal}const{bodyHeaders:y,body:A,isStreamingBody:v}=this.buildBody({options:r});return v&&(e.__metadata={...e.__metadata,hasStreamingBody:!0},n?.ownRequestBody(A,r.body)),{req:{method:u,headers:await this.buildHeaders({options:e,method:u,bodyHeaders:y,retryCount:t,x509Headers:a,x509Timeout:m?r.timeout:void 0,x509Tenant:i}),...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&A instanceof globalThis.ReadableStream&&{duplex:"half"},...A&&{body:A},...(n?c:this.fetchOptions)??{},...(n?l:r.fetchOptions)??{}},url:g,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n,x509Headers:s,x509Timeout:i,x509Tenant:a}){let c={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),c[this.idempotencyHeader]=e.idempotencyKey);const l=e.__metadata?.helperMethod,u=s?i:e.timeout,h=(0,ce.buildHeaders)([c,{Accept:"application/json",...fe()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(n),...u?{"X-Stainless-Timeout":String(Math.trunc(u/1e3))}:{},...(0,y.getPlatformHeaders)(),..."string"==typeof l?{"X-Stainless-Helper-Method":l}:{},"OpenAI-Organization":a?a.organization:this.organization,"OpenAI-Project":a?a.project:this.project},this._provider||d.__classPrivateFieldGet(this,o,"f")?.isPlanningRequest()?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),s?.defaultHeaders??this._options.defaultHeaders,r,s?.requestHeaders??e.headers]);return this._provider||d.__classPrivateFieldGet(this,o,"f")?.isPlanningRequest()||this.validateHeaders(h,e.__security??{bearerAuth:!0}),h.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){const t=new I.APIUserAbortError;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t}buildBody({options:e}){const{body:t,headers:r}=e;if(!t)return void 0===t&&"body"in e?{...d.__classPrivateFieldGet(this,i,"f").call(this,{body:t,headers:(0,ce.buildHeaders)([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};const n=(0,ce.buildHeaders)([r]),s=void 0!==globalThis.ReadableStream&&t instanceof globalThis.ReadableStream,o=!s&&("string"==typeof t||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||void 0!==globalThis.Blob&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||"string"==typeof t&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||s?{bodyHeaders:void 0,body:t,isStreamingBody:!o}:"object"==typeof t&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&"function"==typeof t.next)?{bodyHeaders:void 0,body:A.ReadableStreamFrom(t),isStreamingBody:!0}:"object"==typeof t&&"application/x-www-form-urlencoded"===n.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...d.__classPrivateFieldGet(this,i,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}}t.OpenAI=_e,s=_e,i=new WeakMap,o=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,n=new WeakSet,h=function(){return d.__classPrivateFieldGet(this,l,"f")||void 0!==this._provider||"https://api.openai.com/v1"!==this.baseURL},_e.OpenAI=s,_e.DEFAULT_TIMEOUT=6e5,_e.OpenAIError=I.OpenAIError,_e.APIError=I.APIError,_e.APIConnectionError=I.APIConnectionError,_e.APIConnectionTimeoutError=I.APIConnectionTimeoutError,_e.APIUserAbortError=I.APIUserAbortError,_e.NotFoundError=I.NotFoundError,_e.ConflictError=I.ConflictError,_e.RateLimitError=I.RateLimitError,_e.BadRequestError=I.BadRequestError,_e.AuthenticationError=I.AuthenticationError,_e.InternalServerError=I.InternalServerError,_e.PermissionDeniedError=I.PermissionDeniedError,_e.UnprocessableEntityError=I.UnprocessableEntityError,_e.InvalidWebhookSignatureError=I.InvalidWebhookSignatureError,_e.toFile=x.toFile,_e.toStreamingFile=x.toStreamingFile,_e.Completions=M.Completions,_e.Chat=K.Chat,_e.Embeddings=U.Embeddings,_e.Files=D.Files,_e.Images=$.Images,_e.ContentProvenanceChecks=L.ContentProvenanceChecks,_e.Audio=q.Audio,_e.Moderations=H.Moderations,_e.Models=j.Models,_e.FineTuning=J.FineTuning,_e.Graders=V.Graders,_e.VectorStores=ie.VectorStores,_e.Safety=re.Safety,_e.Webhooks=oe.Webhooks,_e.Beta=W.Beta,_e.Batches=F.Batches,_e.Uploads=se.Uploads,_e.Admin=Q.Admin,_e.Responses=te.Responses,_e.Live=Z.Live,_e.Realtime=ee.Realtime,_e.Conversations=z.Conversations,_e.Evals=Y.Evals,_e.Containers=X.Containers,_e.Skills=ne.Skills,_e.Videos=G.Videos;const ge=new WeakMap;function me(e,t){const r=new AbortController;if(!e)return r;const n=globalThis.AbortSignal;if("function"!=typeof n?.any||!(e instanceof n))return r;try{const s=[r.signal,e];t&&t!==e&&s.push(t);const i=n.any(s);Object.defineProperty(r,"signal",{value:i,configurable:!0}),ge.set(r,e)}catch{}return r}function ye(e){if(function(e){let t=e;for(let e=0;e<8&&t&&"object"==typeof t;e++){const e=t;if("UND_ERR_INVALID_ARG"===e.code&&"string"==typeof e.message&&e.message.includes("invalid onRequestStart method"))return!0;t=e.cause}return!1}(e))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}},398(e,t,r){"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.APIPromise=void 0;const s=r(6316),i=r(907);class o extends Promise{constructor(e,t,r=i.defaultParseResponse){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,n.set(this,void 0),s.__classPrivateFieldSet(this,n,e,"f")}_thenUnwrap(e){return new o(s.__classPrivateFieldGet(this,n,"f"),this.responsePromise,async(t,r)=>(0,i.addRequestID)(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(s.__classPrivateFieldGet(this,n,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}t.APIPromise=o,n=new WeakMap},144(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SubjectTokenProviderError=t.OAuthError=t.InvalidWebhookSignatureError=t.ContentFilterFinishReasonError=t.LengthFinishReasonError=t.InternalServerError=t.RateLimitError=t.UnprocessableEntityError=t.ConflictError=t.NotFoundError=t.PermissionDeniedError=t.AuthenticationError=t.BadRequestError=t.APIConnectionTimeoutError=t.APIConnectionError=t.APIUserAbortError=t.APIError=t.OpenAIError=void 0;const n=r(7545);class s extends Error{}t.OpenAIError=s;class i extends s{constructor(e,t,r,n){super(`${i.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;const s=t;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,t,r){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new o({message:r,cause:(0,n.castToError)(t)});const _=t?.error;return 400===e?new a(e,_,r,s):401===e?new c(e,_,r,s):403===e?new l(e,_,r,s):404===e?new u(e,_,r,s):409===e?new h(e,_,r,s):422===e?new d(e,_,r,s):429===e?new f(e,_,r,s):e>=500?new p(e,_,r,s):new i(e,_,r,s)}}t.APIError=i,t.APIUserAbortError=class extends i{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}};class o extends i{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}t.APIConnectionError=o,t.APIConnectionTimeoutError=class extends o{constructor({message:e}={}){super({message:e??"Request timed out."})}};class a extends i{}t.BadRequestError=a;class c extends i{}t.AuthenticationError=c;class l extends i{}t.PermissionDeniedError=l;class u extends i{}t.NotFoundError=u;class h extends i{}t.ConflictError=h;class d extends i{}t.UnprocessableEntityError=d;class f extends i{}t.RateLimitError=f;class p extends i{}t.InternalServerError=p,t.LengthFinishReasonError=class extends s{constructor(){super("Could not parse response content as the length limit was reached")}},t.ContentFilterFinishReasonError=class extends s{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};class _ extends Error{constructor(e){super(e)}}t.InvalidWebhookSignatureError=_,t.OAuthError=class extends i{constructor(e,t,r){let n,s="OAuth2 authentication error";if(t&&"object"==typeof t){const e=t;n=e.error;const r=e.error_description;r&&"string"==typeof r?s=r:n&&(s=n)}super(e,t,s,r),this.error_code=n}},t.SubjectTokenProviderError=class extends s{constructor(e,t,r){super(e),this.provider=t,this.cause=r}}},3604(e,t,r){"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.TokenPage=t.NextCursorPage=t.ConversationCursorPage=t.CursorPage=t.Page=t.PagePromise=t.AbstractPage=void 0;const s=r(6316),i=r(144),o=r(907),a=r(398),c=r(8874);class l{constructor(e,t,r,i){n.set(this,void 0),s.__classPrivateFieldSet(this,n,e,"f"),this.options=i,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new i.OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await s.__classPrivateFieldGet(this,n,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(n=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}t.AbstractPage=l;class u extends a.APIPromise{constructor(e,t,r){super(e,t,async(e,t)=>new r(e,t.response,await(0,o.defaultParseResponse)(e,t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}t.PagePromise=u,t.Page=class extends l{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},t.CursorPage=class extends l{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...(0,c.maybeObj)(this.options.query),after:t}}:null}},t.ConversationCursorPage=class extends l{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...(0,c.maybeObj)(this.options.query),after:e}}:null}},t.NextCursorPage=class extends l{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&null!=this.nextPageRequestOptions()}nextPageRequestOptions(){const e=this.next;return e?{...this.options,query:{...(0,c.maybeObj)(this.options.query),after:e}}:null}},t.TokenPage=class extends l{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&null!=this.nextPageRequestOptions()}nextPageRequestOptions(){const e=this.next;return e?{...this.options,query:{...(0,c.maybeObj)(this.options.query),page:e}}:null}}},2596(e,t){"use strict";t.APIResource=void 0,t.APIResource=class{constructor(e){this._client=e}}},7542(e,t,r){"use strict";var n,s,i,o;Object.defineProperty(t,"__esModule",{value:!0}),t.Stream=void 0,t._iterSSEMessages=g;const a=r(6316),c=r(144),l=r(6786),u=r(2736),h=r(7545),d=r(4545),f=r(6048);function p(){let e=[],t=0,r=!1;return{get length(){return e.length-t},get canceled(){return r},enqueue(t){r||e.push(t)},dequeue(){if(t===e.length)return;const r=e[t];return e[t]=void 0,t+=1,t===e.length?(e=[],t=0):t>=1024&&2*t>=e.length&&(e=e.slice(t),t=0),r},cancel(){r=!0,e.length=0,t=0}}}class _{constructor(e,t,r){n.add(this),s.set(this,void 0),i.set(this,!1),this.iterator=e,this.controller=t,a.__classPrivateFieldSet(this,s,r,"f")}static fromSSEResponse(e,t,r,n){let s=!1;const i=r?(0,f.loggerFor)(r):console;return new _(async function*(){if(s)throw new c.OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let r=!1,o=!1;const a=g(e,t),l=a.return.bind(a);a.return=e=>(o||t.abort(),l(e));try{for await(const t of a){if("[DONE]"===t.data){o=!0;break}if(null!==t.event&&t.event.startsWith("thread.")){let e;try{e=JSON.parse(t.data)}catch{throw i.error("Could not parse message into JSON:"),i.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}yield{event:t.event,data:e}}else{let r;try{r=JSON.parse(t.data)}catch{throw i.error("Could not parse message into JSON:"),i.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}if("error"===t.event)throw new c.APIError(void 0,r?.error??r,void 0,e.headers);if(r&&r.error)throw new c.APIError(void 0,r.error,void 0,e.headers);yield n?{event:t.event,data:r}:r}}r=!0}catch(e){if(o||!((u=e)instanceof c.APIError)&&(0,h.isAbortError)(u)||t.signal.aborted&&e===t.signal.reason)return;throw e}finally{r||t.abort()}var u},t,r)}static fromReadableStream(e,t,r){let n=!1;return new _(async function*(){if(n)throw new c.OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let r=!1;try{for await(const r of async function*(){const r=new u.LineDecoder,n=e.getReader();let s,i=!1;const o=()=>{s??(s=n.cancel()),s.catch(()=>{})};t.signal.addEventListener("abort",o,{once:!0});try{if(t.signal.aborted)return void o();for(;;){const{value:e,done:s}=await n.read();if(s){i=!0;break}if(t.signal.aborted)return;for(const n of r.decode(e)){if(t.signal.aborted)return;yield n}}if(t.signal.aborted)return;for(const e of r.flush()){if(t.signal.aborted)return;yield e}}finally{t.signal.removeEventListener("abort",o),i||o(),n.releaseLock()}}())if(r){let e;try{e=JSON.parse(r)}catch(e){if(e instanceof SyntaxError)throw new SyntaxError("Error reading response: malformed newline-delimited JSON.");throw e}yield e}r=!0}catch(e){if(t.signal.aborted||(0,h.isAbortError)(e))return;throw e}finally{r||t.abort()}},t,r)}[(s=new WeakMap,i=new WeakMap,n=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}tee(){const{controller:e}=this,t=p(),r=p(),c=this.iterator(),l=s=>({next:()=>{if(s.canceled)return Promise.resolve({value:void 0,done:!0});if(0===s.length){const e=c.next();t.enqueue(e),r.enqueue(e)}return s.dequeue()},return:async()=>(s.canceled||(s.cancel(),t.canceled&&r.canceled&&await a.__classPrivateFieldGet(this,n,"m",o).call(this,c,e)),{value:void 0,done:!0})}),u=t=>{const r=new _(()=>l(t),e,a.__classPrivateFieldGet(this,s,"f"));return a.__classPrivateFieldSet(r,i,!0,"f"),r};return[u(t),u(r)]}toReadableStream(){const{controller:e}=this;let t;return(0,l.makeReadableStream)({start:async()=>{t=this[Symbol.asyncIterator]()},async pull(e){try{const{value:r,done:n}=await t.next();if(n)return e.close();const s=(0,d.encodeUTF8)(JSON.stringify(r)+"\n");e.enqueue(s)}catch(t){e.error(t)}},cancel:()=>a.__classPrivateFieldGet(this,n,"m",o).call(this,t,e)})}}async function*g(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new c.OpenAIError("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new c.OpenAIError("Attempted to iterate over a response with no body")}const r=new m,n=new u.LineDecoder,{signal:s}=t,i=function(e,t){const r="function"==typeof e.getReader?e.getReader():void 0,n=r?{next:()=>r.read(),return:()=>r.cancel()}:(0,l.ReadableStreamToAsyncIterable)(e)[Symbol.asyncIterator](),s={value:void 0,done:!0};let i,o,a=!1,c=!1;const u=()=>new Promise(e=>{o=e}),d=()=>{if(c||a)return i;c=!0;try{i=Promise.resolve(n.return?.())}catch(e){i=Promise.reject(e)}return i.catch(()=>{}),i},f=()=>{queueMicrotask(()=>{o?.(),d()})};return{iterator:{async next(){if(t.aborted)return s;const e=u().then(()=>s);try{const r=await Promise.race([n.next(),e]);return t.aborted?s:r.done?(a=!0,s):{value:r.value,done:!1}}catch(e){if(t.aborted&&((0,h.isAbortError)(e)||e===t.reason))return s;throw e}finally{o=void 0}},async return(){const e=d();if(e&&!t.aborted){const r=u();try{t.aborted||await Promise.race([e,r])}finally{o=void 0}}return s},[Symbol.asyncIterator](){return this}},start(){t.addEventListener("abort",f,{once:!0}),t.aborted&&f()},async cleanup(e){let n;try{t.removeEventListener("abort",f)}catch(e){n=e}if(!a){const r=d();if(r&&!e&&!t.aborted)try{await r}catch(e){n??(n=e)}}if(r)try{r.releaseLock()}catch(e){n??(n=e)}if(void 0!==n&&!e&&!t.aborted)throw n}}}(e.body,s);let o=!1;try{i.start();for await(const e of async function*(e){let t=new Uint8Array,r=0,n=0,s=0;for await(const i of e){if(null==i)continue;let e,o;if(e=i instanceof ArrayBuffer?new Uint8Array(i):"string"==typeof i?(0,d.encodeUTF8)(i):i,n+e.length>t.length){const i=n-r;if(r>=t.length/2&&i+e.length<=t.length)t.copyWithin(0,r,n);else{const s=new Uint8Array(Math.max(2*t.length,i+e.length));s.set(t.subarray(r,n)),t=s}s-=r,r=0,n=i}for(t.set(e,n),n+=e.length;-1!==(o=(0,u.findDoubleNewlineIndex)(t.subarray(s,n)));)o+=s,yield t.slice(r,o),r=o,s=r;s=Math.max(r,n-3)}n>r&&(yield t.slice(r,n))}(i.iterator)){if(s.aborted)return;for(const t of n.decode(e)){if(s.aborted)return;const e=r.decode(t);e&&(yield e)}}if(s.aborted)return;for(const e of n.flush()){if(s.aborted)return;const t=r.decode(e);t&&(yield t)}}catch(e){if(o=!0,!s.aborted||!(0,h.isAbortError)(e)&&e!==s.reason)throw e}finally{await i.cleanup(o)}}t.Stream=_,o=async function(e,t){const r=e.return;r&&(a.__classPrivateFieldGet(this,i,"f")||t.abort(),await Reflect.apply(r,e,[]))};class m{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.slice(0,-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;const[t,,r]=function(e){const t=e.indexOf(":");return-1!==t?[e.slice(0,t),":",e.slice(t+1)]:[e,"",""]}(e);let n=r;return n.startsWith(" ")&&(n=n.slice(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}},7692(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toFile=t.toStreamingFile=void 0;var n=r(1598);Object.defineProperty(t,"toStreamingFile",{enumerable:!0,get:function(){return n.toStreamingFile}});var s=r(6854);Object.defineProperty(t,"toFile",{enumerable:!0,get:function(){return s.toFile}})},2154(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(6316).__exportStar(r(144),t)},7032(e,t,r){"use strict";t=e.exports=function(...e){return Reflect.construct(t.default,e,new.target||t.default)},Object.defineProperty(t,"__esModule",{value:!0}),t.BedrockOpenAI=t.AzureOpenAI=t.SubjectTokenProviderError=t.OAuthError=t.InvalidWebhookSignatureError=t.UnprocessableEntityError=t.PermissionDeniedError=t.InternalServerError=t.AuthenticationError=t.BadRequestError=t.RateLimitError=t.ConflictError=t.NotFoundError=t.APIUserAbortError=t.APIConnectionTimeoutError=t.APIConnectionError=t.APIError=t.OpenAIError=t.PagePromise=t.OpenAI=t.APIPromise=t.toStreamingFile=t.toFile=t.default=void 0;var n=r(9393);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n.OpenAI}});var s=r(7692);Object.defineProperty(t,"toFile",{enumerable:!0,get:function(){return s.toFile}}),Object.defineProperty(t,"toStreamingFile",{enumerable:!0,get:function(){return s.toStreamingFile}});var i=r(398);Object.defineProperty(t,"APIPromise",{enumerable:!0,get:function(){return i.APIPromise}});var o=r(9393);Object.defineProperty(t,"OpenAI",{enumerable:!0,get:function(){return o.OpenAI}});var a=r(3604);Object.defineProperty(t,"PagePromise",{enumerable:!0,get:function(){return a.PagePromise}});var c=r(144);Object.defineProperty(t,"OpenAIError",{enumerable:!0,get:function(){return c.OpenAIError}}),Object.defineProperty(t,"APIError",{enumerable:!0,get:function(){return c.APIError}}),Object.defineProperty(t,"APIConnectionError",{enumerable:!0,get:function(){return c.APIConnectionError}}),Object.defineProperty(t,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return c.APIConnectionTimeoutError}}),Object.defineProperty(t,"APIUserAbortError",{enumerable:!0,get:function(){return c.APIUserAbortError}}),Object.defineProperty(t,"NotFoundError",{enumerable:!0,get:function(){return c.NotFoundError}}),Object.defineProperty(t,"ConflictError",{enumerable:!0,get:function(){return c.ConflictError}}),Object.defineProperty(t,"RateLimitError",{enumerable:!0,get:function(){return c.RateLimitError}}),Object.defineProperty(t,"BadRequestError",{enumerable:!0,get:function(){return c.BadRequestError}}),Object.defineProperty(t,"AuthenticationError",{enumerable:!0,get:function(){return c.AuthenticationError}}),Object.defineProperty(t,"InternalServerError",{enumerable:!0,get:function(){return c.InternalServerError}}),Object.defineProperty(t,"PermissionDeniedError",{enumerable:!0,get:function(){return c.PermissionDeniedError}}),Object.defineProperty(t,"UnprocessableEntityError",{enumerable:!0,get:function(){return c.UnprocessableEntityError}}),Object.defineProperty(t,"InvalidWebhookSignatureError",{enumerable:!0,get:function(){return c.InvalidWebhookSignatureError}}),Object.defineProperty(t,"OAuthError",{enumerable:!0,get:function(){return c.OAuthError}}),Object.defineProperty(t,"SubjectTokenProviderError",{enumerable:!0,get:function(){return c.SubjectTokenProviderError}});var l=r(847);Object.defineProperty(t,"AzureOpenAI",{enumerable:!0,get:function(){return l.AzureOpenAI}});var u=r(3542);Object.defineProperty(t,"BedrockOpenAI",{enumerable:!0,get:function(){return u.BedrockOpenAI}}),Object.setPrototypeOf(t,t.default),t.prototype=t.default.prototype},8006(e,t,r){"use strict";t.isAssistantStreamValueExternallyMutable=g,t.markAssistantStreamValueExternallyMutable=m,t.defineAssistantStreamArrayEntry=y,t.assertSafeAssistantStreamDelta=w,t.accumulateAssistantStreamDelta=function(e,t,r=!1){w(t);const n=e,s=t,i=c(r&&!g(e));return _(n,s,i),b(n,s),l(i),e},t.createAssistantStreamArrayDeltaCommit=function(e,t,r,n=!0){w(t);const s=c(n&&!g(e));return p(e,t,r,s,_),()=>l(s)};const n=r(2154),s=r(4737);function i(e){switch(e){case"value":case"arguments":case"input":case"text":case"content":case"annotations":case"metadata":case"name":case"role":case"status":case"tool_calls":case"step_details":return e;default:return"unknown"}}const o=new WeakMap,a=new WeakSet;function c(e){return{arrays:new Map,cacheArrays:e,records:new WeakMap}}function l(e){for(const[t,r]of e.arrays)r.cacheable&&!a.has(t)?o.set(t,{length:r.length,ownEntryCount:r.ownEntryCount}):o.delete(t)}function u(e){return"string"==typeof e||"number"==typeof e}function h(e,t){return t.every(u)&&e.every(u)}function d(e,t,r){return t?r?.length===e.length?r.ownEntryCount:function(e){let t=0;for(const r of Object.keys(e)){const n=Number(r);Number.isSafeInteger(n)&&n>=0&&n<e.length&&String(n)===r&&(t+=1)}return t}(e):0}function f(e,t,r){const{index:s}=e;if("array"===t&&null==s)throw new Error("Expected array delta entry to have an `index` property");if("array"===t&&"number"!=typeof s)throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");if(!Number.isSafeInteger(s)||s<0||s>=r+1024||s>=65536){const e="number"==typeof s?s:"unknown";throw new n.OpenAIError(`Assistant stream delta contains an invalid ${t} index: ${e}`)}return s}function p(e,t,r,i,c){let l=i.arrays.get(e);if(!l){const t=i.cacheArrays&&!a.has(e),r=t?o.get(e):void 0;l={baselineLength:e.length,cacheable:t,enforceSparseHoleBudget:t,entries:new Map,length:e.length,ownEntryCount:d(e,t,r)},i.arrays.set(e,l)}for(const o of t){if(!(0,s.isObj)(o))throw new Error("Expected array delta entry to be an object but got an invalid value");const t=f(o,r,l.baselineLength);let a;l.entries.has(t)?a=l.entries.get(t):(0,s.hasOwn)(e,t)?(a=e[t],null==a&&l.entries.set(t,o)):(l.entries.set(t,o),l.ownEntryCount+=1);const u=Math.max(l.length,t+1);if(l.enforceSparseHoleBudget&&u-l.ownEntryCount>1024)throw new n.OpenAIError(`Assistant stream delta contains an invalid ${r} index: ${t}`);(0,s.isObj)(a)&&c(a,o,i),l.length=u}}function _(e,t,r){let n=r.records.get(e);for(const[i,o]of Object.entries(t)){if("index"===i||"type"===i)continue;let t;n?.has(i)?t=n.get(i):(0,s.hasOwn)(e,i)&&(t=e[i]),null!=t?(0,s.isObj)(t)&&(0,s.isObj)(o)?_(t,o,r):Array.isArray(t)&&Array.isArray(o)&&!h(t,o)&&p(t,o,"array",r,_):(n||(n=new Map,r.records.set(e,n)),n.set(i,o))}}function g(e){return((0,s.isObj)(e)||Array.isArray(e))&&a.has(e)}function m(e){if(((0,s.isObj)(e)||Array.isArray(e))&&!a.has(e)){a.add(e),Array.isArray(e)&&o.delete(e);for(const t of Reflect.ownKeys(e)){const r=Object.getOwnPropertyDescriptor(e,t);r&&"value"in r&&m(r.value)}}}function y(e,t,r){a.has(e)&&m(r),Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0})}function A(e){const{index:t}=e;if(null==t)throw new Error("Expected array delta entry to have an `index` property");if("number"!=typeof t)throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");return t}function v(e,t,r){if(h(e,t))return e.push(...t),void o.delete(e);for(const n of t){if(!(0,s.isObj)(n))throw new Error("Expected array delta entry to be an object but got an invalid value");const t=A(n);if((0,s.hasOwn)(e,t)){const s=e[t];null==s?(a.has(e)&&m(n),e[t]=n):e[t]=r(s,n)}else y(e,t,n)}}function b(e,t){const r=a.has(e);for(const[o,a]of Object.entries(t)){if("__proto__"===o||"constructor"===o||"prototype"===o)throw new n.OpenAIError(`Assistant stream delta contains an unsafe property: ${o}`);if(!(0,s.hasOwn)(e,o)){r&&m(a),e[o]=a;continue}let t=e[o];if(null!=t)if("index"!==o&&"type"!==o){if("string"==typeof t&&"string"==typeof a)t+=a;else if("number"==typeof t&&"number"==typeof a)t+=a;else{if(!(0,s.isObj)(t)||!(0,s.isObj)(a)){if(Array.isArray(t)&&Array.isArray(a)){v(t,a,b);continue}throw new TypeError(`Unhandled record type: ${i(o)}`)}t=b(t,a)}e[o]=t}else e[o]=a;else r&&m(a),e[o]=a}return e}function w(e){if((0,s.isObj)(e)||Array.isArray(e))for(const[t,r]of Object.entries(e)){if("__proto__"===t||"constructor"===t||"prototype"===t)throw new n.OpenAIError(`Assistant stream delta contains an unsafe property: ${t}`);w(r)}}},5345(e,t,r){"use strict";t.X509_API_BASE_URL=void 0,t.assertX509APIOrigin=function(e){let t;try{t=new URL(e)}catch{throw new n.OpenAIError("X.509 workload identity requires the approved global mTLS API origin.")}if("https://mtls.api.openai.com"!==t.origin||t.username||t.password)throw new n.OpenAIError("X.509 workload identity requires the approved global mTLS API origin.");for(const e of t.searchParams.keys())if((0,s.isSensitiveQueryParameter)(e))throw new n.OpenAIError("X.509 workload identity cannot send conflicting query authentication credentials.");return t};const n=r(144),s=r(6048);t.X509_API_BASE_URL="https://mtls.api.openai.com/v1"},8422(e,t,r){"use strict";t.normalizeX509CredentialOptions=function(e){const{credential:t}=e;if(void 0===t)return{credential:t,options:e};const r=(0,o.findX509Credential)(t);if(!r)throw new n.OpenAIError("An X.509 credential must be created by the SDK authentication helper.");const s=["apiKey","adminAPIKey","workloadIdentity","x509Transport"].filter(t=>null!=e[t]);if(s.length>0)throw new n.OpenAIError(`The \`credential\` option cannot be combined with ${s.map(e=>`\`${e}\``).join(", ")}.`);return{credential:t,options:{...e,apiKey:null,adminAPIKey:null,baseURL:e.baseURL??null,organization:e.organization??null,project:e.project??null,workloadIdentity:r.identity,x509Transport:r.transport}}},t.prepareX509ClientClone=function(e,t,r,n){const o=(0,s.hasOwn)(t,"workloadIdentity")?t.workloadIdentity:e.workloadIdentity,c=void 0!==r&&(function({apiKey:e,adminAPIKey:t}){return null!=e||null!=t}(t)&&void 0===t.workloadIdentity||void 0!==t.provider);void 0!==r&&(0,s.hasOwn)(t,"workloadIdentity")&&delete e.x509Transport;const l=void 0===r||c||void 0!==t.credential||(0,s.hasOwn)(t,"workloadIdentity")||(0,s.hasOwn)(t,"x509Transport")?void 0:r,u=void 0===t.credential?l:t.credential,h=void 0!==u||!c&&(0,i.isX509WorkloadIdentity)(o);return n!==h&&(delete e.fetch,delete e.baseURL,delete e.organization,delete e.project,delete e.defaultHeaders,delete e.defaultQuery,delete e.fetchOptions,h?e.apiKey=null:(delete e.x509Transport,c&&delete e.workloadIdentity)),void 0!==u&&(delete e.apiKey,delete e.adminAPIKey,delete e.workloadIdentity,delete e.x509Transport,e.credential=u,void 0!==t.credential&&(delete e.organization,delete e.project,delete e.defaultHeaders,delete e.defaultQuery,delete e.fetchOptions)),{credential:u,provider:a(e,t)}};const n=r(144),s=r(8874),i=r(9523),o=r(3679);function a(e,t){const r=e.provider,n=t.credential??t.workloadIdentity,s=t.provider??(n?void 0:r);return s!==r&&(delete e.baseURL,delete e.organization,delete e.project,delete e.defaultHeaders,delete e.defaultQuery,delete e.fetchOptions,delete e.fetch),s&&(delete e.apiKey,delete e.adminAPIKey,delete e.credential,delete e.workloadIdentity,delete e.x509Transport,delete e.baseURL),s}},4623(e,t,r){"use strict";t.resolveX509Transport=function(e){if(!e||"object"!=typeof e)throw new n.OpenAIError("X.509 workload identity requires an approved X.509 transport capability.");const t=(0,s.findRegisteredX509Transport)(e);if(!t)throw new n.OpenAIError("X.509 workload identity requires an approved X.509 transport capability.");return t};const n=r(144),s=r(3679);new Set(["ECONNRESET","ECONNREFUSED","ENETUNREACH","EHOSTUNREACH","ENETDOWN","EPIPE","ETIMEDOUT","EAI_AGAIN","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET"]);Symbol("X.509 transport capability")},3679(e,t,r){"use strict";if((e=r.nmd(e))!==globalThis.module&&void 0!==t&&e.exports===t){Object.defineProperty(t,"__esModule",{value:!0}),t.findX509Credential=t.rememberX509Credential=t.findX509OAuthError=t.rememberX509OAuthError=t.isApprovedX509Client=t.markApprovedX509Client=t.isRetryableX509IssuerError=t.markRetryableX509IssuerError=t.isTransientX509ConnectionError=t.markTransientX509ConnectionError=t.rememberRegisteredX509Transport=t.findRegisteredX509Transport=void 0;const e=new WeakMap,r=new WeakSet,n=new WeakSet,s=new WeakSet,i=new WeakMap,o=new WeakMap;t.findRegisteredX509Transport=WeakMap.prototype.get.bind(e),t.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(e),t.markTransientX509ConnectionError=WeakSet.prototype.add.bind(r),t.isTransientX509ConnectionError=WeakSet.prototype.has.bind(r),t.markRetryableX509IssuerError=WeakSet.prototype.add.bind(n),t.isRetryableX509IssuerError=WeakSet.prototype.has.bind(n),t.markApprovedX509Client=WeakSet.prototype.add.bind(s),t.isApprovedX509Client=WeakSet.prototype.has.bind(s),t.rememberX509OAuthError=WeakMap.prototype.set.bind(i),t.findX509OAuthError=WeakMap.prototype.get.bind(i),t.rememberX509Credential=WeakMap.prototype.set.bind(o),t.findX509Credential=WeakMap.prototype.get.bind(o)}},9523(e,t,r){"use strict";var n,s,i,o,a,c,l,u,h,d,f,p,_,g,m,y,A,v,b,w,E,I,S;t.X509WorkloadIdentityAuth=void 0,t.isX509WorkloadIdentity=function(e){if(!e||"object"!=typeof e)return!1;let t=e;for(;null!==t&&t!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(t,"provider");if(e){if(!("value"in e)||void 0!==e.value)return!1;break}t=Object.getPrototypeOf(t)}let r=e;for(;null!==r&&r!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(r,"type");if(e){if(!("value"in e))throw new k.OpenAIError("X.509 workload identity type must be a plain data property.");return"x509"===e.value}r=Object.getPrototypeOf(r)}return!1},t.assertX509RequestOptions=$,t.snapshotX509RequestOptions=function(e){$(e);const t={...e};return $(t),t};const P=r(6316),k=r(144),O=r(3098),C=r(6786),R=r(6048),B=r(8874),x=r(5345),T=r(4623),N=r(3679),F=["dispatcher","agent","client","tls","proxy"],M=(e,t)=>Headers.prototype.get.call(e,t),L=e=>{const t=new k.APIUserAbortError;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t};function U(e){for(const t of Headers.prototype.keys.call(e)){const e=t.toLowerCase().split("_").join("-");if("authorization"!==e&&(0,R.isSensitiveHeader)(e)||"host"===e)throw new k.OpenAIError("X.509 workload identity cannot send conflicting authentication credentials.")}}function D(e){if(!e)return;for(const t of F)if((0,B.hasOwn)(e,t))throw new k.OpenAIError("X.509 workload identity cannot override its approved transport capability.");const t=Object.getOwnPropertyDescriptor(e,"redirect")?.value;if(void 0!==t&&"manual"!==t)throw new k.OpenAIError("X.509 workload identity requests require manual redirects.")}function $(e){if(D(e),e&&["body","headers","method","signal"].some(t=>(0,B.hasOwn)(e,t)))throw new k.OpenAIError("X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.")}class j{constructor(e,t,r,s){if(n.add(this),i.set(this,void 0),o.set(this,void 0),a.set(this,void 0),c.set(this,void 0),l.set(this,void 0),u.set(this,void 0),h.set(this,void 0),d.set(this,void 0),f.set(this,void 0),p.set(this,void 0),_.set(this,0),P.__classPrivateFieldSet(this,h,(0,T.resolveX509Transport)(t),"f"),P.__classPrivateFieldSet(this,i,e.identityProviderId,"f"),P.__classPrivateFieldSet(this,o,e.serviceAccountId,"f"),P.__classPrivateFieldSet(this,a,e.refreshBufferMs,"f"),P.__classPrivateFieldSet(this,c,e.refreshBufferSeconds,"f"),P.__classPrivateFieldSet(this,l,r,"f"),P.__classPrivateFieldSet(this,u,s,"f"),void 0!==P.__classPrivateFieldGet(this,a,"f")&&void 0!==P.__classPrivateFieldGet(this,c,"f"))throw new k.OpenAIError("X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.");if(void 0!==P.__classPrivateFieldGet(this,a,"f")&&(!Number.isSafeInteger(P.__classPrivateFieldGet(this,a,"f"))||P.__classPrivateFieldGet(this,a,"f")<0))throw new k.OpenAIError("X.509 workload identity requires a nonnegative integer refreshBufferMs.");if(void 0!==P.__classPrivateFieldGet(this,c,"f")&&(!Number.isSafeInteger(P.__classPrivateFieldGet(this,c,"f"))||P.__classPrivateFieldGet(this,c,"f")<0||!Number.isSafeInteger(1e3*P.__classPrivateFieldGet(this,c,"f"))))throw new k.OpenAIError("X.509 workload identity requires a nonnegative integer refreshBufferSeconds.");P.__classPrivateFieldSet(this,d,void 0===P.__classPrivateFieldGet(this,c,"f")?P.__classPrivateFieldGet(this,a,"f")??12e5:1e3*P.__classPrivateFieldGet(this,c,"f"),"f")}identitySnapshot(){return{type:"x509",identityProviderId:P.__classPrivateFieldGet(this,i,"f"),serviceAccountId:P.__classPrivateFieldGet(this,o,"f"),...void 0===P.__classPrivateFieldGet(this,a,"f")?{}:{refreshBufferMs:P.__classPrivateFieldGet(this,a,"f")},...void 0===P.__classPrivateFieldGet(this,c,"f")?{}:{refreshBufferSeconds:P.__classPrivateFieldGet(this,c,"f")}}}static shouldAuthenticate(e,t,r=e.headers){return!(0,O.buildHeaders)([t,r]).nulls.has("authorization")}snapshotHeaders(e,t){const r=P.__classPrivateFieldGet(this,n,"m",I).call(this);return r.defaultHeaders??(r.defaultHeaders=(0,O.buildHeaders)([e])),r.requestHeaders??(r.requestHeaders=(0,O.buildHeaders)([t])),this.headerSnapshots()}headerSnapshots(){const{defaultHeaders:e,requestHeaders:t}=P.__classPrivateFieldGet(this,n,"m",I).call(this);if(!e||!t)throw new k.OpenAIError("X.509 workload identity requires snapshotted request headers.");return{defaultHeaders:e,requestHeaders:t}}snapshotTenant(e,t){if(e!==P.__classPrivateFieldGet(this,l,"f")||t!==P.__classPrivateFieldGet(this,u,"f"))throw new k.OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");const r=P.__classPrivateFieldGet(this,n,"m",I).call(this);return r.tenant={organization:e,project:t},r.tenant}tenantSnapshot(){const{tenant:e}=P.__classPrivateFieldGet(this,n,"m",I).call(this);if(!e)throw new k.OpenAIError("X.509 workload identity requires snapshotted tenant selectors.");return e}snapshotAPIURL(e){(0,x.assertX509APIOrigin)(e),P.__classPrivateFieldGet(this,n,"m",I).call(this).apiURL=e}requestAPIURL(){const{apiURL:e}=P.__classPrivateFieldGet(this,n,"m",I).call(this);if(void 0===e)throw new k.OpenAIError("X.509 workload identity requires a snapshotted API destination.");return e}snapshotRequest(e,t,r){var s;(s=P.__classPrivateFieldGet(this,n,"m",I).call(this)).request??(s.request={signal:e,timeout:t,fetchOptions:r})}requestSnapshot(){const{request:e}=P.__classPrivateFieldGet(this,n,"m",I).call(this);if(!e)throw new k.OpenAIError("X.509 workload identity requires snapshotted request settings.");return e}beginRequestPreparation(){const e=P.__classPrivateFieldGet(this,n,"m",I).call(this);e.deadlineArmed&&void 0===e.preparationStartedAt&&(e.preparationStartedAt=performance.now(),e.preparationWallStartedAt=Date.now())}beginRequestPlanning(){P.__classPrivateFieldGet(this,n,"m",I).call(this).phase="planning"}beginRequestNetwork(){const e=P.__classPrivateFieldGet(this,n,"m",I).call(this);e.deadlineArmed?void 0!==e.preparationStartedAt&&(e.monotonicStartedAt+=performance.now()-e.preparationStartedAt,e.wallStartedAt+=Date.now()-(e.preparationWallStartedAt??Date.now()),delete e.preparationStartedAt,delete e.preparationWallStartedAt):(e.wallStartedAt=Date.now(),e.monotonicStartedAt=performance.now(),e.deadlineArmed=!0)}isPlanningRequest(){return"planning"===P.__classPrivateFieldGet(this,n,"m",I).call(this).phase}authorizePlannedRequest(e,t,r,s=!1){const i=P.__classPrivateFieldGet(this,n,"m",I).call(this),o=Object.getOwnPropertyDescriptor(t,"headers"),a=Object.getOwnPropertyDescriptor(t,"body"),c=Object.getOwnPropertyDescriptor(t,"signal"),l=Object.getOwnPropertyDescriptor(t,"redirect");if("planning"!==i.phase||!o||!(o.value instanceof Headers)||!a&&"body"in t||[a,c,l].some(e=>e&&!("value"in e)))throw new k.OpenAIError("X.509 workload identity requires an approved final request.");this.snapshotAPIURL(e),D(t);try{U(o.value)}catch{throw new k.OpenAIError("X.509 workload identity cannot use caller-supplied authentication credentials.")}if(null!==M(o.value,"Authorization"))throw new k.OpenAIError("X.509 workload identity cannot use caller-supplied authorization credentials.");if(P.__classPrivateFieldGet(this,n,"m",S).call(this,o.value),!s&&(c?.value??void 0)!==(this.requestSnapshot().signal??void 0))throw new k.OpenAIError("X.509 workload identity must preserve its approved request signal.");const u=this.requestSnapshot();i.request={...u,timeout:Math.min(u.timeout,r)},i.phase="authorizing"}ownRequestBody(e,t){e instanceof ReadableStream&&e!==t&&(P.__classPrivateFieldGet(this,n,"m",I).call(this).materializedBody=e)}static isStreamingRequestBody(e){return void 0!==globalThis.ReadableStream&&e instanceof globalThis.ReadableStream||"object"==typeof e&&null!==e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)}retireRequestBody(){const e=P.__classPrivateFieldGet(this,n,"m",I).call(this),t=e.materializedBody;delete e.materializedBody,t&&P.__classPrivateFieldGet(s,s,"m",g).call(s,t)}releaseRequestBody(e){const t=P.__classPrivateFieldGet(this,n,"m",I).call(this);t.materializedBody===e?delete t.materializedBody:this.retireRequestBody()}setEffectiveSignal(e){e?P.__classPrivateFieldGet(this,n,"m",I).call(this).effectiveSignal=e:delete P.__classPrivateFieldGet(this,n,"m",I).call(this).effectiveSignal}effectiveSignal(){const e=P.__classPrivateFieldGet(this,n,"m",I).call(this);return e.effectiveSignal??e.request?.signal}runRequest(e,t){return P.__classPrivateFieldGet(this,h,"f").run(async()=>{const r=P.__classPrivateFieldGet(this,h,"f").current();if(!r)throw new k.OpenAIError("X.509 workload identity requires an active certificate request scope.");r.owner=this,r.requestOwner=t;try{return await e()}finally{this.retireRequestBody(),this.releaseRequestCredentials(),delete r.requestOwner,delete r.owner}})}inRequest(e){const t=P.__classPrivateFieldGet(this,h,"f").current();return t?.owner===this&&t.requestOwner===e&&"authorizing"!==t.phase}matches(e){return P.__classPrivateFieldGet(this,h,"f")===P.__classPrivateFieldGet(e,h,"f")&&P.__classPrivateFieldGet(this,i,"f")===P.__classPrivateFieldGet(e,i,"f")&&P.__classPrivateFieldGet(this,o,"f")===P.__classPrivateFieldGet(e,o,"f")&&P.__classPrivateFieldGet(this,l,"f")===P.__classPrivateFieldGet(e,l,"f")&&P.__classPrivateFieldGet(this,u,"f")===P.__classPrivateFieldGet(e,u,"f")&&P.__classPrivateFieldGet(this,d,"f")===P.__classPrivateFieldGet(e,d,"f")}continuation(){const{wallStartedAt:e,monotonicStartedAt:t,deadlineArmed:r,request:s,requestOwner:i,effectiveSignal:o}=P.__classPrivateFieldGet(this,n,"m",I).call(this),a={wallStartedAt:e,monotonicStartedAt:t,owner:this,...r?{deadlineArmed:r}:{},...s?{request:s}:{},...o?{effectiveSignal:o}:{},...i?{requestOwner:i}:{}};return e=>P.__classPrivateFieldGet(this,h,"f").resume(a,async()=>{try{return await e()}finally{this.releaseRequestCredentials(),delete a.requestOwner,delete a.owner}})}releaseRequestCredentials(){const e=P.__classPrivateFieldGet(this,n,"m",I).call(this);delete e.request,delete e.phase,delete e.deadlineArmed,delete e.preparationStartedAt,delete e.preparationWallStartedAt,delete e.effectiveSignal,delete e.materializedBody,delete e.apiURL,delete e.tenant,delete e.token,delete e.defaultHeaders,delete e.requestHeaders,delete e.tokenGeneration,delete e.headers,delete e.authorization}requestStartedAt(e){return P.__classPrivateFieldGet(this,h,"f").current()?.wallStartedAt}usedWorkloadToken(e){return void 0!==P.__classPrivateFieldGet(this,h,"f").current()?.token}remainingTimeout(e,t){const r=P.__classPrivateFieldGet(this,h,"f").current();if(void 0===r)return t;const n=t-(performance.now()-r.monotonicStartedAt);if(n<=0)throw new k.APIConnectionTimeoutError;return n}async waitForRetry(e,t){try{await P.__classPrivateFieldGet(this,h,"f").sleep(e,t)}catch(e){if(t?.aborted)throw L(t);throw e}}static isRetryableFailure(e){return"object"==typeof e&&null!==e&&((0,N.isTransientX509ConnectionError)(e)||(0,N.isRetryableX509IssuerError)(e))}static retryHeaders(e){if(!e||"object"!=typeof e||!(0,N.isRetryableX509IssuerError)(e))return;const t=Object.getOwnPropertyDescriptor(e,"headers")?.value;return t instanceof Headers?t:void 0}async getToken(e,t){const r=t?t.signal:e?.signal;if(r?.aborted)throw L(r);e&&$(t?t.fetchOptions:e.fetchOptions),P.__classPrivateFieldGet(this,n,"m",E).call(this,t);const i=e?P.__classPrivateFieldGet(this,n,"m",I).call(this):void 0,o=P.__classPrivateFieldGet(this,f,"f");if(o&&performance.now()<o.refreshAt&&Date.now()<o.wallRefreshAt)return P.__classPrivateFieldGet(s,s,"m",m).call(s,i,o);const a=t&&e?this.remainingTimeout(e,t.timeout):t?.timeout,{signal:c,dispose:l}=function(e,t){const r=new AbortController,n=void 0===e?void 0:setTimeout(()=>r.abort(new k.APIConnectionTimeoutError),e),s=n;"object"==typeof s&&null!==s&&"unref"in s&&"function"==typeof s.unref&&s.unref();const i=()=>r.abort(t?.reason);return t?.addEventListener("abort",i,{once:!0}),t?.aborted&&i(),{signal:r.signal,dispose:()=>{t?.removeEventListener("abort",i),n&&clearTimeout(n)}}}(a,r);if(r?.aborted)throw l(),L(r);const u=P.__classPrivateFieldGet(this,p,"f")??P.__classPrivateFieldGet(this,n,"m",b).call(this);u.waiters+=1;const h=function(e,t){let r;const n=new Promise((e,n)=>{r=()=>n(t.reason),t.addEventListener("abort",r,{once:!0}),t.aborted&&r()});return{result:Promise.race([e.promise,n]),dispose:()=>{r&&t.removeEventListener("abort",r)}}}(u,c);try{const e=await h.result,t=P.__classPrivateFieldGet(this,f,"f");if(!t||t.accessToken!==e.accessToken)throw new k.APIUserAbortError;return P.__classPrivateFieldGet(s,s,"m",m).call(s,i,t)}catch(r){return await P.__classPrivateFieldGet(this,n,"m",y).call(this,r,u,o,i,e,t)}finally{h.dispose(),l(),u.waiters-=1,P.__classPrivateFieldGet(this,n,"m",v).call(this,u)}}invalidateToken(){const e=P.__classPrivateFieldGet(this,h,"f").current();if(!e?.token||P.__classPrivateFieldGet(this,f,"f")?.accessToken!==e.token||P.__classPrivateFieldGet(this,f,"f").generation!==e.tokenGeneration)return;P.__classPrivateFieldSet(this,_,P.__classPrivateFieldGet(this,_,"f")+1,"f"),P.__classPrivateFieldSet(this,f,void 0,"f");const t=P.__classPrivateFieldGet(this,p,"f");P.__classPrivateFieldSet(this,p,void 0,"f"),t?.controller.abort(new k.APIUserAbortError)}bindRequest(e,t,r){if(!(t.headers instanceof Headers))throw new k.OpenAIError("X.509 workload identity requires the original workload authorization headers.");const s=P.__classPrivateFieldGet(this,n,"m",I).call(this),{token:i}=s,o=e.__security??{bearerAuth:!0};let a=i?`Bearer ${i}`:null;!i&&o.adminAPIKeyAuth&&null!==r&&null!==M(t.headers,"Authorization")&&(a=new Headers({Authorization:`Bearer ${r}`}).get("Authorization")),s.headers=t.headers,s.authorization=a,this.assertRequest(t)}adoptRequestHeaders(e){const t=P.__classPrivateFieldGet(this,n,"m",I).call(this),r=t.headers;if(!(r instanceof Headers&&e.headers instanceof Headers))throw new k.OpenAIError("X.509 workload identity must preserve its issued workload authorization.");t.headers=e.headers;try{this.assertRequest(e)}catch(e){throw t.headers=r,e}}assertRequest(e){const{headers:t}=e;if(!(t instanceof Headers))throw new k.OpenAIError("X.509 workload identity must preserve its issued workload authorization.");const r=P.__classPrivateFieldGet(this,h,"f").current();if(!r||r.headers!==t||void 0===r.authorization||M(t,"Authorization")!==r.authorization)throw new k.OpenAIError("X.509 workload identity must preserve its issued workload authorization.");P.__classPrivateFieldGet(this,n,"m",S).call(this,t),U(t)}fetch(){return async(e,t={})=>{const r=(0,x.assertX509APIOrigin)("string"==typeof e||e instanceof URL?e:e.url);D(t),this.assertRequest(t);const n=t.headers;if(!(n instanceof Headers))throw new k.OpenAIError("X.509 workload identity must preserve its issued workload authorization.");const s=new Headers([...Headers.prototype.entries.call(n)]);return U(s),t.headers=s,t.redirect="manual",await P.__classPrivateFieldGet(this,h,"f").dispatch(r,t)}}}t.X509WorkloadIdentityAuth=j,s=j,i=new WeakMap,o=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,_=new WeakMap,n=new WeakSet,g=async function(e){try{await(0,C.CancelReadableStream)(e)}catch{}},m=function(e,t){return e&&(e.token=t.accessToken,e.tokenGeneration=t.generation),t.accessToken},y=async function(e,t,r,s,i,o){const a=o?o.signal:i?.signal;if(a?.aborted)throw L(a);if(t.controller.signal.aborted&&t.generation!==P.__classPrivateFieldGet(this,_,"f"))return await this.getToken(i,o);const c=P.__classPrivateFieldGet(this,n,"m",A).call(this,e,r,s);if(void 0!==c)return c;if(e&&"object"==typeof e&&!(e instanceof k.OAuthError)){const t=(0,N.findX509OAuthError)(e);if(t)throw new k.OAuthError(t.status,t.error,t.headers)}throw e},A=function(e,t,r){if(!t||t!==P.__classPrivateFieldGet(this,f,"f")||performance.now()>=t.expiresAt||Date.now()>=t.wallExpiresAt||!s.isRetryableFailure(e))return;const n=s.retryHeaders(e),i=n?.get("retry-after-ms");let o=i?Number(i):void 0;const a=n?.get("retry-after");if(a&&(void 0===o||Number.isNaN(o))){const e=Number(a);o=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}const c=void 0!==o&&Number.isFinite(o)&&o>=0&&o<=6e4?Math.max(1e3,o):1e3;return t.refreshAt=Math.min(t.expiresAt,performance.now()+c),t.wallRefreshAt=Math.min(t.wallExpiresAt,Date.now()+c),P.__classPrivateFieldGet(s,s,"m",m).call(s,r,t)},v=function(e){0===e.waiters&&P.__classPrivateFieldGet(this,p,"f")===e&&queueMicrotask(()=>{0===e.waiters&&P.__classPrivateFieldGet(this,p,"f")===e&&(P.__classPrivateFieldSet(this,p,void 0,"f"),P.__classPrivateFieldSet(this,_,P.__classPrivateFieldGet(this,_,"f")+1,"f"),e.controller.abort(new k.APIUserAbortError))})},b=function(){const e=new AbortController,t=P.__classPrivateFieldGet(this,_,"f"),r={controller:e,generation:t,waiters:0,promise:P.__classPrivateFieldGet(this,n,"m",w).call(this,e,t)};return P.__classPrivateFieldSet(this,p,r,"f"),r},w=async function(e,t){const r=performance.now(),n=Date.now();try{const s=await P.__classPrivateFieldGet(this,h,"f").exchange(P.__classPrivateFieldGet(this,i,"f"),P.__classPrivateFieldGet(this,o,"f"),e.signal),a=1e3*s.expiresIn,c=r+a,l=n+a;if(performance.now()>=c||Date.now()>=l)throw new k.OpenAIError("X.509 workload identity token expired before its exchange completed.");if(P.__classPrivateFieldGet(this,_,"f")!==t||e.signal.aborted||P.__classPrivateFieldGet(this,p,"f")?.controller!==e)throw new k.APIUserAbortError;return P.__classPrivateFieldSet(this,_,P.__classPrivateFieldGet(this,_,"f")+1,"f"),P.__classPrivateFieldSet(this,f,{accessToken:s.accessToken,generation:P.__classPrivateFieldGet(this,_,"f"),expiresAt:c,refreshAt:c-Math.min(P.__classPrivateFieldGet(this,d,"f"),a/2),wallExpiresAt:l,wallRefreshAt:l-Math.min(P.__classPrivateFieldGet(this,d,"f"),a/2)},"f"),s}finally{P.__classPrivateFieldGet(this,p,"f")?.controller===e&&P.__classPrivateFieldSet(this,p,void 0,"f")}},E=function(e){if(!e)return;if(e.organization!==P.__classPrivateFieldGet(this,l,"f")||e.project!==P.__classPrivateFieldGet(this,u,"f"))throw new k.OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");(0,x.assertX509APIOrigin)(e.apiURL);const t=(0,O.buildHeaders)([e.defaultHeaders,e.requestHeaders]);if(null!==P.__classPrivateFieldGet(this,l,"f")&&t.nulls.has("openai-organization")||null!==P.__classPrivateFieldGet(this,u,"f")&&t.nulls.has("openai-project"))throw new k.OpenAIError("X.509 workload identity cannot omit its enrolled organization or project.");for(const r of t.values.keys()){const n=r.toLowerCase().split("_").join("-");if(!("openai-organization"!==n&&"openai-project"!==n||r===n&&M(t.values,r)===("openai-organization"===n?e.organization:e.project)))throw new k.OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");if((0,R.isSensitiveHeader)(n)||"host"===n)throw new k.OpenAIError("X.509 workload identity cannot use caller-supplied authentication credentials.")}},I=function(){const e=P.__classPrivateFieldGet(this,h,"f").current();if(!e||e.owner!==this)throw new k.OpenAIError("X.509 workload identity requires an active certificate request scope.");return e},S=function(e){if(M(e,"OpenAI-Organization")!==P.__classPrivateFieldGet(this,l,"f")||M(e,"OpenAI-Project")!==P.__classPrivateFieldGet(this,u,"f"))throw new k.OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");for(const t of Headers.prototype.keys.call(e)){const e=t.toLowerCase().split("_").join("-");if(("openai-organization"===e||"openai-project"===e)&&t!==e)throw new k.OpenAIError("X.509 workload identity cannot override its enrolled organization or project.")}}},1958(e,t,r){"use strict";t.brand_privateBedrockClient=void 0,t.assertBedrockRequestOrigin=function(e,t){const r=new URL(e),s=new URL(t),i=r.origin,o=s.origin;if("http:"!==r.protocol&&"https:"!==r.protocol||"http:"!==s.protocol&&"https:"!==s.protocol||o!==i)throw new n.OpenAIError(`Bedrock request origin \`${o}\` does not match the configured base URL origin \`${i}\`.`)},t.assertValidBedrockBearerCredential=s;const n=r(6316).__importStar(r(2154));r(4737);function s(e){if(/^[\t ]|[\t ]$/.test(e))throw new TypeError("Bedrock bearer credential contains an invalid HTTP header value.");for(const t of e){const e=t.codePointAt(0)??0;if(e<32&&9!==e||127===e||e>255)throw new TypeError("Bedrock bearer credential contains an invalid HTTP header value.")}}t.brand_privateBedrockClient=Symbol.for("openai.privateBedrockClient")},7699(e,t,r){"use strict";t.resolveDataResidency=function(e){if(null===e.dataResidency||void 0===e.dataResidency)return;if((0,s.hasOwn)(e,"baseURL"))throw new n.OpenAIError("The `dataResidency` and `baseURL` options are mutually exclusive.");const t=i.get(e.dataResidency);if(void 0===t)throw new n.OpenAIError("Invalid `dataResidency`; expected one of: global, us, eu, ae.");return t},t.assertNoDataResidency=function(e,t){if(null!=e)throw new n.OpenAIError(`${t} does not support \`dataResidency\`.`)};const n=r(144),s=r(8874),i=new Map([["global","https://api.openai.com/v1"],["us","https://us.api.openai.com/v1"],["eu","https://eu.api.openai.com/v1"],["ae","https://ae.api.openai.com/v1"]])},2736(e,t,r){"use strict";var n,s,i,o,a,c,l;t.LineDecoder=void 0,t.findDoubleNewlineIndex=function(e){for(let t=0;t<e.length-1;t++){const r=_(e,t);if(r>0){const n=t+r,s=_(e,n);if(s>0)return n+s}}return-1};const u=r(6316),h=r(4545),d=65536;class f{constructor(){n.add(this),s.set(this,void 0),i.set(this,void 0),o.set(this,void 0),a.set(this,void 0),c.set(this,void 0),u.__classPrivateFieldSet(this,s,new Uint8Array,"f"),u.__classPrivateFieldSet(this,i,0,"f"),u.__classPrivateFieldSet(this,o,0,"f"),u.__classPrivateFieldSet(this,a,0,"f"),u.__classPrivateFieldSet(this,c,!1,"f")}decode(e){if(null==e)return[];let t;if(t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(0,h.encodeUTF8)(e):e,0===t.length)return[];if(u.__classPrivateFieldGet(this,c,"f")&&(u.__classPrivateFieldSet(this,c,!1,"f"),10===t[0]&&(t=t.subarray(1)),0===t.length))return[];u.__classPrivateFieldGet(this,n,"m",l).call(this,t);const r=[];let f;for(;null!=(f=p(u.__classPrivateFieldGet(this,s,"f"),u.__classPrivateFieldGet(this,a,"f"),u.__classPrivateFieldGet(this,o,"f")));){const e=(0,h.decodeUTF8)(u.__classPrivateFieldGet(this,s,"f").subarray(u.__classPrivateFieldGet(this,i,"f"),f.preceding));r.push(e),u.__classPrivateFieldSet(this,i,f.index,"f"),f.carriage&&(u.__classPrivateFieldGet(this,i,"f")<u.__classPrivateFieldGet(this,o,"f")&&10===u.__classPrivateFieldGet(this,s,"f")[u.__classPrivateFieldGet(this,i,"f")]?u.__classPrivateFieldSet(this,i,u.__classPrivateFieldGet(this,i,"f")+1,"f"):u.__classPrivateFieldGet(this,i,"f")===u.__classPrivateFieldGet(this,o,"f")&&u.__classPrivateFieldSet(this,c,!0,"f")),u.__classPrivateFieldSet(this,a,u.__classPrivateFieldGet(this,i,"f"),"f")}if(u.__classPrivateFieldSet(this,a,u.__classPrivateFieldGet(this,o,"f"),"f"),u.__classPrivateFieldGet(this,i,"f")===u.__classPrivateFieldGet(this,o,"f"))u.__classPrivateFieldSet(this,i,0,"f"),u.__classPrivateFieldSet(this,o,0,"f"),u.__classPrivateFieldSet(this,a,0,"f"),u.__classPrivateFieldGet(this,s,"f").length>d&&u.__classPrivateFieldSet(this,s,new Uint8Array,"f");else if(r.length>0&&u.__classPrivateFieldGet(this,s,"f").length>d){const e=u.__classPrivateFieldGet(this,o,"f")-u.__classPrivateFieldGet(this,i,"f");if(e<=d||u.__classPrivateFieldGet(this,s,"f").length>4*e){const t=e<=d?Math.min(Math.max(2*e,256),d):2*e,r=new Uint8Array(t);r.set(u.__classPrivateFieldGet(this,s,"f").subarray(u.__classPrivateFieldGet(this,i,"f"),u.__classPrivateFieldGet(this,o,"f"))),u.__classPrivateFieldSet(this,s,r,"f"),u.__classPrivateFieldSet(this,i,0,"f"),u.__classPrivateFieldSet(this,o,e,"f"),u.__classPrivateFieldSet(this,a,e,"f")}}return r}flush(){return u.__classPrivateFieldSet(this,c,!1,"f"),u.__classPrivateFieldGet(this,i,"f")===u.__classPrivateFieldGet(this,o,"f")?[]:this.decode("\n")}}function p(e,t,r){for(let n=t;n<r;n++){if(10===e[n])return{preceding:n,index:n+1,carriage:!1};if(13===e[n])return{preceding:n,index:n+1,carriage:!0}}return null}function _(e,t){return 10===e[t]?1:13===e[t]?10===e[t+1]?2:1:0}t.LineDecoder=f,s=new WeakMap,i=new WeakMap,o=new WeakMap,a=new WeakMap,c=new WeakMap,n=new WeakSet,l=function(e){if(u.__classPrivateFieldGet(this,o,"f")+e.length>u.__classPrivateFieldGet(this,s,"f").length){const t=u.__classPrivateFieldGet(this,o,"f")-u.__classPrivateFieldGet(this,i,"f");if(u.__classPrivateFieldGet(this,i,"f")>=u.__classPrivateFieldGet(this,s,"f").length/2&&t+e.length<=u.__classPrivateFieldGet(this,s,"f").length)u.__classPrivateFieldGet(this,s,"f").copyWithin(0,u.__classPrivateFieldGet(this,i,"f"),u.__classPrivateFieldGet(this,o,"f"));else{const r=Math.max(2*u.__classPrivateFieldGet(this,s,"f").length,t+e.length,256),n=new Uint8Array(r);n.set(u.__classPrivateFieldGet(this,s,"f").subarray(u.__classPrivateFieldGet(this,i,"f"),u.__classPrivateFieldGet(this,o,"f"))),u.__classPrivateFieldSet(this,s,n,"f")}u.__classPrivateFieldSet(this,a,u.__classPrivateFieldGet(this,a,"f")-u.__classPrivateFieldGet(this,i,"f"),"f"),u.__classPrivateFieldSet(this,o,t,"f"),u.__classPrivateFieldSet(this,i,0,"f")}u.__classPrivateFieldGet(this,s,"f").set(e,u.__classPrivateFieldGet(this,o,"f")),u.__classPrivateFieldSet(this,o,u.__classPrivateFieldGet(this,o,"f")+e.length,"f")},f.NEWLINE_CHARS=new Set(["\n","\r"]),f.NEWLINE_REGEXP=/\r\n|[\n\r]/g},53(e,t,r){"use strict";t.getPlatformHeaders=t.isRunningInBrowser=void 0;const n=r(3284);t.isRunningInBrowser=()=>"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator;const s=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",i=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let o;t.getPlatformHeaders=()=>o??(o=(()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n.VERSION,"X-Stainless-OS":i(Deno.build.os),"X-Stainless-Arch":s(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n.VERSION,"X-Stainless-OS":i(globalThis.process.platform??"unknown"),"X-Stainless-Arch":s(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/\bEdg(?:e|A|iOS)?\b(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:r}of e){const e=r.exec(navigator.userAgent);if(e)return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":n.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})())},7545(e,t){"use strict";t.castToError=void 0,t.isAbortError=function(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))},t.castToError=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t="cause"in e,r=new Error(e.message,t?{cause:e.cause}:{});return e.stack&&(r.stack=e.stack),t&&!Object.prototype.hasOwnProperty.call(r,"cause")&&(r.cause=e.cause),e.name&&(r.name=e.name),r}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)}},3098(e,t,r){"use strict";t.buildHeaders=void 0;const n=r(8874),s=Symbol("brand.privateNullableHeaders"),i=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*o(e){if(!e)return;if(s in e){const{values:t,nulls:r}=e;yield*t.entries();for(const e of r)yield[e,null];return}let t,r=!1;const i=Symbol.iterator in e?e[Symbol.iterator]:void 0;"function"==typeof i?t={[Symbol.iterator]:()=>i.call(e)}:(r=!0,t=Object.entries(e??{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const s=(0,n.isReadonlyArray)(e[1])?e[1]:[e[1]];let i=!1;for(const e of s)void 0!==e&&(r&&!i&&(i=!0,yield[t,null]),yield[t,e])}}t.buildHeaders=e=>{const t=new Headers,r=new Set;for(const n of e){const e=new Set;for(const[s,a]of o(n)){if(!i.test(s))throw new TypeError(`Header name must be a valid HTTP token ["${s}"]`);const n=s.toLowerCase();e.has(n)||(t.delete(n),e.add(n)),null===a?(t.delete(n),r.add(n)):(t.append(n,a),r.delete(n))}}return{[s]:!0,values:t,nulls:r}}},4184(e,t,r){"use strict";t.encodedMultipartFormRequestOptions=async function(e,t,r,i=null){if(null===e.body||"object"!=typeof e.body||Array.isArray(e.body))throw new TypeError("Multipart request body must be an object");const o=Object.fromEntries(Object.entries(e.body).filter(([,e])=>void 0!==e));if(null!==i&&1===Object.keys(o).length&&Object.prototype.hasOwnProperty.call(o,i)){const t=o[i];if("string"!=typeof t)throw new TypeError("Raw multipart alternative must be a string");return{...e,body:t,headers:(0,s.buildHeaders)([e.headers,{"content-type":r[i].content_type}])}}const a=[];for(const[e,t]of Object.entries(r)){if(!Object.prototype.hasOwnProperty.call(o,e))continue;const r=o[e],s=t.json?JSON.stringify(r):r;if("string"!=typeof s)throw new TypeError(`Multipart field ${e} must encode as a string`);a.push([e,(0,n.makeFile)([s],"",{type:t.content_type})]),delete o[e]}const c=(await(0,n.multipartFormRequestOptions)({...e,body:o},t)).body;if(!(c instanceof FormData))throw await c.cancel(),new TypeError("Unexpected streaming upload in typed multipart request body");for(const[e,t]of a)c.append(e,t,"");return{...e,body:c,headers:(0,s.buildHeaders)([e.headers,{"content-type":null}])}};const n=r(1598),s=r(3098)},907(e,t,r){"use strict";t.defaultParseResponse=async function(e,t){const{response:r,requestLogID:a,retryOfRequestLogID:c,startTime:l}=t,u=await(async()=>{if(t.options.stream)return(0,i.loggerFor)(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData):n.Stream.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData);if(204===r.status)return null;if(t.options.__binaryResponse)return r;const s=r.headers.get("content-type"),a=s?.split(";")[0]?.trim().toLowerCase();if(a?.includes("application/json")||a?.endsWith("+json")){if("0"===r.headers.get("content-length"))return;const e=await r.text();if(!e)return;return o(JSON.parse(e),r)}return await r.text()})().catch(e=>{throw function(e,t){if(!t.aborted||e!==t.reason||(0,s.isAbortError)(e))return e;const r="This operation was aborted",n=globalThis.DOMException;return"function"==typeof n?new n(r,"AbortError"):Object.assign(new Error(r),{name:"AbortError"})}(e,t.controller.signal)});return(0,i.loggerFor)(e).debug(`[${a}] response parsed`,(0,i.formatRequestDetails)({retryOfRequestLogID:c,url:r.url,status:r.status,body:u,durationMs:Date.now()-l})),u},t.addRequestID=o;const n=r(7542),s=r(7545),i=r(6048);function o(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}},7659(e,t){"use strict";t.configureProvider=function(e){const t=i.get(e);if(!t)throw new Error("Invalid provider. Providers must be created with createProvider().");return t.configure()};const r=Symbol.for("openai.node.providerDefinitions.v1"),n=globalThis,s=n[r],i=s??new WeakMap;s||Object.defineProperty(n,r,{value:i})},3157(e,t){"use strict";t.RFC1738=t.formatters=t.default_formatter=t.default_format=void 0,t.default_format="RFC3986",t.default_formatter=String,t.formatters={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:t.default_formatter},t.RFC1738="RFC1738"},3092(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringify=function(e,t={}){let r=e;const c=function(e=l){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||l.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=s.default_format;if(void 0!==e.format){if(!(0,n.has)(s.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const a=s.formatters[r];let c,u,h=l.filter;if(("function"==typeof e.filter||(0,i.isArray)(e.filter))&&(h=e.filter),c=e.arrayFormat&&e.arrayFormat in o?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":l.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");return u=void 0===e.allowDots?1==!!e.encodeDotInKeys||l.allowDots:!!e.allowDots,{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:l.addQueryPrefix,allowDots:u,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:l.allowEmptyArrays,arrayFormat:c,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:l.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?l.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:l.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:l.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:l.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:l.encodeValuesOnly,filter:h,format:r,formatter:a,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:l.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:l.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:l.strictNullHandling}}(t);let u,d;"function"==typeof c.filter?(d=c.filter,r=d("",r)):(0,i.isArray)(c.filter)&&(d=c.filter,u=d);const f=[];if("object"!=typeof r||null===r)return"";const p=o[c.arrayFormat],_="comma"===p&&c.commaRoundTrip;u||(u=Object.keys(r)),c.sort&&u.sort(c.sort);const g=new WeakMap;for(const e of u)c.skipNulls&&null===r[e]||a(f,h(r[e],e,p,_,c.allowEmptyArrays,c.strictNullHandling,c.skipNulls,c.encodeDotInKeys,c.encode?c.encoder:null,c.filter,c.sort,c.allowDots,c.serializeDate,c.format,c.formatter,c.encodeValuesOnly,c.charset,g));const m=f.join(c.delimiter);let y=!0===c.addQueryPrefix?"?":"";return c.charsetSentinel&&(y+="iso-8859-1"===c.charset?"utf8=%26%2310003%3B&":"utf8=%E2%9C%93&"),m.length>0?y+m:""};const n=r(2880),s=r(3157),i=r(8874),o={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},a=function(e,t){Array.prototype.push.apply(e,(0,i.isArray)(t)?t:[t])};let c;const l={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:n.encode,encodeValuesOnly:!1,format:s.default_format,formatter:s.default_formatter,indices:!1,serializeDate:e=>(c??(c=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1},u={};function h(e,t,r,s,o,c,d,f,p,_,g,m,y,A,v,b,w,E){let I=e,S=E,P=0,k=!1;for(;void 0!==(S=S.get(u))&&!k;){const t=S.get(e);if(P+=1,void 0!==t){if(t===P)throw new RangeError("Cyclic object value");k=!0}void 0===S.get(u)&&(P=0)}if("function"==typeof _?I=_(t,I):I instanceof Date?I=y?.(I):"comma"===r&&(0,i.isArray)(I)&&(I=(0,n.maybe_map)(I,e=>e instanceof Date?y?.(e):e)),null===I){if(c)return p&&!b?p(t,l.encoder,w,"key",A):t;I=""}if("string"==typeof(O=I)||"number"==typeof O||"boolean"==typeof O||"symbol"==typeof O||"bigint"==typeof O||(0,n.is_buffer)(I)){if(p){const e=b?t:p(t,l.encoder,w,"key",A);return[v?.(e)+"="+v?.(p(I,l.encoder,w,"value",A))]}return[v?.(t)+"="+v?.(String(I))]}var O;const C=[];if(void 0===I)return C;let R;if("comma"===r&&(0,i.isArray)(I))b&&p&&(I=(0,n.maybe_map)(I,p)),R=[{value:I.length>0?I.join(",")||null:void 0}];else if((0,i.isArray)(_))R=_;else{const e=Object.keys(I);g&&e.sort(g),R=e}const B=f?String(t).replace(/\./g,"%2E"):String(t),x=s&&(0,i.isArray)(I)&&1===I.length?B+"[]":B;if(o&&(0,i.isArray)(I)&&0===I.length)return x+"[]";for(const t of R){const n="object"==typeof t&&void 0!==t.value?t.value:I[t];if(d&&null===n)continue;const l=m&&f?t.replace(/\./g,"%2E"):t;let S;S=(0,i.isArray)(I)?"function"==typeof r?r(x,l):x:x+(m?"."+l:"["+l+"]"),E.set(e,P);const k=new WeakMap([[u,E]]);a(C,h(n,S,r,s,o,c,d,f,"comma"===r&&b&&(0,i.isArray)(I)?null:p,_,g,m,y,A,v,b,w,k))}return C}},2880(e,t,r){"use strict";t.encode=t.has=void 0,t.is_buffer=function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},t.maybe_map=function(e,t){if((0,s.isArray)(e)){const r=[];for(const n of e)r.push(t(n));return r}return t(e)};const n=r(3157),s=r(8874);let i;t.has=(e,t)=>{const r=i??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return i=r,r(e,t)};const o=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();const a=1024;t.encode=(e,t,r,s,i)=>{if(0===e.length)return e;let c=e;if("symbol"==typeof e?c=Symbol.prototype.toString.call(e):"string"!=typeof e&&(c=String(e)),"iso-8859-1"===r)return escape(c).replace(/%u[0-9a-f]{4}/gi,e=>"%26%23"+Number.parseInt(e.slice(2),16)+"%3B");let l="";for(let e=0;e<c.length;){let t=Math.min((Math.floor(e/a)+1)*a,c.length);t<c.length&&c.codePointAt(t-1)>65535&&(t+=1);const r=c.length>=a?c.slice(e,t):c,s=[];for(let e=0;e<r.length;++e){let t=r.charCodeAt(e);45===t||46===t||95===t||126===t||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||i===n.RFC1738&&(40===t||41===t)?s[s.length]=r.charAt(e):t<128?s[s.length]=o[t]:t<2048?s[s.length]=o[192|t>>6]+o[128|63&t]:t<55296||t>=57344?s[s.length]=o[224|t>>12]+o[128|t>>6&63]+o[128|63&t]:(e+=1,t=65536+((1023&t)<<10|1023&r.charCodeAt(e)),s[s.length]=o[240|t>>18]+o[128|t>>12&63]+o[128|t>>6&63]+o[128|63&t])}l+=s.join(""),e=t}return l}},9462(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FallbackEncoder=void 0,t.observeJSONRequestBody=function(e,t){let n=r.get(e);return n||(n=new Set,r.set(e,n)),n.add(t),()=>{const n=r.get(e);n&&(n.delete(t),0===n.size&&r.delete(e))}};const r=new WeakMap;t.FallbackEncoder=({headers:e,body:t})=>{const n="object"==typeof t&&null!==t?r.get(t):void 0;let s;if(n&&0!==n.size){const e=[...n];s=JSON.stringify(t,function(t,r){let n=r;for(const r of e){const e=r.value(this,t,n);void 0!==e&&(n=e)}return n});for(const t of e)t.complete()}else s=JSON.stringify(t);return{bodyHeaders:{"content-type":"application/json"},body:s}}},2475(e,t,r){"use strict";t.createCanonicalResponseContext=function(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new n.OutputTextIndex}},t.getOutputText=s,t.ensureCanonicalOutputText=i,t.cloneResponse=function(e,t){e.canonicalSnapshot=void 0,e.outputTextLengths=new WeakMap,e.outputTextIndex=new n.OutputTextIndex;const r=structuredClone(t);return Object.getOwnPropertyDescriptor(r,"output_text")&&null!==r.output_text&&void 0!==r.output_text?0===r.output.length&&""===r.output_text&&(e.canonicalSnapshot=r):i(e,r),r},t.updateCachedOutputTextLength=function(e,t,r,n,s){const i=e.outputTextLengths.get(t);if(void 0!==i){const o=i-n.length+s.length;e.outputTextLengths.set(t,o),e.outputTextIndex.update(r,o)}},t.updateOutputText=function(e,t,r,n,i,a){if(n===i)return;const c=t.output[r];if(r===t.output.length-1&&(void 0===a||"message"===c?.type&&a===c.content.length-1))return void o(t,n,i);const l=function(e,t,r,n){if(void 0===r||"message"!==t?.type)return 0;if(r<t.content.length-r-1){let e=0;for(let n=0;n<r;n+=1){const r=t.content[n];"output_text"===r?.type&&(e+=r.text.length)}return e}let i=0;for(let e=r+1;e<t.content.length;e+=1){const r=t.content[e];"output_text"===r?.type&&(i+=r.text.length)}return(e.outputTextLengths.get(t)??s(e,t).length)-i-n.length}(e,c,a,i),u=e.outputTextIndex.prefixSum(r)+l;u+n.length!==t.output_text.length?t.output_text=t.output_text.slice(0,u)+i+t.output_text.slice(u+n.length):o(t,n,i)};const n=r(1917);function s(e,t){if("message"!==t.type)return"";let r="";for(const e of t.content)"output_text"===e.type&&(r+=e.text);return e.outputTextLengths.set(t,r.length),r}function i(e,t){if(e.canonicalSnapshot===t)return;const r=new n.OutputTextIndex;let i="";for(const n of t.output){const t=s(e,n);i+=t,r.append(t.length)}t.output_text=i,e.outputTextIndex=r,e.canonicalSnapshot=t}function o(e,t,r){0!==t.length?e.output_text=e.output_text.slice(0,e.output_text.length-t.length)+r:e.output_text+=r}},1917(e,t){"use strict";t.OutputTextIndex=void 0,t.OutputTextIndex=class{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(e){this.size===this.capacity&&this.grow();const t=this.size;this.size+=1,this.update(t,e)}update(e,t){if(!Number.isSafeInteger(e)||e<0||e>=this.size)throw new RangeError(`missing output at index ${e}`);let r=this.capacity+e;const n=t-(this.values[r]??0);if(0!==n)for(;r>=1;)this.values[r]=(this.values[r]??0)+n,r=Math.floor(r/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw new RangeError(`missing output at index ${e}`);let t=this.capacity,r=this.capacity+e,n=0;for(;t<r;)t%2==1&&(n+=this.values[t]??0,t+=1),r%2==1&&(r-=1,n+=this.values[r]??0),t=Math.floor(t/2),r=Math.floor(r/2);return n}grow(){const e=this.capacity;this.capacity*=2;const t=Array.from({length:2*this.capacity},()=>0);for(let r=0;r<this.size;r+=1)t[this.capacity+r]=this.values[e+r]??0;for(let e=this.capacity-1;e>0;e-=1)t[e]=(t[2*e]??0)+(t[2*e+1]??0);this.values=t}}},7695(e,t,r){"use strict";t.createResponseContext=function(){return(0,i.createCanonicalResponseContext)()},t.accumulateResponseWithContext=function(e,t,r,w=!1,E){const I=function(e){let t;try{t=Object.getOwnPropertyDescriptor(e,"type")}catch{return v()}const r=t?.value;if("string"!=typeof r||!A.has(r))return v();const n=new Map([["type",r]]);if("response.output_item.added"===r||"response.output_item.done"===r||"response.content_part.added"===r||"response.content_part.done"===r||"response.shell_call_command.added"===r||"response.shell_call_command.delta"===r||"response.shell_call_command.done"===r||(0,s.hasOwn)(g,r))try{for(const t of b){const r=Object.getOwnPropertyDescriptor(e,t);n.set(t,r?Reflect.get(e,t,e):void 0)}"response.output_item.done"===r?n.set("item",structuredClone(Reflect.get(e,"item",e))):"response.content_part.added"!==r&&"response.content_part.done"!==r||n.set("part",structuredClone(Reflect.get(e,"part",e)))}catch{return v()}return new Proxy(e,{get:(e,t)=>n.has(t)?n.get(t):Reflect.get(e,t,e)})}(e);if(E&&"keepalive"!==I.type&&E(I),!t){if("response.created"!==I.type)throw new n.OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${I.type}`);return _(r,I.response)}return function(e,t,r){if("response.output_item.done"===e.type)return void function(e,t){const r=l(t,e.output_index),i=e.item;if(h(r,e.type),h(i,e.type),!(0,s.hasOwn)(i,"type")||r.type!==i.type)throw new n.OpenAIError(`expected output item type '${r.type}', got '${i.type}'`);const o=(0,s.hasOwn)(r,"id")?r.id:void 0,a=(0,s.hasOwn)(i,"id")?i.id:void 0;if(o!==a)throw new n.OpenAIError(`expected output item id '${o}', got '${a}'`);if(u(r)&&u(i)&&r.call_id!==i.call_id)throw new n.OpenAIError(`expected output item call_id '${r.call_id}', got '${i.call_id}'`)}(e,t);if(r&&("response.shell_call_command.added"===e.type||"response.shell_call_command.delta"===e.type||"response.shell_call_command.done"===e.type)){const r=l(t,e.output_index);if(!(0,s.hasOwn)(r,"type")||"shell_call"!==r.type)throw new n.OpenAIError(`expected output item type 'shell_call', got '${r.type}'`);return}if("response.content_part.added"!==e.type&&"response.content_part.done"!==e.type&&!(0,s.hasOwn)(g,e.type))return;const i=e;if(!(0,s.hasOwn)(e,"item_id")||"string"!=typeof i.item_id||0===i.item_id.length)throw new n.OpenAIError(`expected a non-empty item_id for ${e.type}`);const o=l(t,i.output_index),a=(0,s.hasOwn)(o,"id")?o.id:void 0;if(a!==i.item_id)throw new n.OpenAIError(`expected item_id '${a}', got '${i.item_id}'`);const c=function(e){return"response.content_part.added"===e.type||"response.content_part.done"===e.type?"reasoning_text"===e.part.type?"reasoning":"message":g[e.type]}(i);if(o.type!==c)throw new n.OpenAIError(`expected output item type '${c}', got '${o.type}'`)}(I,t,w),function(e,t,r){switch(e.type){case"response.output_item.added":{c(t.output,e.output_index,"output");const n=function(e,t){const r=o.get(e);if(r&&r.snapshot===t&&r.output===t.output&&r.length===t.output.length)return r;const n=p(t);return o.set(e,n),n}(r,t),s=structuredClone(e.item),a=h(s,e.type);d(n.identities,a),"message"===s.type&&(0,i.ensureCanonicalOutputText)(r,t),t.output.push(s),f(n.identities,a),n.length=t.output.length;const l=(0,i.getOutputText)(r,s);return r.canonicalSnapshot===t&&r.outputTextIndex.append(l.length),l&&(t.output_text+=l),!0}case"response.output_item.done":{const n=l(t,e.output_index),s=(0,i.getOutputText)(r,n),o=e.item;"message"!==n.type&&"message"!==o.type||(0,i.ensureCanonicalOutputText)(r,t),t.output[e.output_index]=o;const a=(0,i.getOutputText)(r,o);return r.canonicalSnapshot===t&&r.outputTextIndex.update(e.output_index,a.length),(0,i.updateOutputText)(r,t,e.output_index,s,a),!0}default:return!1}}(I,t,r)||function(e,t,r){if("response.content_part.added"===e.type){const n=l(t,e.output_index),{type:s}=n,{part:o}=e;if("message"===s&&"reasoning_text"!==o.type){c(n.content,e.content_index,"content");const s=o;"output_text"===s.type&&(0,i.ensureCanonicalOutputText)(r,t),n.content.push(s),"output_text"===s.type&&((0,i.updateCachedOutputTextLength)(r,n,e.output_index,"",s.text),(0,i.updateOutputText)(r,t,e.output_index,"",s.text,e.content_index))}else if("reasoning"===s&&"reasoning_text"===o.type){const t=n.content??[];c(t,e.content_index,"content"),n.content||(n.content=t),t.push(o)}return!0}return!1}(I,t,r)||function(e,t,r){if("response.content_part.done"===e.type){const s=l(t,e.output_index),{part:o}=e;if("message"===s.type&&"reasoning_text"!==o.type){const n=m(s.content,e.content_index),a="output_text"===n.type?n.text:"",c=o;"output_text"!==n.type&&"output_text"!==c.type||(0,i.ensureCanonicalOutputText)(r,t),s.content[e.content_index]=c;const l="output_text"===c.type?c.text:"";(0,i.updateCachedOutputTextLength)(r,s,e.output_index,a,l),(0,i.updateOutputText)(r,t,e.output_index,a,l,e.content_index)}else if("reasoning"===s.type&&"reasoning_text"===o.type){const{content:t}=s;if(!t)throw new n.OpenAIError(`missing content at index ${e.content_index}`);m(t,e.content_index),t[e.content_index]=o}return!0}return!1}(I,t,r)||function(e,t,r){switch(e.type){case"response.output_text.delta":{const s=l(t,e.output_index);if("message"===s.type){const o=m(s.content,e.content_index);if("output_text"!==o.type)throw new n.OpenAIError(`expected content to be 'output_text', got ${o.type}`);const a=o.text;(0,i.ensureCanonicalOutputText)(r,t),o.text=a+e.delta,(0,i.updateCachedOutputTextLength)(r,s,e.output_index,a,o.text),e.output_index===t.output.length-1&&e.content_index===s.content.length-1?t.output_text+=e.delta:(0,i.updateOutputText)(r,t,e.output_index,a,o.text,e.content_index)}return!0}case"response.output_text.done":{const s=l(t,e.output_index);if("message"===s.type){const o=m(s.content,e.content_index);if("output_text"!==o.type)throw new n.OpenAIError(`expected content to be 'output_text', got ${o.type}`);const a=o.text;(0,i.ensureCanonicalOutputText)(r,t),o.text=e.text,(0,i.updateCachedOutputTextLength)(r,s,e.output_index,a,e.text),(0,i.updateOutputText)(r,t,e.output_index,a,e.text,e.content_index)}return!0}case"response.output_text.annotation.added":{const r=l(t,e.output_index);if("message"===r.type){const t=m(r.content,e.content_index);if("output_text"!==t.type)throw new n.OpenAIError(`expected content to be 'output_text', got ${t.type}`);a(t.annotations,e.annotation_index,"annotation",!0),t.annotations[e.annotation_index]=structuredClone(e.annotation)}return!0}default:return!1}}(I,t,r)||function(e,t){switch(e.type){case"response.refusal.delta":{const r=l(t,e.output_index);if("message"===r.type){const t=m(r.content,e.content_index);if("refusal"!==t.type)throw new n.OpenAIError(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}return!0}case"response.refusal.done":{const r=l(t,e.output_index);if("message"===r.type){const t=m(r.content,e.content_index);if("refusal"!==t.type)throw new n.OpenAIError(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}return!0}case"response.function_call_arguments.delta":{const r=l(t,e.output_index);return"function_call"===r.type&&(r.arguments+=e.delta),!0}case"response.function_call_arguments.done":{const r=l(t,e.output_index);return"function_call"===r.type&&(r.arguments=e.arguments),!0}case"response.custom_tool_call_input.delta":{const r=l(t,e.output_index);return"custom_tool_call"===r.type&&(r.input+=e.delta),!0}case"response.custom_tool_call_input.done":{const r=l(t,e.output_index);return"custom_tool_call"===r.type&&(r.input=e.input),!0}case"response.mcp_call_arguments.delta":{const r=l(t,e.output_index);return"mcp_call"===r.type&&(r.arguments+=e.delta),!0}case"response.mcp_call_arguments.done":{const r=l(t,e.output_index);return"mcp_call"===r.type&&(r.arguments=e.arguments),!0}default:return!1}}(I,t)||function(e,t){switch(e.type){case"response.shell_call_command.added":case"response.shell_call_command.done":{const r=l(t,e.output_index);if("shell_call"===r.type){const t="response.shell_call_command.added"===e.type;a(r.action.commands,e.command_index,"command",t),r.action.commands[e.command_index]=e.command}return!0}case"response.shell_call_command.delta":{const r=l(t,e.output_index);return"shell_call"===r.type&&(a(r.action.commands,e.command_index,"command"),r.action.commands[e.command_index]+=e.delta),!0}case"response.shell_call_output_content.delta":{const r=l(t,e.output_index);if("shell_call_output"===r.type){const n=y(t,r,e.command_index);n.stdout+=e.delta.stdout??"",n.stderr+=e.delta.stderr??""}return!0}case"response.shell_call_output_content.done":{const r=l(t,e.output_index);if("shell_call_output"===r.type){const n=m(e.output,0);y(t,r,e.command_index),r.output[e.command_index]=structuredClone(n)}return!0}default:return!1}}(I,t)||function(e,t){switch(e.type){case"response.reasoning_text.delta":{const r=l(t,e.output_index);if("reasoning"===r.type){if(!r.content)throw new n.OpenAIError(`missing content at index ${e.content_index}`);const t=m(r.content,e.content_index);if("reasoning_text"!==t.type)throw new n.OpenAIError(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}return!0}case"response.reasoning_text.done":{const r=l(t,e.output_index);if("reasoning"===r.type){if(!r.content)throw new n.OpenAIError(`missing content at index ${e.content_index}`);const t=m(r.content,e.content_index);if("reasoning_text"!==t.type)throw new n.OpenAIError(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}return!0}case"response.reasoning_summary_part.added":{const r=l(t,e.output_index);return"reasoning"===r.type&&(c(r.summary,e.summary_index,"content"),r.summary.push(structuredClone(e.part))),!0}case"response.reasoning_summary_part.done":{const r=l(t,e.output_index);return"reasoning"===r.type&&(m(r.summary,e.summary_index),r.summary[e.summary_index]=structuredClone(e.part)),!0}case"response.reasoning_summary_text.delta":{const r=l(t,e.output_index);return"reasoning"===r.type&&(m(r.summary,e.summary_index).text+=e.delta),!0}case"response.reasoning_summary_text.done":{const r=l(t,e.output_index);return"reasoning"===r.type&&(m(r.summary,e.summary_index).text=e.text),!0}default:return!1}}(I,t)||function(e,t){switch(e.type){case"response.code_interpreter_call_code.delta":{const r=l(t,e.output_index);return"code_interpreter_call"===r.type&&(r.code=(r.code??"")+e.delta),!0}case"response.code_interpreter_call_code.done":{const r=l(t,e.output_index);return"code_interpreter_call"===r.type&&(r.code=e.code),!0}case"response.code_interpreter_call.in_progress":{const r=l(t,e.output_index);return"code_interpreter_call"===r.type&&(r.status="in_progress"),!0}case"response.code_interpreter_call.interpreting":{const r=l(t,e.output_index);return"code_interpreter_call"===r.type&&(r.status="interpreting"),!0}case"response.code_interpreter_call.completed":{const r=l(t,e.output_index);return"code_interpreter_call"===r.type&&(r.status="completed"),!0}default:return!1}}(I,t)||function(e,t){switch(e.type){case"response.file_search_call.in_progress":{const r=l(t,e.output_index);return"file_search_call"===r.type&&(r.status="in_progress"),!0}case"response.file_search_call.searching":{const r=l(t,e.output_index);return"file_search_call"===r.type&&(r.status="searching"),!0}case"response.file_search_call.completed":{const r=l(t,e.output_index);return"file_search_call"===r.type&&(r.status="completed"),!0}case"response.web_search_call.in_progress":{const r=l(t,e.output_index);return"web_search_call"===r.type&&(r.status="in_progress"),!0}case"response.web_search_call.searching":{const r=l(t,e.output_index);return"web_search_call"===r.type&&(r.status="searching"),!0}case"response.web_search_call.completed":{const r=l(t,e.output_index);return"web_search_call"===r.type&&(r.status="completed"),!0}default:return!1}}(I,t)||function(e,t){switch(e.type){case"response.image_generation_call.in_progress":{const r=l(t,e.output_index);return"image_generation_call"===r.type&&(r.status="in_progress"),!0}case"response.image_generation_call.generating":{const r=l(t,e.output_index);return"image_generation_call"===r.type&&(r.status="generating"),!0}case"response.image_generation_call.completed":{const r=l(t,e.output_index);return"image_generation_call"===r.type&&(r.status="completed"),!0}case"response.mcp_call.in_progress":{const r=l(t,e.output_index);return"mcp_call"===r.type&&(r.status="in_progress"),!0}case"response.mcp_call.completed":{const r=l(t,e.output_index);return"mcp_call"===r.type&&(r.status="completed"),!0}case"response.mcp_call.failed":{const r=l(t,e.output_index);return"mcp_call"===r.type&&(r.status="failed"),!0}default:return!1}}(I,t)?t:function(e){switch(e.type){case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":return!0;default:return!1}}(I)?_(r,I.response):function(e){switch(e.type){case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":return!0;default:return!1}}(I)?t:v()};const n=r(2154),s=r(4737),i=r(2475),o=new WeakMap;function a(e,t,r,i=!1){if(!Array.isArray(e)||!Number.isSafeInteger(t)||t<0||t>e.length||(t===e.length?!i||t in e:!(0,s.hasOwn)(e,t)))throw new n.OpenAIError(`missing ${r} at index ${t}`)}function c(e,t,r){if(t!==e.length)throw new n.OpenAIError(`missing ${r} at index ${t}`);a(e,t,r,!0)}function l(e,t){a(e.output,t,"output");const r=e.output[t];if(!r)throw new n.OpenAIError(`missing output at index ${t}`);return r}function u(e){return"function_call"===e.type||"custom_tool_call"===e.type||"shell_call"===e.type||"shell_call_output"===e.type}function h(e,t){if(!(0,s.hasOwn)(e,"type")||"string"!=typeof e.type)throw new n.OpenAIError(`expected an own output item type for ${t}`);const r="function_call"===e.type||"custom_tool_call"===e.type,i=[];if((0,s.hasOwn)(e,"id")){if("string"!=typeof e.id||0===e.id.length)throw new n.OpenAIError(`expected a non-empty output item id for ${t}`);i.push(`id:${e.id}`)}else if(!r)throw new n.OpenAIError(`expected a non-empty output item id for ${t}`);if(u(e)){if(!(0,s.hasOwn)(e,"call_id")||"string"!=typeof e.call_id||0===e.call_id.length)throw new n.OpenAIError(`expected a non-empty output item call_id for ${t}`);i.push(`call:${e.type}:${e.call_id}`)}return i}function d(e,t){for(const r of t)if(e.has(r))throw new n.OpenAIError(`duplicate output item identity '${r}'`)}function f(e,t){d(e,t);for(const r of t)e.add(r)}function p(e){const t={snapshot:e,output:e.output,length:e.output.length,identities:new Set};for(let r=0;r<e.output.length;r+=1){const n=l(e,r);f(t.identities,h(n,"response snapshot"))}return t}function _(e,t){const r=(0,i.createCanonicalResponseContext)(),n=(0,i.cloneResponse)(r,t),s=p(n);return e.canonicalSnapshot=r.canonicalSnapshot,e.outputTextLengths=r.outputTextLengths,e.outputTextIndex=r.outputTextIndex,o.set(e,s),n}const g={"response.output_text.delta":"message","response.output_text.done":"message","response.output_text.annotation.added":"message","response.refusal.delta":"message","response.refusal.done":"message","response.function_call_arguments.delta":"function_call","response.function_call_arguments.done":"function_call","response.custom_tool_call_input.delta":"custom_tool_call","response.custom_tool_call_input.done":"custom_tool_call","response.mcp_call_arguments.delta":"mcp_call","response.mcp_call_arguments.done":"mcp_call","response.mcp_call.in_progress":"mcp_call","response.mcp_call.completed":"mcp_call","response.mcp_call.failed":"mcp_call","response.shell_call_output_content.delta":"shell_call_output","response.shell_call_output_content.done":"shell_call_output","response.reasoning_text.delta":"reasoning","response.reasoning_text.done":"reasoning","response.reasoning_summary_part.added":"reasoning","response.reasoning_summary_part.done":"reasoning","response.reasoning_summary_text.delta":"reasoning","response.reasoning_summary_text.done":"reasoning","response.code_interpreter_call_code.delta":"code_interpreter_call","response.code_interpreter_call_code.done":"code_interpreter_call","response.code_interpreter_call.in_progress":"code_interpreter_call","response.code_interpreter_call.interpreting":"code_interpreter_call","response.code_interpreter_call.completed":"code_interpreter_call","response.file_search_call.in_progress":"file_search_call","response.file_search_call.searching":"file_search_call","response.file_search_call.completed":"file_search_call","response.web_search_call.in_progress":"web_search_call","response.web_search_call.searching":"web_search_call","response.web_search_call.completed":"web_search_call","response.image_generation_call.in_progress":"image_generation_call","response.image_generation_call.generating":"image_generation_call","response.image_generation_call.completed":"image_generation_call","response.image_generation_call.partial_image":"image_generation_call","response.mcp_list_tools.in_progress":"mcp_list_tools","response.mcp_list_tools.completed":"mcp_list_tools","response.mcp_list_tools.failed":"mcp_list_tools"};function m(e,t){a(e,t,"content");const r=e[t];if(!r)throw new n.OpenAIError(`missing content at index ${t}`);return r}function y(e,t,r){const n=e.output.find(e=>"shell_call"===e.type&&e.call_id===t.call_id);for(n?a(n.action.commands,r,"command"):a(t.output,r,"content",!0);t.output.length<=r;)t.output.push({stdout:"",stderr:"",outcome:{type:"exit",exit_code:0}});return m(t.output,r)}const A=new Set(["response.output_item.added","response.output_item.done","response.content_part.added","response.content_part.done","response.output_text.delta","response.output_text.done","response.output_text.annotation.added","response.refusal.delta","response.refusal.done","response.function_call_arguments.delta","response.function_call_arguments.done","response.custom_tool_call_input.delta","response.custom_tool_call_input.done","response.mcp_call_arguments.delta","response.mcp_call_arguments.done","response.shell_call_command.added","response.shell_call_command.done","response.shell_call_command.delta","response.shell_call_output_content.delta","response.shell_call_output_content.done","response.reasoning_text.delta","response.reasoning_text.done","response.reasoning_summary_part.added","response.reasoning_summary_part.done","response.reasoning_summary_text.delta","response.reasoning_summary_text.done","response.code_interpreter_call_code.delta","response.code_interpreter_call_code.done","response.code_interpreter_call.in_progress","response.code_interpreter_call.interpreting","response.code_interpreter_call.completed","response.file_search_call.in_progress","response.file_search_call.searching","response.file_search_call.completed","response.web_search_call.in_progress","response.web_search_call.searching","response.web_search_call.completed","response.image_generation_call.in_progress","response.image_generation_call.generating","response.image_generation_call.completed","response.mcp_call.in_progress","response.mcp_call.completed","response.mcp_call.failed","response.created","response.queued","response.in_progress","response.completed","response.failed","response.incomplete","response.audio.delta","response.audio.done","response.audio.transcript.delta","response.audio.transcript.done","response.image_generation_call.partial_image","response.mcp_list_tools.in_progress","response.mcp_list_tools.completed","response.mcp_list_tools.failed","keepalive","error"]);function v(e){throw new n.OpenAIError("Unhandled response stream event: unknown")}const b=["item_id","output_index","content_index","annotation_index","command_index","summary_index"]},6786(e,t){"use strict";function r(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}Object.defineProperty(t,"__esModule",{value:!0}),t.getDefaultFetch=function(){if("undefined"!=typeof fetch)return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")},t.makeReadableStream=r,t.ReadableStreamFrom=function(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return r({start(){},async pull(e){const{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})},t.ReadableStreamToAsyncIterable=function(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}},t.CancelReadableStream=async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(e[Symbol.asyncIterator]().return?.());const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}},6854(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toFile=async function(e,t,r){if((0,n.checkFileSupport)(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&s(e))(e=await e)){const s={...r,type:r?.type??e.type,lastModified:r?.lastModified??e.lastModified};return e instanceof File?((e,t,r)=>(null==t||t===e.name)&&!((e,t)=>null!=t?.type&&t.type!==e.type||null!=t?.lastModified&&t.lastModified!==e.lastModified||null!=t?.endings)(e,r))(e,t,r)?e:(0,n.makeFile)([e],t??e.name,s):(0,n.makeFile)([await e.arrayBuffer()],t??e.name,s)}if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const s=await e.blob();t??(t=(0,n.getName)(e));const o=void 0===r?.type&&s.type?{...r,type:s.type}:r;return(0,n.makeFile)(await i(s),t,o)}const o=await i(e);if(t??(t=(0,n.getName)(e)),void 0===r?.type){const e=o.find(e=>"object"==typeof e&&"type"in e&&!!e.type);e&&(r={...r,type:e.type})}return(0,n.makeFile)(o,t,r)};const n=r(1598),s=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function i(e){const t=[];if("string"==typeof e||ArrayBuffer.isView(e)||(0,n.isArrayBuffer)(e))t.push(e);else if(s(e))t.push(e instanceof Blob?e:new Blob([await e.arrayBuffer()],{type:e.type}));else{if(!(0,n.isAsyncIterable)(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";return`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(", ")}]`}(e)}`)}for await(const r of e)t.push(...await i(r))}return t}},6316(e,t){"use strict";t.__classPrivateFieldSet=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},t.__classPrivateFieldGet=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)},t.__exportStar=function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)},t.__importStar=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=s(e),o=0;o<i.length;o++)"default"!==i[o]&&r(t,e,i[o]);return n(t,e),t};var r=Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]},n=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t},s=function(e){return(s=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t})(e)}},1598(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createForm=t.multipartFormRequestOptions=t.maybeMultipartFormRequestOptions=t.isAsyncIterable=t.checkFileSupport=void 0,t.toStreamingFile=function(e,t,r){if("string"!=typeof t||!t)throw new TypeError("toStreamingFile requires a non-empty file name");const n=r?.type;return n&&I(n),{[o]:!0,data:e,name:t,...n?{type:n}:{}}},t.makeFile=a,t.getName=c,t.isArrayBuffer=d;const n=r(3098),s=r(6786),i=r(4545),o=Symbol("brand.privateStreamingFile");function a(e,r,n){return(0,t.checkFileSupport)(),new File(e,r??"unknown_file",n)}function c(e,t){if("object"!=typeof e||null===e)return;const r="name"in e?e.name:void 0,n=r&&String(r)||"filename"in e&&e.filename&&String(e.filename);if(n)return!1===t?.stripFilename?u(n):l(n);const s="url"in e&&e.url&&String(e.url);if(s)try{return l(new URL(s).pathname)}catch{return l(s)}const i="path"in e&&e.path&&String(e.path);return i?l(i):void 0}function l(e){return e.split(/[\\/]/).pop()||void 0}function u(e){const t=e.replace(/\\/g,"/");if(t.startsWith("/")||/^[A-Za-z]:/.test(t)||t.split("/").includes(".."))throw new TypeError("Upload file name must be a safe relative path without parent directory segments");return t}t.checkFileSupport=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&Number.parseInt(e.versions.node.split("."),10)<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":""))}};const h=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get;function d(e){try{return void 0!==h?.call(e)}catch{return!1}}t.isAsyncIterable=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],t.maybeMultipartFormRequestOptions=async(e,r,n)=>A(e.body)?y(e.body)?v(e,n):{...e,body:await(0,t.createForm)(e.body,r,n)}:e,t.multipartFormRequestOptions=async(e,r,n)=>y(e.body)?v(e,n):{...e,body:await(0,t.createForm)(e.body,r,n)};const f=new WeakMap;t.createForm=async(e,t,r={})=>{if(!await function(e){const t="function"==typeof e?e:e.fetch,r=f.get(t);if(r)return r;const n=(async()=>{try{let e;if("Response"in t)e=t.Response;else{const r=await t("data:,");await r.arrayBuffer(),e=r.constructor}const r=new FormData;return r.toString()!==await new e(r).text()}catch{return!0}})();return f.set(t,n),n}(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>O(n,e,t,r))),n};const p=e=>e instanceof Blob,_=e=>"object"==typeof e&&null!==e&&"getReader"in e&&"function"==typeof e.getReader,g=e=>"object"==typeof e&&null!==e&&o in e,m=e=>"object"==typeof e&&null!==e&&(e instanceof Response||(0,t.isAsyncIterable)(e)||_(e)||g(e)||p(e)),y=e=>{if(g(e)||(0,t.isAsyncIterable)(e)||_(e))return!0;if(Array.isArray(e))return e.some(y);if(e&&"object"==typeof e&&!p(e)&&!(e instanceof Response))for(const t of Object.keys(e))if(y(e[t]))return!0;return!1},A=e=>{if(m(e))return!0;if(Array.isArray(e))return e.some(A);if(e&&"object"==typeof e)for(const t of Object.keys(e))if(A(e[t]))return!0;return!1},v=(e,t={})=>{const r=function*(e){if(e&&"object"==typeof e)for(const[t,r]of Object.entries(e))yield*b(t,r)}(e.body),o=!1===t.stripFilenames?new WeakMap:void 0,a=o?((e,t)=>{const r=[];for(const n of e)m(n.value)&&!t.has(n.value)&&t.set(n.value,w(n.value,{stripFilenames:!1})),r.push(n);return r})(r,o):r,c=`openai-${Math.random().toString(36).slice(2)}`,l=(0,s.ReadableStreamFrom)(async function*(e,t,r,n){for await(const{key:s,value:o}of e){if(m(o)){const e=n?.get(o)??w(o,r),a=E(o);yield(0,i.encodeUTF8)(`--${t}\r\n`),yield(0,i.encodeUTF8)(`Content-Disposition: form-data; name="${k(s)}"; filename="${k(e)}"\r\nContent-Type: ${a}\r\n\r\n`),yield*P(S(o))}else yield(0,i.encodeUTF8)(`--${t}\r\n`),yield(0,i.encodeUTF8)(`Content-Disposition: form-data; name="${k(s)}"\r\n\r\n${String(o)}`);yield(0,i.encodeUTF8)("\r\n")}yield(0,i.encodeUTF8)(`--${t}--\r\n`)}(a,c,t,o));return{...e,body:l,headers:(0,n.buildHeaders)([{"content-type":`multipart/form-data; boundary=${c}`},e.headers])}};function*b(e,t){if(void 0!==t){if(null==t)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof t||"number"==typeof t||"boolean"==typeof t||m(t))yield{key:e,value:t};else if(Array.isArray(t))for(const r of t)yield*b(e+"[]",r);else{if("object"!=typeof t)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`);for(const[r,n]of Object.entries(t))yield*b(`${e}[${r}]`,n)}}}function w(e,t){if(g(e)){const{name:r}=e;if("string"!=typeof r||!r)throw new TypeError("Streaming upload file name must be a non-empty string");return!1===t.stripFilenames?u(r):l(r)??"unknown_file"}return c(e,{stripFilename:t.stripFilenames})??"unknown_file"}function E(e){let t;return g(e)||p(e)?({type:t}=e):e instanceof Response&&(t=e.headers.get("content-type")??void 0),I(t||"application/octet-stream")}function I(e){if("string"!=typeof e)throw new TypeError("Streaming upload content type must be a string");for(let t=0;t<e.length;t+=1){const r=e.codePointAt(t)??0;if(r<=31||127===r)throw new TypeError("Streaming upload content type must not contain control characters")}return e}function S(e){return g(e)?e.data:e}async function*P(e){if("string"==typeof e)yield(0,i.encodeUTF8)(e);else if(ArrayBuffer.isView(e))yield new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(d(e))yield new Uint8Array(e);else if(e instanceof Response)yield*P(e.body||await e.blob());else if(e instanceof Blob)"function"==typeof e.stream?yield*P(e.stream()):yield new Uint8Array(await e.arrayBuffer());else if(_(e))for await(const t of(0,s.ReadableStreamToAsyncIterable)(e))yield*P(t);else{if(!(0,t.isAsyncIterable)(e))throw new TypeError(`Invalid streaming file chunk: ${String(e)}`);for await(const t of e)yield*P(t)}}function k(e){return Array.from(e,e=>{const t=e.codePointAt(0)??0;return t<=31||127===t||'"'===e||"\\"===e?encodeURIComponent(e):e}).join("")}const O=async(e,r,n,i)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${r}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)e.append(r,String(n));else if(n instanceof Response){const t=await n.blob();e.append(r,a([t],c(n,{stripFilename:i.stripFilenames}),{type:t.type}))}else if((0,t.isAsyncIterable)(n))e.append(r,a([await new Response((0,s.ReadableStreamFrom)(n)).blob()],c(n,{stripFilename:i.stripFilenames})));else if(p(n)){const t=c(n,{stripFilename:i.stripFilenames});void 0===t?e.append(r,n):e.append(r,n,t)}else if(Array.isArray(n)){const t=await Promise.all(n.map(async e=>{const t=new FormData;return await O(t,r+"[]",e,i),t}));for(const r of t)if(r)for(const[t,n]of r.entries())e.append(t,n)}else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map(([t,n])=>O(e,`${r}[${t}]`,n,i)))}}}},4737(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(6316);n.__exportStar(r(8874),t),n.__exportStar(r(7739),t),n.__exportStar(r(3209),t),n.__exportStar(r(6048),t),n.__exportStar(r(5263),t),n.__exportStar(r(8233),t),n.__exportStar(r(2602),t)},7739(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toFloat32Array=t.fromBase64=t.toBase64=void 0;const n=r(144),s=r(4545);t.toBase64=e=>{if(!e)return"";if(void 0!==globalThis.Buffer)return globalThis.Buffer.from(e).toString("base64");if("string"==typeof e&&(e=(0,s.encodeUTF8)(e)),"undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,e));throw new n.OpenAIError("Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined")},t.fromBase64=e=>{if(void 0!==globalThis.Buffer){const t=globalThis.Buffer.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if("undefined"!=typeof atob){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}throw new n.OpenAIError("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},t.toFloat32Array=e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");if(t.length%Float32Array.BYTES_PER_ELEMENT!==0)throw new RangeError("Invalid base64-encoded float32 array: byte length must be a multiple of 4");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),r=t.length,n=new Uint8Array(r);for(let e=0;e<r;e++)n[e]=t.charCodeAt(e);return Array.from(new Float32Array(n.buffer))}}},4545(e,t){"use strict";let r,n;t.encodeUTF8=function(e){let t;return(r??(t=new globalThis.TextEncoder,r=t.encode.bind(t)))(e)},t.decodeUTF8=function(e){let t;return(n??(t=new globalThis.TextDecoder,n=t.decode.bind(t)))(e)}},3209(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.readEnv=void 0,t.readEnv=e=>{try{if(void 0!==globalThis.process)return globalThis.process.env?.[e]?.trim()||void 0;if(void 0!==globalThis.Deno)return globalThis.Deno.env?.get?.(e)?.trim()||void 0}catch{return}}},6048(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatRequestDetails=t.parseLogLevel=void 0,t.loggerFor=l,t.isSensitiveQueryParameter=h,t.isSensitiveHeader=f,t.redactURL=p;const n=r(8874),s={off:0,error:200,warn:300,info:400,debug:500};function i(){}function o(e,t,r){return!t||s[e]>s[r]?i:t[e].bind(t)}t.parseLogLevel=(e,t,r)=>{if(e)return(0,n.hasOwn)(s,e)?e:void l(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(s))}`)};const a={error:i,warn:i,info:i,debug:i};let c=new WeakMap;function l(e){const t=e.logger,r=e.logLevel??"off";if(!t)return a;const n=c.get(t);if(n&&n[0]===r)return n[1];const s={error:o("error",t,r),warn:o("warn",t,r),info:o("info",t,r),debug:o("debug",t,r)};return c.set(t,[r,s]),s}const u=new Set(["apikey","accesstoken","refreshtoken","sessiontoken","sessionid","idtoken","authtoken","authorization","token","password","clientsecret","xamzsecuritytoken","xamzsignature","xamzcredential"]);function h(e){const t=e.toLowerCase().replace(/[-_]/gu,"");return u.has(t)||u.has(t.replace(/^x/u,""))}const d=new Set(["authorization","proxy-authorization","api-key","x-api-key","x-amz-security-token","cookie","set-cookie","x-session-token","x-session-id","x-auth-token","x-id-token"]);function f(e){return d.has(e.toLowerCase().replace(/_/gu,"-"))||h(e)}function p(e){const t=new URL(e);t.username="",t.password="",t.hash="";for(const e of t.searchParams.keys())h(e)&&t.searchParams.set(e,"***");return t.href}t.formatRequestDetails=e=>{if(e.options){if(e.options={...e.options},delete e.options.headers,e.options.path){const t=e.options.path,r=new URL(p(new URL(t,"https://redacted.invalid").href));e.options.path="https://redacted.invalid"===r.origin?`${t.startsWith("/")?"/":""}${r.pathname.slice(1)}${r.search}`:r.href}e.options.query&&(e.options.query=Object.fromEntries(Object.entries(e.options.query).map(([e,t])=>[e,h(e)?"***":t])))}return e.url&&(e.url=p(e.url)),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,f(e)?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e}},8491(e,t,r){"use strict";t.path=t.wy=void 0;const n=r(144);function s(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const i=Object.freeze(Object.create(null));t.wy=(e=s)=>function(t,...r){if(1===t.length)return t[0];let s=!1;const o=[];let a="";for(let n=0;n<t.length;n+=1)if(n in t){const c=t[n];/[?#]/.test(c)&&(s=!0);const l=r[n];let u=(s?encodeURIComponent:e)(""+l);n!==r.length&&(null==l||"object"==typeof l&&l.toString===Object.getPrototypeOf(Object.getPrototypeOf(l.hasOwnProperty??i)??i)?.toString)&&(u=l+"",o.push({start:a.length+c.length,length:u.length,error:`Value of type ${Object.prototype.toString.call(l).slice(8,-1)} is not a valid path parameter`})),a+=c+(n===r.length?"":u)}const c=a.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let u;for(;null!==(u=l.exec(c));)o.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(o.sort((e,t)=>e.start-t.start),o.length>0){let e=0,t="";for(const r of o){const n=" ".repeat(r.start-e),s="^".repeat(r.length);e=r.start+r.length,t+=n+s}throw new n.OpenAIError(`Path parameters result in path with invalid segments:\n${o.map(e=>e.error).join("\n")}\n${a}\n${t}`)}return a},t.path=(0,t.wy)(s)},2602(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.stringifyQuery=function(e){return n.stringify(e,{arrayFormat:"brackets"})};const n=r(6316).__importStar(r(3092))},8233(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sleep=void 0,t.sleep=e=>new Promise(t=>setTimeout(t,e))},5263(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.uuid4=void 0,t.uuid4=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return t.uuid4=e.randomUUID.bind(e),e.randomUUID();const r=new Uint8Array(1),n=e?()=>e.getRandomValues(r)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^n()&15>>+e/4).toString(16))}},8874(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.safeJSON=t.maybeCoerceBoolean=t.maybeCoerceFloat=t.maybeCoerceInteger=t.coerceBoolean=t.coerceFloat=t.coerceInteger=t.validatePositiveInteger=t.ensurePresent=t.isReadonlyArray=t.isArray=t.isAbsoluteURL=void 0,t.maybeObj=function(e){return"object"!=typeof e?{}:e??{}},t.isEmptyObj=function(e){if(!e)return!0;for(const t in e)return!1;return!0},t.hasOwn=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.isObj=function(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)};const n=r(144),s=/^[a-z][a-z0-9+.-]*:/i;t.isAbsoluteURL=e=>s.test(e),t.isArray=e=>(t.isArray=Array.isArray,(0,t.isArray)(e)),t.isReadonlyArray=t.isArray,t.ensurePresent=e=>{if(null==e)throw new n.OpenAIError(`Expected a value to be given but received ${e} instead.`);return e},t.validatePositiveInteger=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new n.OpenAIError(`${e} must be an integer`);if(t<0)throw new n.OpenAIError(`${e} must be a positive integer`);return t},t.coerceInteger=e=>{if("number"==typeof e)return Math.round(e);if("string"==typeof e)return parseInt(e,10);throw new n.OpenAIError(`Could not coerce ${e} (type: ${typeof e}) into a number`)},t.coerceFloat=e=>{if("number"==typeof e)return e;if("string"==typeof e)return parseFloat(e);throw new n.OpenAIError(`Could not coerce ${e} (type: ${typeof e}) into a number`)},t.coerceBoolean=e=>"boolean"==typeof e?e:"string"==typeof e?"true"===e:Boolean(e),t.maybeCoerceInteger=e=>{if(null!=e)return(0,t.coerceInteger)(e)},t.maybeCoerceFloat=e=>{if(null!=e)return(0,t.coerceFloat)(e)},t.maybeCoerceBoolean=e=>{if(null!=e)return(0,t.coerceBoolean)(e)},t.safeJSON=e=>{try{return JSON.parse(e)}catch(e){return}}},4778(e,t,r){"use strict";var n,s,i,o,a,c,l,u,h,d,f,p;t.AbstractChatCompletionRunner=void 0;const _=r(6316),g=r(2154),m=r(5263),y=r(1489),A=r(9277),v=r(528),b=r(8615),w=10;function E(e){if(!(0,A.isAssistantMessage)(e))return e;const t={role:"assistant"};return null!=e.audio&&(t.audio={id:e.audio.id}),void 0!==e.content&&(t.content=e.content),null!=e.function_call&&(t.function_call=e.function_call),void 0!==e.name&&(t.name=e.name),null!=e.refusal&&(t.refusal=e.refusal),void 0!==e.tool_calls&&(t.tool_calls=e.tool_calls.map(e=>"custom"===e.type?{id:e.id,type:e.type,custom:{input:e.custom.input,name:e.custom.name}}:{id:e.id,type:e.type,function:{arguments:e.function.arguments,name:e.function.name}})),t}class I extends v.EventStream{constructor(){super(...arguments),n.add(this),this._chatCompletions=[],i.set(this,!1),o.set(this,!1),this.messages=[]}_addChatCompletion(e){_.__classPrivateFieldSet(this,i,!this.controller.signal.aborted,"f"),function(e){for(const t of e.choices)for(const e of t.message.tool_calls??[])e.id||(e.id=`call_${(0,m.uuid4)()}`)}(e),this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0,r=!0){if(r&&!("content"in e)&&(e.content=null),this.messages.push(e),t)if(this._emit("message",e),(0,A.isToolMessage)(e)&&e.content)this._emit("functionToolCallResult",e.content);else if((0,A.isAssistantMessage)(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionToolCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new g.OpenAIError("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),_.__classPrivateFieldGet(this,n,"m",a).call(this)}async finalMessage(){return await this.done(),_.__classPrivateFieldGet(this,n,"m",c).call(this)}async finalFunctionToolCall(){return await this.done(),_.__classPrivateFieldGet(this,n,"m",l).call(this)}async finalFunctionToolCallResult(){return await this.done(),_.__classPrivateFieldGet(this,n,"m",u).call(this)}async totalUsage(){return await this.done(),_.__classPrivateFieldGet(this,n,"m",h).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){_.__classPrivateFieldGet(this,o,"f")&&_.__classPrivateFieldGet(this,n,"m",d).call(this);const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=_.__classPrivateFieldGet(this,n,"m",c).call(this);t&&this._emit("finalMessage",t);const r=_.__classPrivateFieldGet(this,n,"m",a).call(this);r&&this._emit("finalContent",r);const s=_.__classPrivateFieldGet(this,n,"m",l).call(this);s&&this._emit("finalFunctionToolCall",s);const i=_.__classPrivateFieldGet(this,n,"m",u).call(this);null!=i&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",_.__classPrivateFieldGet(this,n,"m",h).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),_.__classPrivateFieldGet(s,s,"m",f).call(s,t);const n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion((0,y.parseChatCompletion)(n,t))}async _runChatCompletion(e,t,r){for(const e of t.messages)this._addMessage(e,!1,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r,a){const c="tool",{tool_choice:l="auto",stream:u,toolContext:h,...f}=t,m=h,A="string"!=typeof l&&"function"===l.type&&l?.function?.name,{maxChatCompletions:v=w,afterCompletion:I}=a||{},S=async e=>{null!=I&&(_.__classPrivateFieldSet(this,o,!0,"f"),await I(e,r),_.__classPrivateFieldGet(this,n,"m",d).call(this))},P=t.tools.map(e=>{if((0,y.isAutoParsableTool)(e)){if(!e.$callback)throw new g.OpenAIError("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),k=Object.create(null);for(const e of P)"function"===e.type&&(k[e.function.name||e.function.function.name]=e.function);const O="tools"in t?P.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(const e of t.messages)this._addMessage(e,!1,!1);let C=!1;const R=async e=>{const t=C;if(C=!1,"function"!==e.type)return{message:void 0,functionCalled:!1};const n=e.id,{name:i,arguments:o}=e.function,a=k[i];if(!a){const e=`Invalid tool_call: ${JSON.stringify(i)}. Available options are: ${Object.keys(k).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;return{message:{role:c,tool_call_id:n,content:e},functionCalled:!1}}if(A&&A!==i){const e=`Invalid tool_call: ${JSON.stringify(i)}. ${JSON.stringify(A)} requested. Please try again`;return{message:{role:c,tool_call_id:n,content:e},functionCalled:!1}}let l;if((0,b.isRunnableFunctionWithParse)(a)){let e;try{e=await a.parse(o)}catch(e){if(this.controller.signal.aborted)throw new g.APIUserAbortError;const t=e instanceof Error?e.message:String(e);return{message:{role:c,tool_call_id:n,content:t},functionCalled:!1}}if(this.controller.signal.aborted)throw new g.APIUserAbortError;l=await a.function(e,r,m)}else{if(this.controller.signal.aborted&&!t)throw new g.APIUserAbortError;l=await a.function(o,r,m)}const u=_.__classPrivateFieldGet(s,s,"m",p).call(s,l);return{message:{role:c,tool_call_id:n,content:u},functionCalled:!0}};for(let r=0;r<v;++r){const r=await this._createChatCompletion(e,{...f,tool_choice:l,tools:O,messages:this.messages.map(E)},a);C=this.controller.signal.aborted&&_.__classPrivateFieldGet(this,i,"f");const n=r.choices[0]?.message;if(!n)throw new g.OpenAIError("missing message in ChatCompletion response");if(!n.tool_calls?.length)return void await S(r);if(A||!1===t.parallel_tool_calls)for(const e of n.tool_calls){const t=await R(e);if(t.message&&this._addMessage(t.message),this.controller.signal.aborted)throw new g.APIUserAbortError;if(A&&t.functionCalled)return void await S(r)}else{const e=await Promise.allSettled(n.tool_calls.map(R));if(!this.controller.signal.aborted)for(const t of e)if("rejected"===t.status)throw t.reason;for(const t of e)"fulfilled"===t.status&&t.value.message&&this._addMessage(t.value.message);if(this.controller.signal.aborted)throw new g.APIUserAbortError}await S(r)}}}t.AbstractChatCompletionRunner=I,s=I,i=new WeakMap,o=new WeakMap,n=new WeakSet,a=function(){return _.__classPrivateFieldGet(this,n,"m",c).call(this).content??null},c=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if((0,A.isAssistantMessage)(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new g.OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant")},l=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if((0,A.isAssistantMessage)(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){const r=t.tool_calls[e];if("function"===r?.type)return r.function}}},u=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if((0,A.isToolMessage)(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},h=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},d=function(){if(this.controller.signal.aborted){const e=new g.APIUserAbortError;throw Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e}},f=function(e){if(null!=e.n&&e.n>1)throw new g.OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},p=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)}},7288(e,t,r){"use strict";var n,s,i,o,a,c,l,u,h,d,f,p,_,g,m,y,A,v,b,w,E,I,S,P,k,O,C,R,B,x;t.AssistantStream=void 0;const T=r(6316),N=r(3528),F=r(2154),M=r(528),L=r(4737),U=r(8006);class D extends M.EventStream{constructor(){super(...arguments),n.add(this),s.set(this,Object.create(null)),i.set(this,new Map),o.set(this,void 0),a.set(this,Object.create(null)),c.set(this,new Map),l.set(this,void 0),u.set(this,void 0),h.set(this,void 0),d.set(this,void 0),f.set(this,void 0),p.set(this,void 0),_.set(this,void 0),g.set(this,void 0),m.set(this,void 0),y.set(this,void 0)}[(s=new WeakMap,i=new WeakMap,o=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,_=new WeakMap,g=new WeakMap,m=new WeakMap,y=new WeakMap,n=new WeakSet,Symbol.asyncIterator)](){return this._createIterator(e=>{const t=t=>e(structuredClone(t));return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}static fromReadableStream(e){const t=new D;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();const r=N.Stream.fromReadableStream(e,this.controller);for await(const e of r)T.__classPrivateFieldGet(this,n,"m",A).call(this,e);if(r.controller.signal?.aborted)throw new F.APIUserAbortError;return this._addRun(T.__classPrivateFieldGet(this,n,"m",v).call(this))}toReadableStream(){return new N.Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){const s=new D;return s._run(()=>s._runToolAssistantStream(e,t,r,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}async _createToolAssistantStream(e,t,r,s){this._listenForAbort(s?.signal);const i={...r,stream:!0},o=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(const e of o)T.__classPrivateFieldGet(this,n,"m",A).call(this,e);if(o.controller.signal?.aborted)throw new F.APIUserAbortError;return this._addRun(T.__classPrivateFieldGet(this,n,"m",v).call(this))}static createThreadAssistantStream(e,t,r){const n=new D;return n._run(()=>n._threadAssistantStream(e,t,{...r,__metadata:{...r?.__metadata,helperMethod:"stream"}})),n}static createAssistantStream(e,t,r,n){const s=new D;return s._run(()=>s._runAssistantStream(e,t,r,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}currentEvent(){return(0,U.markAssistantStreamValueExternallyMutable)(T.__classPrivateFieldGet(this,g,"f")),T.__classPrivateFieldGet(this,g,"f")}currentRun(){return(0,U.markAssistantStreamValueExternallyMutable)(T.__classPrivateFieldGet(this,m,"f")),T.__classPrivateFieldGet(this,m,"f")}currentMessageSnapshot(){return(0,U.markAssistantStreamValueExternallyMutable)(T.__classPrivateFieldGet(this,l,"f")),T.__classPrivateFieldGet(this,l,"f")}currentRunStepSnapshot(){return(0,U.markAssistantStreamValueExternallyMutable)(T.__classPrivateFieldGet(this,y,"f")),T.__classPrivateFieldGet(this,y,"f")}async finalRunSteps(){return await this.done(),Object.values(T.__classPrivateFieldGet(this,s,"f"))}async finalMessages(){return await this.done(),Object.values(T.__classPrivateFieldGet(this,a,"f"))}async finalRun(){if(await this.done(),!T.__classPrivateFieldGet(this,h,"f"))throw new Error("Final run was not received.");return T.__classPrivateFieldGet(this,h,"f")}async _createThreadAssistantStream(e,t,r){this._listenForAbort(r?.signal);const s={...t,stream:!0},i=await e.createAndRun(s,{...r,signal:this.controller.signal});this._connected();for await(const e of i)T.__classPrivateFieldGet(this,n,"m",A).call(this,e);if(i.controller.signal?.aborted)throw new F.APIUserAbortError;return this._addRun(T.__classPrivateFieldGet(this,n,"m",v).call(this))}async _createAssistantStream(e,t,r,s){this._listenForAbort(s?.signal);const i={...r,stream:!0},o=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const e of o)T.__classPrivateFieldGet(this,n,"m",A).call(this,e);if(o.controller.signal?.aborted)throw new F.APIUserAbortError;return this._addRun(T.__classPrivateFieldGet(this,n,"m",v).call(this))}static accumulateDelta(e,t){return(0,U.accumulateAssistantStreamDelta)(e,t)}_addRun(e){return T.__classPrivateFieldGet(this,n,"m",k).call(this,"run",e),e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}}t.AssistantStream=D,A=function(e){if(this.ended)return;const{event:t,exposedEvent:r}=function(e){const t=Object.getOwnPropertyDescriptor(e,"event"),r=Object.getOwnPropertyDescriptor(e,"data"),n=Reflect.get(e,"event",e),s=Reflect.get(e,"data",e);let i=s;if("thread.message.created"===n||"thread.message.in_progress"===n||"thread.message.delta"===n||"thread.message.completed"===n||"thread.message.incomplete"===n||"thread.run.step.created"===n||"thread.run.step.in_progress"===n||"thread.run.step.delta"===n||"thread.run.step.completed"===n||"thread.run.step.failed"===n||"thread.run.step.cancelled"===n||"thread.run.step.expired"===n){const e=Object.getOwnPropertyDescriptor(s,"id");if(e&&"value"in e&&Reflect.get(s,"id",s)!==e.value){const t=e.value;i=new Proxy(s,{get:(e,r)=>"id"===r?t:Reflect.get(e,r,e)})}}return{event:Object.freeze({event:n,data:i}),exposedEvent:void 0!==t&&"value"in t&&t.value===n&&void 0!==r&&"value"in r&&r.value===s&&i===s?e:{event:n,data:i}}}(e);let i,c,u,h;switch(t.event){case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":i=T.__classPrivateFieldGet(this,n,"m",E).call(this,t),c=t.data;break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":u=T.__classPrivateFieldGet(this,n,"m",b).call(this,t),h=t.data}switch(T.__classPrivateFieldSet(this,g,r,"f"),T.__classPrivateFieldGet(this,n,"m",O).call(this,r),void 0!==i&&void 0!==c&&T.__classPrivateFieldGet(this,n,"m",I).call(this,c,i),void 0!==u&&void 0!==h&&T.__classPrivateFieldGet(this,n,"m",w).call(this,h,u),void 0===u&&void 0!==T.__classPrivateFieldGet(this,o,"f")&&T.__classPrivateFieldGet(this,y,"f")&&T.__classPrivateFieldGet(this,n,"m",w).call(this,T.__classPrivateFieldGet(this,y,"f"),T.__classPrivateFieldGet(this,o,"f")),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":T.__classPrivateFieldGet(this,n,"m",x).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{if(void 0===u)throw new F.OpenAIError("Received assistant run-step event without a canonical run-step ID");const e=T.__classPrivateFieldGet(this,s,"f")[u];e&&T.__classPrivateFieldGet(this,n,"m",w).call(this,e,u),T.__classPrivateFieldGet(this,n,"m",P).call(this,t,u),T.__classPrivateFieldGet(this,n,"m",w).call(this,t.data,u);const r=T.__classPrivateFieldGet(this,s,"f")[u];r&&T.__classPrivateFieldGet(this,n,"m",w).call(this,r,u);break}case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":if(void 0!==i&&T.__classPrivateFieldGet(this,l,"f")&&T.__classPrivateFieldGet(this,n,"m",I).call(this,T.__classPrivateFieldGet(this,l,"f"),i),T.__classPrivateFieldGet(this,n,"m",S).call(this,t),void 0!==i){T.__classPrivateFieldGet(this,n,"m",I).call(this,t.data,i);const e=T.__classPrivateFieldGet(this,a,"f")[i];e&&T.__classPrivateFieldGet(this,n,"m",I).call(this,e,i)}break;case"error":throw new F.APIError(void 0,t.data,void 0,void 0)}},v=function(){if(this.ended)throw new F.OpenAIError("stream has ended, this shouldn't happen");if(!T.__classPrivateFieldGet(this,h,"f"))throw new Error("Final run has not been received");return T.__classPrivateFieldGet(this,h,"f")},b=function(e){const t=Object.getOwnPropertyDescriptor(e.data,"id"),r=t&&"value"in t?t.value:void 0;if("string"!=typeof r||0===r.length)throw new F.OpenAIError("Received assistant run-step event with an invalid run-step ID");if("thread.run.step.delta"===e.event){const t=e.data.delta;if(t&&(0,L.hasOwn)(t,"id"))throw new F.OpenAIError("Run-step deltas must not contain an id field")}if("thread.run.step.created"===e.event){if(void 0!==T.__classPrivateFieldGet(this,o,"f"))throw new F.OpenAIError(`Received run-step creation for "${r}" before the active run step "${T.__classPrivateFieldGet(this,o,"f")}" reached a terminal state`);if((0,L.hasOwn)(T.__classPrivateFieldGet(this,s,"f"),r)||T.__classPrivateFieldGet(this,i,"f").has(r))throw new F.OpenAIError(`Received run-step creation for run step "${r}", which has already been created`);return T.__classPrivateFieldSet(this,o,r,"f"),T.__classPrivateFieldGet(this,i,"f").set(r,r),r}if(void 0!==T.__classPrivateFieldGet(this,o,"f")){if(r!==T.__classPrivateFieldGet(this,o,"f"))throw new F.OpenAIError(`Received ${e.event} for run step "${r}", which does not match the active run step "${T.__classPrivateFieldGet(this,o,"f")}"`);return r}if("thread.run.step.delta"===e.event){if(!(0,L.hasOwn)(T.__classPrivateFieldGet(this,s,"f"),r))throw new F.OpenAIError("Received a RunStepDelta before creation of a snapshot");throw new F.OpenAIError(`Received run-step delta for "${r}" with no active run step`)}if((0,L.hasOwn)(T.__classPrivateFieldGet(this,s,"f"),r)||T.__classPrivateFieldGet(this,i,"f").has(r))throw new F.OpenAIError(`Received run-step event for run step "${r}", which has already been created`);return T.__classPrivateFieldGet(this,i,"f").set(r,r),"thread.run.step.in_progress"===e.event&&T.__classPrivateFieldSet(this,o,r,"f"),r},w=function(e,t){const r=Object.getOwnPropertyDescriptor(e,"id"),n=r&&"value"in r?r.value:void 0;if("string"!=typeof n||0===n.length)throw new F.OpenAIError("Received assistant run-step event with an invalid run-step ID");const s=T.__classPrivateFieldGet(this,i,"f").get(n);if(void 0!==s&&s!==t)throw new F.OpenAIError(`Received run-step creation for run step "${n}", which has already been created`);T.__classPrivateFieldGet(this,i,"f").set(n,t)},E=function(e){const t=Object.getOwnPropertyDescriptor(e.data,"id"),r=t&&"value"in t?t.value:void 0;if("string"!=typeof r||0===r.length)throw new F.OpenAIError("Received assistant message event with an invalid message ID");if("thread.message.created"===e.event){if(T.__classPrivateFieldGet(this,l,"f"))throw new F.OpenAIError(`Received message creation for "${r}" before the active message "${T.__classPrivateFieldGet(this,u,"f")}" reached a terminal state`);if((0,L.hasOwn)(T.__classPrivateFieldGet(this,a,"f"),r)||T.__classPrivateFieldGet(this,c,"f").has(r))throw new F.OpenAIError(`Received message creation for message "${r}", which has already been created`);return T.__classPrivateFieldSet(this,u,r,"f"),T.__classPrivateFieldGet(this,c,"f").set(r,r),r}if(!T.__classPrivateFieldGet(this,l,"f")){if("thread.message.delta"===e.event)throw new F.OpenAIError("Received a delta with no existing snapshot (there should be one from message creation)");throw new F.OpenAIError("Received thread message event with no existing snapshot")}if(r!==T.__classPrivateFieldGet(this,u,"f"))throw new F.OpenAIError(`Received ${e.event} for message "${r}", which does not match the active message "${T.__classPrivateFieldGet(this,u,"f")}"`);return r},I=function(e,t){const r=Object.getOwnPropertyDescriptor(e,"id"),n=r&&"value"in r?r.value:void 0;if("string"!=typeof n||0===n.length)throw new F.OpenAIError("Received assistant message event with an invalid message ID");const s=T.__classPrivateFieldGet(this,c,"f").get(n);if(void 0!==s&&s!==t)throw new F.OpenAIError(`Received message creation for message "${n}", which has already been created`);T.__classPrivateFieldGet(this,c,"f").set(n,t)},S=function(e){const[t,r]=T.__classPrivateFieldGet(this,n,"m",R).call(this,e,T.__classPrivateFieldGet(this,l,"f"));if(T.__classPrivateFieldSet(this,l,t,"f"),!T.__classPrivateFieldGet(this,u,"f"))throw new F.OpenAIError("Received thread message event with no active message ID");T.__classPrivateFieldGet(this,a,"f")[T.__classPrivateFieldGet(this,u,"f")]=t;for(const e of r){const r=t.content[e.index];"text"===r?.type&&T.__classPrivateFieldGet(this,n,"m",k).call(this,"textCreated",r.text)}switch(e.event){case"thread.message.created":T.__classPrivateFieldSet(this,d,void 0,"f"),T.__classPrivateFieldSet(this,f,void 0,"f"),T.__classPrivateFieldGet(this,n,"m",k).call(this,"messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(T.__classPrivateFieldGet(this,n,"m",k).call(this,"messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if("text"===r.type&&r.text){const e=r.text,s=t.content[r.index];if(!s||"text"!==s.type)throw new Error("The snapshot associated with this text delta is not text or missing");T.__classPrivateFieldGet(this,n,"m",k).call(this,"textDelta",e,s.text)}if(r.index!==T.__classPrivateFieldGet(this,d,"f")){if(T.__classPrivateFieldGet(this,f,"f"))switch(T.__classPrivateFieldGet(this,f,"f").type){case"text":T.__classPrivateFieldGet(this,n,"m",k).call(this,"textDone",T.__classPrivateFieldGet(this,f,"f").text,T.__classPrivateFieldGet(this,l,"f"));break;case"image_file":T.__classPrivateFieldGet(this,n,"m",k).call(this,"imageFileDone",T.__classPrivateFieldGet(this,f,"f").image_file,T.__classPrivateFieldGet(this,l,"f"))}T.__classPrivateFieldSet(this,d,r.index,"f")}T.__classPrivateFieldSet(this,f,t.content[r.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==T.__classPrivateFieldGet(this,d,"f")){const t=e.data.content[T.__classPrivateFieldGet(this,d,"f")];if(t)switch(t.type){case"image_file":T.__classPrivateFieldGet(this,n,"m",k).call(this,"imageFileDone",t.image_file,T.__classPrivateFieldGet(this,l,"f"));break;case"text":T.__classPrivateFieldGet(this,n,"m",k).call(this,"textDone",t.text,T.__classPrivateFieldGet(this,l,"f"))}}T.__classPrivateFieldGet(this,l,"f")&&T.__classPrivateFieldGet(this,n,"m",k).call(this,"messageDone",e.data),T.__classPrivateFieldSet(this,d,void 0,"f"),T.__classPrivateFieldSet(this,f,void 0,"f"),T.__classPrivateFieldSet(this,l,void 0,"f"),T.__classPrivateFieldSet(this,u,void 0,"f")}},P=function(e,t){const r=T.__classPrivateFieldGet(this,n,"m",C).call(this,e,t);switch(T.__classPrivateFieldSet(this,y,r,"f"),e.event){case"thread.run.step.created":T.__classPrivateFieldSet(this,p,void 0,"f"),T.__classPrivateFieldSet(this,_,void 0,"f"),T.__classPrivateFieldGet(this,n,"m",k).call(this,"runStepCreated",e.data);break;case"thread.run.step.delta":{const t=e.data.delta;if(t.step_details&&"tool_calls"===t.step_details.type&&t.step_details.tool_calls&&"tool_calls"===r.step_details.type)for(const e of t.step_details.tool_calls)e.index===T.__classPrivateFieldGet(this,p,"f")?T.__classPrivateFieldGet(this,n,"m",k).call(this,"toolCallDelta",e,r.step_details.tool_calls[e.index]):(T.__classPrivateFieldGet(this,_,"f")&&T.__classPrivateFieldGet(this,n,"m",k).call(this,"toolCallDone",T.__classPrivateFieldGet(this,_,"f")),T.__classPrivateFieldSet(this,p,e.index,"f"),T.__classPrivateFieldSet(this,_,r.step_details.tool_calls[e.index],"f"),T.__classPrivateFieldGet(this,_,"f")&&T.__classPrivateFieldGet(this,n,"m",k).call(this,"toolCallCreated",T.__classPrivateFieldGet(this,_,"f")));T.__classPrivateFieldGet(this,n,"m",k).call(this,"runStepDelta",e.data.delta,r);break}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":T.__classPrivateFieldSet(this,y,void 0,"f"),T.__classPrivateFieldSet(this,o,void 0,"f"),"tool_calls"===e.data.step_details.type&&T.__classPrivateFieldGet(this,_,"f")&&T.__classPrivateFieldGet(this,n,"m",k).call(this,"toolCallDone",T.__classPrivateFieldGet(this,_,"f")),T.__classPrivateFieldGet(this,n,"m",k).call(this,"runStepDone",e.data,r),T.__classPrivateFieldSet(this,p,void 0,"f"),T.__classPrivateFieldSet(this,_,void 0,"f")}},k=function(e,...t){if(this._hasListeners(e))for(const e of t)(0,U.markAssistantStreamValueExternallyMutable)(e);this._emit(e,...t)},O=function(e){T.__classPrivateFieldGet(this,n,"m",k).call(this,"event",e)},C=function(e,t){switch(e.event){case"thread.run.step.created":return T.__classPrivateFieldGet(this,s,"f")[t]=e.data,e.data;case"thread.run.step.delta":{const r=T.__classPrivateFieldGet(this,s,"f")[t];if(!r)throw new Error("Received a RunStepDelta before creation of a snapshot");const n=e.data.delta;if(n){if((0,L.hasOwn)(n,"id"))throw new F.OpenAIError("Run-step deltas must not contain an id field");const e=(0,U.accumulateAssistantStreamDelta)(r,n,!0);T.__classPrivateFieldGet(this,s,"f")[t]=e}return T.__classPrivateFieldGet(this,s,"f")[t]}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":T.__classPrivateFieldGet(this,s,"f")[t]=e.data}if(T.__classPrivateFieldGet(this,s,"f")[t])return T.__classPrivateFieldGet(this,s,"f")[t];throw new Error("No snapshot available")},R=function(e,t){const r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":{if(!t)throw new Error("Received a delta with no existing snapshot (there should be one from message creation)");const s=e.data;if(s.delta.content){(0,U.assertSafeAssistantStreamDelta)(s.delta);const e=!(0,U.isAssistantStreamValueExternallyMutable)(t),i=(0,U.createAssistantStreamArrayDeltaCommit)(t.content,s.delta.content,"content",e);for(const i of s.delta.content)if((0,L.hasOwn)(t.content,i.index)){const r=t.content[i.index];t.content[i.index]=T.__classPrivateFieldGet(this,n,"m",B).call(this,i,r,e)}else(0,U.defineAssistantStreamArrayEntry)(t.content,i.index,i),r.push(i);i()}return[t,r]}case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return["thread.message.in_progress"===e.event?t:e.data,r];throw new Error("Received thread message event with no existing snapshot")}throw new Error("Tried to accumulate a non-message event")},B=function(e,t,r){return(0,U.accumulateAssistantStreamDelta)(t,e,r)},x=function(e){switch(T.__classPrivateFieldSet(this,m,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.cancelling":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":T.__classPrivateFieldSet(this,h,e.data,"f"),T.__classPrivateFieldGet(this,_,"f")&&T.__classPrivateFieldGet(this,n,"m",k).call(this,"toolCallDone",T.__classPrivateFieldGet(this,_,"f")),T.__classPrivateFieldSet(this,p,void 0,"f"),T.__classPrivateFieldSet(this,_,void 0,"f")}}},7460(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatCompletionRunner=void 0;const n=r(4778),s=r(9277);class i extends n.AbstractChatCompletionRunner{static runTools(e,t,r){const n=new i,s={...r,__metadata:{...r?.__metadata,helperMethod:"runTools"}};return n._run(()=>n._runTools(e,t,n,s)),n}_addMessage(e,t=!0,r=!0){super._addMessage(e,t,r),t&&(0,s.isAssistantMessage)(e)&&e.content&&this._emit("content",e.content)}}t.ChatCompletionRunner=i},8634(e,t,r){"use strict";var n,s,i,o,a,c,l,u,h,d,f,p,_,g,m;Object.defineProperty(t,"__esModule",{value:!0}),t.ChatCompletionStream=void 0,t.makeChatCompletionReadableStreamMessageChunk=function(e,t,r){const n={type:"message",message:t,...r?{tool_call_ids:r}:{}};return{id:e.id,choices:[],created:e.created,model:e.model,object:`${O}${JSON.stringify(n)}`}};const y=r(6316),A=r(438),v=r(2154),b=r(9462),w=r(5263),E=r(8874),I=r(1489),S=r(3528),P=r(4778);function k(e){try{return(0,A.partialParse)(e)}catch(t){if(t instanceof A.MalformedJSON||t instanceof SyntaxError)return(0,I.parseResponseFormatContent)({type:"json_schema",$parseRaw:void 0},e);throw t}}const O="chat.completion.chunk.message:";function C(e){return"type"in e&&"message"===e.type&&"message"in e||"object"in e&&"string"==typeof e.object&&e.object.startsWith(O)}function R(e){return"type"in e?e:JSON.parse(e.object.slice(30))}const B=128,x=128,T=67108864;function N(){return{bytes:0,depth:0,fragments:0,work:0,escaped:!1,has_non_whitespace:!1,in_string:!1,last_parsed_bytes:0,pending_high_surrogate:!1}}function F(e,t,r,n){if(t.fragments>=65536)throw new v.OpenAIError("Chat completion stream exceeded its structured JSON fragment limit");let s=0,{depth:i,escaped:o,has_non_whitespace:a,in_string:c}=e,l=!1,u=!0;for(const h of r){const r=s,d=h.codePointAt(0);if(u&&e.pending_high_surrogate&&d>=56320&&d<=57343?s+=1:s+=d<=127?1:d<=2047?2:d<=65535?3:4,u=!1,t.bytes+s>16777216)throw new v.OpenAIError("Chat completion stream exceeded its structured JSON byte limit");if(n&&n.work+s>T)throw n.work+=r,new v.OpenAIError("Chat completion stream exceeded its structured JSON parse-work limit");if(" "!==h&&"\n"!==h&&"\r"!==h&&"\t"!==h&&(a=!0),c)o?o=!1:"\\"===h?o=!0:'"'===h&&(c=!1,l||(l=0===i));else if('"'===h)c=!0;else if("{"===h||"["===h){if(i+=1,i>128)throw new v.OpenAIError("Chat completion stream exceeded its structured JSON nesting depth limit")}else("}"===h||"]"===h)&&i>0&&(i-=1,l||(l=0===i))}if(e.bytes+=s,e.fragments+=1,e.depth=i,e.escaped=o,e.has_non_whitespace=a,e.in_string=c,r.length>0){const t=r.codePointAt(r.length-1)??0;e.pending_high_surrogate=t>=55296&&t<=56319}if(t.bytes+=s,t.fragments+=1,n&&(n.work+=s),!a||0===s)return!1;const h=Math.max(1024,Math.floor(e.last_parsed_bytes/2));return!(e.bytes>1024&&!l&&e.bytes-e.last_parsed_bytes<h)}function M(e,t){return!(t.work+e.bytes>T||(t.work+=e.bytes,e.work+=e.bytes,e.last_parsed_bytes=e.bytes,0))}function L(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r){let r=Object.getPrototypeOf(e);for(let e=0;null!==r;e+=1){if(e>=128||Object.getOwnPropertyDescriptor(r,t))throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");r=Object.getPrototypeOf(r)}return}if(!("value"in r)||"string"!=typeof r.value&&null!==r.value&&void 0!==r.value)throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");return r.value}function U(e){const t=Object.getOwnPropertyDescriptor(e,"message");if(!t||!("value"in t)||"object"!=typeof t.value||null===t.value)throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}function D(e,t,r,n){const s=Object.getOwnPropertyDescriptor(e,t);if(!s){let r=Object.getPrototypeOf(e);for(let e=0;null!==r;e+=1){if(e>=128||Object.getOwnPropertyDescriptor(r,t))throw new v.OpenAIError(`Chat completion stream contains an unsafe snapshot ${n} collection`);r=Object.getPrototypeOf(r)}return}if(!("value"in s)||!Array.isArray(s.value))throw new v.OpenAIError(`Chat completion stream contains an unsafe snapshot ${n} collection`);const i=Object.getOwnPropertyDescriptor(s.value,"length");if(!i||!("value"in i)||!Number.isSafeInteger(i.value)||i.value>r)throw new v.OpenAIError(`Chat completion stream exceeded its snapshot ${n} limit`);return s.value}function $(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(r){if(!("value"in r))throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");return r.value}}function j(e,t,r,n){const s=Object.getOwnPropertyDescriptor(e,"length"),i=s&&"value"in s?s.value:void 0;if("number"!=typeof i||!Number.isSafeInteger(i)||i<0||i>t)throw new v.OpenAIError(`Chat completion stream exceeded its snapshot ${r} limit`);const o=[];o.length=i;for(let t=0;t<i;t+=1){const r=Object.getOwnPropertyDescriptor(e,t);if(r){if(!("value"in r))throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");o[t]=n(r.value,t)}}return o}function H(e,t,r){const n={bytes:0,depth:0,fragments:0,work:0,escaped:!1,has_non_whitespace:!1,in_string:!1,last_parsed_bytes:0,pending_high_surrogate:!1},s=t??{bytes:0,fragments:0,work:0};if(F(n,s,e,r),!M(n,s))throw new v.OpenAIError("Chat completion stream exceeded its structured JSON parse-work limit");return e}function G(e){const t=Object.getOwnPropertyDescriptor(e,"type"),r=Object.getOwnPropertyDescriptor(e,"function");if(!(t&&"value"in t&&"function"===t.value&&r&&"value"in r))return;if("object"!=typeof r.value||null===r.value)return;const n=Object.getOwnPropertyDescriptor(r.value,"name");return n&&"value"in n&&"string"==typeof n.value&&0!==n.value.length?{type:"function",name:n.value}:void 0}function Q(e,t){const r=G(e);if(!r||r.name!==t.name||r.type!==t.type)throw new v.OpenAIError("Chat completion stream contains a changed tool call identity")}function q(e,t){return Object.prototype.propertyIsEnumerable.call(t,"__proto__")&&!(0,E.hasOwn)(e,"__proto__")&&Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(e,t)}function W(e,t=[]){const r=Object.getOwnPropertyDescriptors(e);for(const n of t){const t=r[n];(t||n in e)&&(r[n]={value:t&&"value"in t?t.value:Reflect.get(e,n,e),enumerable:t?.enumerable??!1,configurable:t?.configurable??!0,writable:!(!t||!("writable"in t))&&t.writable})}return Object.create(Object.getPrototypeOf(e),r)}const K=4096,X=JSON.stringify,z=Symbol("omitted serialized parser value"),Y=Symbol("unsafe serialized parser value");function J(e,t){const r=new WeakSet,n=e=>!(!Number.isSafeInteger(e)||e<0||t.bytes+e>1048576||(t.bytes+=e,0)),s=(e,i)=>{if(i>64||t.nodes>=K)return Y;if(t.nodes+=1,void 0===e||"function"==typeof e||"symbol"==typeof e)return z;if("bigint"==typeof e)return Y;if(null===e||"boolean"==typeof e||"number"==typeof e){const t=X(e);return"string"==typeof t&&n(t.length)?t:Y}if("string"==typeof e)return n(6*e.length+2)?X(e):Y;if("object"!=typeof e||r.has(e))return Y;const o=Array.isArray(e),a=Object.getPrototypeOf(e);if(o&&a!==Array.prototype||!o&&null!==a&&a!==Object.prototype)return Y;for(let t=e;null!==t;t=Object.getPrototypeOf(t)){const e=Object.getOwnPropertyDescriptor(t,"toJSON");if(e){if(!("value"in e)||"function"==typeof e.value)return Y;break}}r.add(e);try{if(!n(2))return Y;if(o){const r=Object.getOwnPropertyDescriptor(e,"length"),o=r&&"value"in r?r.value:void 0;if("number"!=typeof o||!Number.isSafeInteger(o)||o<0||o>K-t.nodes)return Y;const a=[];for(let r=0;r<o;r+=1){const o=String(r),c=Object.getOwnPropertyDescriptor(e,o);if(!c){if(Object.getOwnPropertyDescriptor(Array.prototype,o)||Object.getOwnPropertyDescriptor(Object.prototype,o))return Y;if(t.nodes+=1,!n(4))return Y;a.push("null");continue}if(!("value"in c))return Y;const l=s(c.value,i+1);if(l===Y)return l;a.push(l===z?"null":l)}return`[${a.join(",")}]`}const r=Reflect.ownKeys(e);if(r.length>K-t.nodes)return Y;const a=[];for(const t of r){if("string"!=typeof t)continue;const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return Y;if(r.enumerable){if(!("value"in r))return Y;a.push([t,r.value])}}a.sort(([e],[t])=>e===t?0:e<t?-1:1);const c=[];for(const[e,t]of a){const r=s(t,i+1);if(r===Y)return r;if(r!==z){if(!n(6*e.length+3))return Y;c.push(`${X(e)}:${r}`)}}return`{${c.join(",")}}`}finally{r.delete(e)}};try{const t=s(e,0);return"string"==typeof t?t:void 0}catch{return}}function V(e,t,r,n){const s=Object.getOwnPropertyDescriptor(t,"$parseRaw"),i=Object.getOwnPropertyDescriptor(r,n);if(!(s&&"value"in s&&"function"==typeof s.value&&i&&"value"in i))return;const o=J(i.value,{nodes:0,bytes:0});void 0!==o&&e.set(t,o)}function Z(e,t,r,n,s){const i=t&&e.get(t),o=Object.getOwnPropertyDescriptor(r,n);return void 0!==i&&void 0!==o&&"value"in o&&J(s,{nodes:0,bytes:0})===i}function ee(e,t){return e&&"value"in e?{...e,value:t}:{configurable:!0,enumerable:!0,writable:!0,value:t}}function te(e,t,r){for(const n of r){const r=e[n];(r||n in t)&&(e[n]=r&&"value"in r?{...r,value:void 0}:{configurable:r?.configurable??!0,enumerable:r?.enumerable??!1,writable:!1,value:void 0})}}function re(e){const t=e.source??{type:e.type,..."function"===e.type?{function:{}}:{}},r=Object.getOwnPropertyDescriptors(t);if(r.type=ee(r.type,e.type),"function"!==e.type||!e.function)return r.function&&(r.function=ee(r.function,void 0)),te(r,t,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(t),r);const n=r.function,s=n&&"value"in n&&"object"==typeof n.value&&null!==n.value?n.value:{},i=Object.getOwnPropertyDescriptors(s);return i.name=ee(i.name,e.function.name),i.strict=ee(i.strict,e.function.strict),r.function=ee(n,Object.create(Object.getPrototypeOf(s),i)),e.function.schemaMatches||te(r,t,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(t),r)}function ne(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r||!("value"in r))return;const{value:n}=r;return"object"==typeof n&&null!==n?n:void 0}class se extends P.AbstractChatCompletionRunner{constructor(e){super(),n.add(this),s.set(this,void 0),i.set(this,void 0),o.set(this,void 0),a.set(this,void 0),c.set(this,void 0),l.set(this,void 0),y.__classPrivateFieldSet(this,s,e,"f"),y.__classPrivateFieldSet(this,i,new Set,"f"),y.__classPrivateFieldSet(this,o,[],"f"),y.__classPrivateFieldSet(this,c,!1,"f");const t=e?.tools,r=t&&Object.getOwnPropertyDescriptor(t,"length"),u=r&&"value"in r?r.value:void 0;if(t&&"number"==typeof u&&Number.isSafeInteger(u)&&u>=0)for(let e=0;e<Math.min(u,x);e+=1){const r=Object.getOwnPropertyDescriptor(t,String(e));if(!r||!("value"in r))continue;const n=r.value;if((0,I.isChatCompletionFunctionTool)(n)&&((0,I.isAutoParsableTool)(n)||!0===n.function.strict)){y.__classPrivateFieldSet(this,c,!0,"f");break}}y.__classPrivateFieldSet(this,l,{bytes:0,fragments:0,work:0},"f")}get currentChatCompletionSnapshot(){return y.__classPrivateFieldGet(this,a,"f")}static fromReadableStream(e){const t=new se(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const n=new se(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,__metadata:{...r?.__metadata,helperMethod:"stream"}})),n}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal);const i={...t,stream:!0};y.__classPrivateFieldSet(this,s,i,"f"),y.__classPrivateFieldGet(this,n,"m",u).call(this);const o=function(e){const t=W(e);if(e.tools){const r=[],n=Object.getOwnPropertyDescriptor(e.tools,"length"),s=n&&"value"in n?n.value:void 0,i="number"==typeof s&&Number.isSafeInteger(s)&&s>=0?Math.min(s,x):0;for(let t=0;t<i;t+=1){const n=Object.getOwnPropertyDescriptor(e.tools,String(t));if(!n||!("value"in n)){r.length=t+1;continue}const s=n.value,i=W(s,["type","$brand","$parseRaw","$callback","function"]),o=Object.getOwnPropertyDescriptors(i);if((0,I.isChatCompletionFunctionTool)(i)){const e=o.function;o.function={...e&&"value"in e?e:{configurable:!0,enumerable:!0,writable:!0},value:W(i.function,["name","strict"])}}r[t]=Object.create(Object.getPrototypeOf(s),o)}t.tools=r}return e.response_format&&(t.response_format=W(e.response_format,["type","$brand","$parseRaw"])),t}(i);y.__classPrivateFieldSet(this,s,o,"f"),y.__classPrivateFieldSet(this,c,o.tools?.some(e=>(0,I.isChatCompletionFunctionTool)(e)&&((0,I.isAutoParsableTool)(e)||!0===e.function.strict))??!1,"f");const a=i.tools||i.response_format?function(e,t,r){const n=new WeakMap,s=new WeakMap;if(e.tools)for(let r=0;r<e.tools.length&&r<x;r+=1){const i=ne(e.tools,String(r)),o=t.tools?.[r];if(i&&o){n.set(i,o);const e=ne(o,"function");e&&V(s,o,e,"parameters")}}let i,o,a,c;t.response_format&&V(s,t.response_format,t.response_format,"json_schema");let l=[],u=new WeakMap,h=new Map,d=new WeakMap;return(0,b.observeJSONRequestBody)(e,{value(r,f,p){if(!i&&""===f&&"object"==typeof p&&null!==p)return i=p,o=void 0,a=void 0,c=void 0,l=[],u=new WeakMap,h=new Map,void(d=new WeakMap);if(r===i&&"response_format"===f){if("object"==typeof p&&null!==p){a=p;const n=ne(r,f);c={source:n===e.response_format?t.response_format:void 0,schemaMatches:!1}}return}if(r===i&&"tools"===f)return Array.isArray(p)?(o=new Proxy(p,{get(e,t){const r=Reflect.get(e,t,e);if("string"==typeof t){const e=Number(t);Number.isSafeInteger(e)&&e>=0&&e<x&&String(e)===t&&h.set(e,"object"==typeof r&&null!==r?r:void 0)}return r}}),o):void 0;if(r===o){const e=Number(f);if(!Number.isSafeInteger(e)||e<0||e>=x||"object"!=typeof p||null===p)return;const t=h.get(e),r={source:t?n.get(t):void 0};return l[e]=r,void u.set(p,r)}const _=u.get(r);if(_){if("type"===f&&"string"==typeof p)_.type=p;else if("function"===f&&"object"==typeof p&&null!==p){const e={source:_.source,schemaMatches:!1};_.function=e,d.set(p,e)}return}if(r===a&&c)return void("type"===f&&"string"==typeof p?c.type=p:"json_schema"===f&&(c.schemaMatches=Z(s,c.source,r,f,p)));const g=d.get(r);g&&("name"===f&&"string"==typeof p?g.name=p:"strict"===f&&"boolean"==typeof p?g.strict=p:"parameters"===f&&(g.schemaMatches=Z(s,g.source,r,f,p)))},complete(){if(!i)return;const e=W(t);if(o){const t=[];for(let e=0;e<l.length;e+=1){const r=l[e];r&&(t[e]=re(r))}e.tools=t}else delete e.tools;c?e.response_format=function(e){const t=e.source??{type:e.type},r=Object.getOwnPropertyDescriptors(t);return r.type=ee(r.type,e.type),"json_schema"===e.type&&e.source&&e.schemaMatches||te(r,t,["$brand","$parseRaw"]),Object.create(Object.getPrototypeOf(t),r)}(c):delete e.response_format,r(e),i=void 0,o=void 0,a=void 0,c=void 0,l=[],u=new WeakMap,h=new Map,d=new WeakMap}})}(i,o,e=>{y.__classPrivateFieldSet(this,s,e,"f"),y.__classPrivateFieldSet(this,c,e.tools?.some(e=>(0,I.isChatCompletionFunctionTool)(e)&&((0,I.isAutoParsableTool)(e)||!0===e.function.strict))??!1,"f")}):void 0,l=await e.chat.completions.create(i,{...r,signal:this.controller.signal}).finally(a);this._connected();for await(const e of l)y.__classPrivateFieldGet(this,n,"m",d).call(this,e);if(l.controller.signal?.aborted)throw new v.APIUserAbortError;return this._addChatCompletion(y.__classPrivateFieldGet(this,n,"m",g).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),y.__classPrivateFieldGet(this,n,"m",u).call(this),this._connected();const r=S.Stream.fromReadableStream(e,this.controller);let s;for await(const e of r){if("error"in e&&(0,E.hasOwn)(e,"error")&&"object"==typeof e.error&&null!==e.error)throw new v.APIError(void 0,e.error,void 0,void 0);if(C(e)){const t=R(e);if(y.__classPrivateFieldGet(this,a,"f")){const e=y.__classPrivateFieldGet(this,a,"f").choices[0]?.message.tool_calls;for(const[r,n]of t.tool_call_ids?.entries()??[]){const t=e?.[r];t&&n&&(t.id=n)}this._addChatCompletion(y.__classPrivateFieldGet(this,n,"m",g).call(this)),s=void 0}this._addMessage(t.message);continue}const t=e;s&&t.id&&s!==t.id&&this._addChatCompletion(y.__classPrivateFieldGet(this,n,"m",g).call(this)),y.__classPrivateFieldGet(this,n,"m",d).call(this,t),t.id&&(s=t.id)}if(r.controller.signal?.aborted)throw new v.APIUserAbortError;if(y.__classPrivateFieldGet(this,a,"f"))return this._addChatCompletion(y.__classPrivateFieldGet(this,n,"m",g).call(this));const i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new v.OpenAIError("request ended without sending any chunks")}[(s=new WeakMap,i=new WeakMap,o=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,n=new WeakSet,u=function(){this.ended||(y.__classPrivateFieldSet(this,i,new Set,"f"),y.__classPrivateFieldSet(this,a,void 0,"f"),y.__classPrivateFieldSet(this,l,{bytes:0,fragments:0,work:0},"f"))},h=function(e){let t=y.__classPrivateFieldGet(this,o,"f")[e.index];return t||(t={content_done:!1,content_parse_state:void 0,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null,tool_call_parse_states:new Map,tool_call_identities:new Map},y.__classPrivateFieldGet(this,o,"f")[e.index]=t,t)},d=function(e){if(this.ended)return;const t=new WeakMap,r=y.__classPrivateFieldGet(this,n,"m",m).call(this,e,t);this._emit("chunk",e,r);for(const i of e.choices){const e=t.get(i),o=r.choices[e?.index??i.index],a=e?.tool_calls??[],{delta:l}=i,u=(0,I.isParseableResponseFormat)(y.__classPrivateFieldGet(this,s,"f")?.response_format),d=u||y.__classPrivateFieldGet(this,c,"f"),_=d?U(o):o.message,g=d?L(_,"refusal"):_.refusal,m=!g&&u?L(_,"content"):_.content;null!=l?.content&&"assistant"===_.role&&m&&(this._emit("content",l.content,m),this._emit("content.delta",{delta:l.content,snapshot:m,parsed:_.parsed})),null!=l?.refusal&&"assistant"===_.role&&g&&this._emit("refusal.delta",{delta:l.refusal,snapshot:g}),null!=i.logprobs?.content&&"assistant"===_.role&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:o.logprobs?.content??[]}),null!=i.logprobs?.refusal&&"assistant"===_.role&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});const A=y.__classPrivateFieldGet(this,n,"m",h).call(this,o);o.finish_reason&&(y.__classPrivateFieldGet(this,n,"m",p).call(this,o),null!=A.current_tool_call_index&&y.__classPrivateFieldGet(this,n,"m",f).call(this,o,A.current_tool_call_index));for(const e of a)A.current_tool_call_index!==e.index&&(y.__classPrivateFieldGet(this,n,"m",p).call(this,o),null!=A.current_tool_call_index&&y.__classPrivateFieldGet(this,n,"m",f).call(this,o,A.current_tool_call_index)),A.current_tool_call_index=e.index;for(const e of a){const t=_.tool_calls?.[e.index];if(t?.type)if("function"===t.type){const r=A.tool_call_identities.get(e.index);let n;if(r?.parseable){const e=L(t.function,"arguments");if("string"!=typeof e)throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");n=e}else n=t.function.arguments;this._emit("tool_calls.function.arguments.delta",{name:t.function.name,index:e.index,arguments:n,parsed_arguments:t.function.parsed_arguments,arguments_delta:e.arguments_delta})}else"custom"!==t.type&&oe(t)}}},f=function(e,t){const r=y.__classPrivateFieldGet(this,n,"m",h).call(this,e);if(r.done_tool_calls.has(t))return;const i=y.__classPrivateFieldGet(this,c,"f")?U(e):e.message,o=i.tool_calls?.[t];if(!o)throw new Error("no tool call snapshot");const l=r.tool_call_identities.get(t);if(l&&Q(o,l),!o.type)throw new Error("tool call snapshot missing `type`");if("function"===o.type){const i=y.__classPrivateFieldGet(this,s,"f")?.tools?.find(e=>(0,I.isChatCompletionFunctionTool)(e)&&e.function.name===o.function.name);let c,l=null;if((0,I.isAutoParsableTool)(i)||!0===i?.function.strict){y.__classPrivateFieldGet(this,a,"f")&&y.__classPrivateFieldGet(this,n,"m",_).call(this,y.__classPrivateFieldGet(this,a,"f"));const e=L(o.function,"arguments");if("string"!=typeof e)throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");c=e}else c=o.function.arguments;(0,I.isAutoParsableTool)(i)?l=i.$parseRaw(H(c)):i?.function.strict&&(l=(0,I.parseResponseFormatContent)({type:"json_schema",$parseRaw:void 0},H(c))),e.finish_reason&&r.done_tool_calls.add(t),this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:t,arguments:c,parsed_arguments:l})}else o.type},p=function(e){const t=y.__classPrivateFieldGet(this,n,"m",h).call(this,e),r=(0,I.isParseableResponseFormat)(y.__classPrivateFieldGet(this,s,"f")?.response_format),i=r||y.__classPrivateFieldGet(this,c,"f"),o=i?U(e):e.message,l=i?L(o,"refusal"):o.refusal,u=!l&&r,d=u?L(o,"content"):o.content;null==d||""===d&&(l||o.tool_calls?.length||o.function_call)||t.content_done||(u&&y.__classPrivateFieldGet(this,a,"f")&&y.__classPrivateFieldGet(this,n,"m",_).call(this,y.__classPrivateFieldGet(this,a,"f")),t.content_done=!0,this._emit("content.done",{content:d,parsed:l?null:(0,I.parseResponseFormatContent)(y.__classPrivateFieldGet(this,s,"f")?.response_format,u?H(d):d)})),l&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:l})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},_=function(e){const t={bytes:0,fragments:0,work:0},r=(0,I.isParseableResponseFormat)(y.__classPrivateFieldGet(this,s,"f")?.response_format),n=new WeakMap,i=D(e,"choices",B,"choice");if(!i)throw new v.OpenAIError("Chat completion stream contains an unsafe snapshot choice collection");for(let e=0;e<i.length;e+=1){const a=$(i,e);if(!a)continue;const u=U(a),h=L(u,"refusal"),d=L(u,"content"),f=new Map,p=D(u,"tool_calls",x,"tool-call");n.set(a,Object.freeze({message:u,content:d,refusal:h,toolCallCollection:p,toolCalls:f}));const _=y.__classPrivateFieldGet(this,o,"f")[a.index];r&&!h&&"string"==typeof d&&H(d,t,y.__classPrivateFieldGet(this,l,"f"));for(const[e,t]of _?.tool_call_identities??[]){const r=p&&$(p,e);if(!r)throw new v.OpenAIError("Chat completion stream contains a changed tool call identity");Q(r,t)}if(y.__classPrivateFieldGet(this,c,"f"))for(let e=0;e<(p?.length??0);e+=1){const r=$(p,e);if(!r)continue;const n=G(r);if(!n){const e=Object.getOwnPropertyDescriptor(r,"type");if(e&&!("value"in e))throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");if("function"!==e?.value)continue;const t=Object.getOwnPropertyDescriptor(r,"function");if(t&&!("value"in t))throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");if(t&&"object"==typeof t.value&&null!==t.value){const e=Object.getOwnPropertyDescriptor(t.value,"name");if(e&&!("value"in e))throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot")}continue}if(!(0,I.shouldParseToolCall)(y.__classPrivateFieldGet(this,s,"f"),{type:n.type,function:{name:n.name}}))continue;const i=Object.getOwnPropertyDescriptor(r,"function");if(!i||!("value"in i))throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");const o=i.value,a=L(o,"arguments");if("string"!=typeof a)throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");H(a,t,y.__classPrivateFieldGet(this,l,"f")),f.set(e,Object.freeze({tool:r,function:o,type:n.type,name:n.name,arguments:a}))}}return n},g=function(){if(this.ended)throw new v.OpenAIError("stream has ended, this shouldn't happen");const e=y.__classPrivateFieldGet(this,a,"f");if(!e)throw new v.OpenAIError("request ended without sending any chunks");const t=y.__classPrivateFieldGet(this,n,"m",_).call(this,e),r=y.__classPrivateFieldGet(this,i,"f");return y.__classPrivateFieldSet(this,i,new Set,"f"),y.__classPrivateFieldSet(this,a,void 0,"f"),y.__classPrivateFieldSet(this,o,[],"f"),function(e,t,r,n){const{id:s,choices:i,created:o,model:a,system_fingerprint:c,...l}=e,u={...l,id:s,choices:j(i,B,"choice",e=>{const s=n.get(e);if(!s)throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");const i=new Proxy(e,{get:(e,t,r)=>"message"===t?s.message:Reflect.get(e,t,r)}),{message:o,finish_reason:a,index:c,logprobs:l,...u}=i,h=new Proxy(o,{get:(e,t,r)=>"content"===t?s.content:"refusal"===t?s.refusal:"tool_calls"===t?s.toolCallCollection:Reflect.get(e,t,r)}),{content:d=null,function_call:f,tool_calls:p,audio:_,...g}=h,m=a??(r.has(c)&&function(e){return null!=e?.id&&null!=e.data&&null!=e.transcript&&null!=e.expires_at}(_)?"stop":null);if(!m)throw new v.OpenAIError(`missing finish_reason for choice ${c}`);const y=_?{audio:_}:{},A=h.role;if(!A)throw new v.OpenAIError(`missing role for choice ${c}`);if(f){const{arguments:e,name:t}=f;if(null==e)throw new v.OpenAIError(`missing function_call.arguments for choice ${c}`);if(!t)throw new v.OpenAIError(`missing function_call.name for choice ${c}`);return{...u,message:{...y,content:d,function_call:{arguments:e,name:t},role:A,refusal:h.refusal??null},finish_reason:m,index:c,logprobs:l}}return p?{...u,index:c,finish_reason:m,logprobs:l,message:{...g,...y,role:A,content:d,refusal:h.refusal??null,tool_calls:j(p,x,"tool-call",(e,r)=>{const n=s.toolCalls.get(r);if(!n){const r=G(e);if(r&&(0,I.shouldParseToolCall)(t,{type:r.type,function:{name:r.name}}))throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot")}if(n&&n.tool!==e)throw new v.OpenAIError("Chat completion stream contains a changed tool call identity");const i=n&&new Proxy(n.function,{get:(e,t,r)=>"arguments"===t?n.arguments:"name"===t?n.name:Reflect.get(e,t,r)}),o=n&&i?new Proxy(e,{get:(e,t,r)=>"type"===t?n.type:"function"===t?i:Reflect.get(e,t,r)}):e;if(null==o.type)throw new v.OpenAIError(`missing choices[${c}].tool_calls[${r}].type`);if("custom"===o.type){const{custom:e,type:t,id:n,...s}=o,{input:i="",name:a,...l}=e||{};if(null==a)throw new v.OpenAIError(`missing choices[${c}].tool_calls[${r}].custom.name`);return{...s,id:n||`call_${(0,w.uuid4)()}`,type:t,custom:{...l,name:a,input:i}}}const{function:a,type:l,id:u,...h}=o,{arguments:d,name:f,...p}=a||{};if(null==f)throw new v.OpenAIError(`missing choices[${c}].tool_calls[${r}].function.name`);if(null==d)throw new v.OpenAIError(`missing choices[${c}].tool_calls[${r}].function.arguments`);return{...h,id:u||`call_${(0,w.uuid4)()}`,type:l,function:{...p,name:f,arguments:d}}})}}:{...u,message:{...g,...y,content:d,role:A,refusal:h.refusal??null},finish_reason:m,index:c,logprobs:l}}),created:o,model:a,object:"chat.completion",...c?{system_fingerprint:c}:{}};return(0,I.maybeParseChatCompletion)(u,t)}(e,y.__classPrivateFieldGet(this,s,"f"),r,t)},m=function(e,t){var r,o,u,d,f;let p=y.__classPrivateFieldGet(this,a,"f");const{choices:g,obfuscation:m,...A}=e;if(p)e.id&&q(p,A);else{const e={...A,choices:[]};y.__classPrivateFieldSet(this,a,e,"f"),p=e}const b=y.__classPrivateFieldGet(this,s,"f")?.n,w="number"==typeof b&&Number.isSafeInteger(b)&&b>0?Math.min(b,B):B;for(const a of e.choices){const{delta:e,finish_reason:g,index:m,logprobs:A=null,...b}=a,S=[];if(t.set(a,Object.freeze({index:m,tool_calls:S})),!Number.isSafeInteger(m)||m<0||m>=w)throw new v.OpenAIError(`Chat completion stream contains an invalid choice index: ${m}`);let P=p.choices[m];if(!P){const e={finish_reason:g,index:m,message:{},logprobs:null,...b};p.choices[m]=e,P=e}if(((0,I.isParseableResponseFormat)(y.__classPrivateFieldGet(this,s,"f")?.response_format)||y.__classPrivateFieldGet(this,c,"f"))&&L(U(P),"refusal"),A)if(P.logprobs){const{content:e,refusal:t,...n}=A;ie(),q(P.logprobs,n),e&&((r=P.logprobs).content??(r.content=[]),P.logprobs.content.push(...e)),t&&((o=P.logprobs).refusal??(o.refusal=[]),P.logprobs.refusal.push(...t))}else P.logprobs={...A},A.content&&(P.logprobs.content=[...A.content]),A.refusal&&(P.logprobs.refusal=[...A.refusal]);if(g&&(P.finish_reason=g,y.__classPrivateFieldGet(this,s,"f")&&(0,I.hasAutoParseableInput)(y.__classPrivateFieldGet(this,s,"f")))){if("length"===g)throw new v.LengthFinishReasonError;if("content_filter"===g)throw new v.ContentFilterFinishReasonError}if(q(P,b),!e){Object.freeze(S);continue}y.__classPrivateFieldGet(this,i,"f").delete(m);const{audio:O,content:C,refusal:R,function_call:B,role:T,...D}=e,{tool_calls:$,...j}=D,W=(0,E.hasOwn)(D,"tool_calls")?$:e.tool_calls;if(ie(),q(P.message,j),null!=O?.expires_at&&null==O.id&&null==O.data&&null==O.transcript&&null==C&&null==R&&null==B&&null==T&&null==W&&0===Object.keys(j).length&&y.__classPrivateFieldGet(this,i,"f").add(m),R&&(P.message.refusal=(P.message.refusal||"")+R),T&&(P.message.role=T),O){const e=(u=P.message).audio??(u.audio={});null!=O.id&&(e.id=O.id),null!=O.data&&(e.data=(e.data??"")+O.data),null!=O.transcript&&(e.transcript=(e.transcript??"")+O.transcript),null!=O.expires_at&&(e.expires_at=O.expires_at)}if(B&&(P.message.function_call?(B.name&&(P.message.function_call.name=B.name),B.arguments&&((d=P.message.function_call).arguments??(d.arguments=""),P.message.function_call.arguments+=B.arguments)):P.message.function_call=B),null!=C)if(!P.message.refusal&&(0,I.isParseableResponseFormat)(y.__classPrivateFieldGet(this,s,"f")?.response_format)){const e=y.__classPrivateFieldGet(this,n,"m",h).call(this,P),t=e.content_parse_state??(e.content_parse_state=N()),r=F(t,y.__classPrivateFieldGet(this,l,"f"),C);P.message.content=(L(P.message,"content")||"")+C,t.has_non_whitespace?r&&M(t,y.__classPrivateFieldGet(this,l,"f"))?(y.__classPrivateFieldGet(this,n,"m",_).call(this,p),P.message.parsed=k(H(P.message.content))):C.length>0&&(P.message.parsed=null):P.message.parsed=null}else P.message.content=(P.message.content||"")+C;if(W){const e=(f=P.message).tool_calls??(f.tool_calls=[]);for(const t of W){const{index:r,id:i,type:o,function:a,custom:u,...d}=t;if(!Number.isSafeInteger(r)||r<0||r>=x)throw new v.OpenAIError(`Chat completion stream contains an invalid tool call index: ${r}`);let f="";const g=e[r]??(e[r]={}),m=a?.name,A=y.__classPrivateFieldGet(this,c,"f")?y.__classPrivateFieldGet(this,n,"m",h).call(this,P):void 0;let b=A?.tool_call_identities.get(r);if(b&&(Q(g,b),void 0!==o&&o!==b.type||void 0!==m&&m!==b.name))throw new v.OpenAIError("Chat completion stream contains a changed tool call identity");if(q(g,d),i&&(g.id=i),o&&(g.type=o),u){const e=g.custom??(g.custom={name:u.name??"",input:""});u.name&&(e.name=u.name),u.input&&(e.input+=u.input)}if(a){const e=g.function??(g.function={name:m??"",arguments:""});if(m&&(e.name=m),A&&!b){const e=G(g),t=e&&y.__classPrivateFieldGet(this,s,"f")?.tools?.find(t=>(0,I.isChatCompletionFunctionTool)(t)&&t.function.name===e.name);if(e&&(b={...e,parseable:void 0!==t&&(0,I.shouldParseToolCall)(y.__classPrivateFieldGet(this,s,"f"),{type:e.type,function:{name:e.name}})},A.tool_call_identities.set(r,b),!b.parseable)){const e=A.tool_call_parse_states.get(r);e&&(y.__classPrivateFieldGet(this,l,"f").bytes-=e.bytes,y.__classPrivateFieldGet(this,l,"f").fragments-=e.fragments,y.__classPrivateFieldGet(this,l,"f").work-=e.work,A.tool_call_parse_states.delete(r))}}const t=a.arguments;if(null!=t)if(f=t,A&&!1!==b?.parseable){let s=A.tool_call_parse_states.get(r);s||(s=N(),A.tool_call_parse_states.set(r,s));const i=F(s,y.__classPrivateFieldGet(this,l,"f"),t),o=L(e,"arguments");if("string"!=typeof o)throw new v.OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");e.arguments=o+t,i&&!0===b?.parseable&&M(s,y.__classPrivateFieldGet(this,l,"f"))?(y.__classPrivateFieldGet(this,n,"m",_).call(this,p),e.parsed_arguments=k(H(e.arguments))):t.length>0&&(0,E.hasOwn)(e,"parsed_arguments")&&(e.parsed_arguments=void 0)}else e.arguments+=t}S.push(Object.freeze({index:r,arguments_delta:f}))}}Object.freeze(S)}return p},Symbol.asyncIterator)](){return this._createIterator(e=>{const t=t=>e(t);return this.on("chunk",t),()=>this.off("chunk",t)},{onReturn:()=>this.abort()})}toReadableStream(){return new S.Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ie(e){}function oe(e){return e}t.ChatCompletionStream=se},6942(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatCompletionStreamingRunner=void 0;const n=r(8634),s=r(2154),i=r(3528),o=r(9277);class a extends n.ChatCompletionStream{static fromReadableStream(e){const t=new a(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e,t;const r=this._createIterator(r=>{const i=t=>{e=t,r(t)},a=i=>{if((0,o.isAssistantMessage)(i))t=i.tool_calls?.map(e=>e.id);else if((0,o.isToolMessage)(i)){if(!e)throw new s.OpenAIError("cannot serialize a tool message before receiving any chunks");r((0,n.makeChatCompletionReadableStreamMessageChunk)(e,i,t)),t=void 0}};return this.on("chunk",i),this.on("message",a),()=>{this.off("chunk",i),this.off("message",a)}},{onReturn:()=>this.abort()});return new i.Stream(()=>r,this.controller).toReadableStream()}static runTools(e,t,r){const n=new a(t),s={...r,__metadata:{...r?.__metadata,helperMethod:"runTools"}};return n._run(()=>n._runTools(e,t,n,s)),n}}t.ChatCompletionStreamingRunner=a},528(e,t,r){"use strict";var n,s,i,o,a,c,l,u,h,d,f,p,_,g,m,y,A,v,b,w,E,I,S,P;t.EventStream=void 0;const k=r(6316),O=r(2154),C=8388608,R=256,B=JSON.stringify,x=JSON.parse,T=new WeakSet,N=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer")?.get,F=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length")?.get,M=Object.getOwnPropertyDescriptor(DataView.prototype,"buffer")?.get,L=Object.getOwnPropertyDescriptor(Symbol.prototype,"description")?.get,U=Date.prototype.getTime,D=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get,$="function"==typeof SharedArrayBuffer?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength")?.get:void 0,j=Object.getOwnPropertyDescriptor(new Error("native stack descriptor"),"stack"),H=Function.prototype.toString,G=Object.prototype.toString,Q=Object.getOwnPropertyDescriptor(Error,"isError"),q=Q&&"value"in Q&&"function"==typeof Q.value?Q.value:void 0,W=H.call(Error),K=H.call(Date),X=H.call(Function),z=new Set([O.APIConnectionError.prototype,O.APIConnectionTimeoutError.prototype,O.APIError.prototype,O.OpenAIError.prototype,O.APIUserAbortError.prototype,O.AuthenticationError.prototype,O.BadRequestError.prototype,O.ConflictError.prototype,O.ContentFilterFinishReasonError.prototype,O.InternalServerError.prototype,O.InvalidWebhookSignatureError.prototype,O.LengthFinishReasonError.prototype,O.NotFoundError.prototype,O.OAuthError.prototype,O.PermissionDeniedError.prototype,O.RateLimitError.prototype,O.SubjectTokenProviderError.prototype,O.UnprocessableEntityError.prototype]),Y=new Set,J=new Map,V=new WeakMap,Z=function(){if("undefined"!=typeof process)try{const e=Object.getOwnPropertyDescriptor(process,"getBuiltinModule");if(!e||!("value"in e)||"function"!=typeof e.value)return;const t=Reflect.apply(e.value,process,["node:util"]);if("object"!=typeof t||null===t)return;const r=Object.getOwnPropertyDescriptor(t,"types");if(!r||!("value"in r)||"object"!=typeof r.value||null===r.value)return;const n=Object.getOwnPropertyDescriptor(r.value,"isProxy");if(!n||!("value"in n)||"function"!=typeof n.value)return;return n.value}catch{return}}();function ee(e){if("function"!=typeof e)return;const t=Object.getOwnPropertyDescriptor(e,"prototype");if(!t||!("value"in t)||"object"!=typeof t.value&&"function"!=typeof t.value)return;z.add(t.value);const r=H.call(e);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(r)&&!1===t.configurable&&!1===t.writable){Y.add(r);const e=new Map;for(const r of Reflect.ownKeys(t.value)){const n=Object.getOwnPropertyDescriptor(t.value,r);n&&e.set(r,n)}J.set(r,e)}}for(const e of[Object,Function,Array,Date,Map,Set,ArrayBuffer,DataView,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,Int8Array,Int16Array,Int32Array,Float32Array,Float64Array])ee(e);for(const e of["SharedArrayBuffer","AggregateError","Float16Array","BigInt64Array","BigUint64Array","Blob","File","Headers"]){const t=Object.getOwnPropertyDescriptor(globalThis,e);t&&"value"in t&&ee(t.value)}const te=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"constructor");te&&"value"in te&&ee(te.value),"function"==typeof Buffer&&ee(Buffer);const re=(()=>{if("function"==typeof Blob)try{const e=new Blob([]);for(const t of Object.getOwnPropertySymbols(e)){const r=Object.getOwnPropertyDescriptor(e,t);if(r&&"value"in r&&"object"==typeof r.value&&r.value)return Object.getPrototypeOf(r.value)}}catch{return}})(),ne=Map.prototype.entries,se=Set.prototype.values,ie="function"==typeof Headers?Object.getOwnPropertyDescriptor(Headers.prototype,"entries"):void 0,oe=ie&&"value"in ie&&"function"==typeof ie.value?ie.value:void 0,ae=new Set(["ArrayBuffer","SharedArrayBuffer","Blob","File","Map","Date","Set","Headers"]);function ce(e){const t=Object.getOwnPropertyDescriptor(e,"constructor");if(!t||!("value"in t)||"function"!=typeof t.value)return;const r=t.value,n=H.call(r),s=J.get(n);if(!Y.has(n)||!s)return;const i=Object.getOwnPropertyDescriptor(r,"prototype");return i&&"value"in i&&i.value===e&&!1===i.configurable&&!1===i.writable?{constructor:r,descriptors:s,functionPrototype:Object.getPrototypeOf(r)}:void 0}function le(e){return z.has(e)||void 0!==ce(e)}function ue(e,t,r){if(void 0===t)return void 0===e;if("function"!=typeof e||"function"!=typeof t)return!1;const n=H.call(t);if(H.call(e)!==n)return!1;const s=Object.getPrototypeOf(e);if(s===r)return!0;if(!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(n))return!1;const i=ce(s);return void 0!==i&&H.call(i.constructor)===X}function he(e,t,r){return!(!t||e.configurable!==t.configurable||e.enumerable!==t.enumerable||"value"in e!="value"in t)&&("value"in e&&"value"in t?e.writable===t.writable&&("function"==typeof t.value?ue(e.value,t.value,r):(null===t.value||"object"!=typeof t.value)&&Object.is(e.value,t.value)):ue(e.get,t.get,r)&&ue(e.set,t.set,r))}function de(e){if(q)return q.call(Error,e);let t=e;for(let e=0;null!==t&&e<R;e+=1){if(Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))return!1;t=Object.getPrototypeOf(t)}return null===t&&"[object Error]"===G.call(e)}function fe(e,t){if(!de(e))return!1;if(j&&!("value"in j)&&"function"==typeof j.get&&Object.prototype.isPrototypeOf.call(Error.prototype,e)&&t.get===j.get&&t.set===j.set)return!0;const r=function(e,t){if("function"!=typeof t.get||"function"!=typeof t.set)return;let r=Object.getPrototypeOf(e);for(let e=0;null!==r&&e<R;e+=1){const e=Object.getOwnPropertyDescriptor(r,"constructor");if(e&&"value"in e&&"function"==typeof e.value){const n=e.value;if(H.call(n)===W&&le(r)){const e=Object.getPrototypeOf(n);return Object.getPrototypeOf(t.get)===e&&Object.getPrototypeOf(t.set)===e?{constructor:n,prototype:r}:void 0}}r=Object.getPrototypeOf(r)}}(e,t);if(!r)return!1;let n=V.get(r.prototype);if(!n){const e=Reflect.construct(r.constructor,[]);if("object"!=typeof e||null===e||!de(e)||Object.getPrototypeOf(e)!==r.prototype)return!1;if(n=Object.getOwnPropertyDescriptor(e,"stack"),!n||"value"in n||"function"!=typeof n.get||"function"!=typeof n.set)return!1;V.set(r.prototype,n)}return t.get===n.get&&t.set===n.set}function pe(){let e=[],t=0;return{get length(){return e.length-t},enqueue(t){e.push(t)},dequeue(){if(t===e.length)return;const r=e[t];return e[t]=void 0,t+=1,t===e.length?(e=[],t=0):t>=1024&&2*t>=e.length&&(e=e.slice(t),t=0),r},clear(){e=[],t=0}}}function _e(e,t,r,n,s,i){const o=function(e,t,r){if(Array.isArray(e)){const t=Object.getOwnPropertyDescriptor(e,"length"),n=t&&"value"in t?t.value:void 0;if("number"!=typeof n||!Number.isSafeInteger(n)||n<0||n>Math.floor(r/16))return}if("typed-array"!==t)return Reflect.ownKeys(e);const n=F?.call(e);return"number"!=typeof n||!Number.isSafeInteger(n)||n<0||n>4096?void 0:Reflect.ownKeys(e).filter(e=>{if("string"!=typeof e)return!0;const t=Number(e);return!Number.isInteger(t)||t<0||t>=n||String(t)!==e})}(e,t,n());if(void 0===o)return!1;for(const n of o){if(!s("string"==typeof n?2*n.length+8:8))return!1;"symbol"==typeof n&&i(n,r+1);const o=Object.getOwnPropertyDescriptor(e,n);if(!o)return!1;if(!("value"in o)){if("stack"===n&&fe(e,o))continue;return!1}i(o.value,r+1,"blob"===t)}return!0}function ge(e,t){let r=0,n=0;const s=new WeakSet,i=new Set,o=new Set,a=new Map;let c;const l=()=>t-r,u=e=>!Number.isSafeInteger(e)||e<0?(r=t+1,!1):(r+=e,c?c.bytes+=e:n+=e,r<=t),h=e=>{c?c.edges.add(e):o.add(e)},d=(e,t)=>{h(e);const r={bytes:0,edges:new Set};a.set(e,r);const n=c;c=r;try{return t()}finally{c=n}},f=(e,n,o=!1)=>{if(!(r>t))if("string"!=typeof e)if("symbol"!=typeof e)if("function"!=typeof e)if(null!==e&&"object"==typeof e)if(Z?.(e))r=t+1;else if(n>=R)r=t+1;else{if(s.has(e))return h(e),void u(8);s.add(e),d(e,()=>{if(!u(16))return!1;const i=function(e,t,r){if(ArrayBuffer.isView(e)){let n,s="typed-array";try{n=N?.call(e)}catch{s="data-view",n=M?.call(e)}return"object"!=typeof n||null===n?{bytes:Number.POSITIVE_INFINITY,kind:s}:(t(n,r+1),{bytes:0,kind:s})}const n=function(e){let t=Object.getPrototypeOf(e);for(let e=0;null!==t&&e<R;e+=1){if(t===Date.prototype)return"Date";if(!z.has(t)){const e=Object.getOwnPropertyDescriptor(t,"constructor");if(e&&"value"in e&&"function"==typeof e.value&&H.call(e.value)===K&&ce(t))return"Date"}const e=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);if(e&&"value"in e&&"string"==typeof e.value&&ae.has(e.value))return e.value;t=Object.getPrototypeOf(t)}}(e);if(!n)return;let s;switch(n){case"ArrayBuffer":s=D;break;case"SharedArrayBuffer":s=$;break;case"Blob":case"File":return{bytes:Number.POSITIVE_INFINITY,kind:"blob"};case"Map":return{bytes:0,kind:"map"};case"Date":return Reflect.apply(U,e,[]),{bytes:8,kind:"date"};case"Set":return{bytes:0,kind:"set"};case"Headers":return{bytes:0,kind:"headers"};default:return}const i=s?.call(e);return{bytes:"number"==typeof i&&Number.isSafeInteger(i)&&i>=0?i:Number.POSITIVE_INFINITY,kind:"buffer"}}(e,f,n);return!!function(e,t,r,n,s,i,o,a){let c=Object.getPrototypeOf(e);for(let e=t+1;null!==c;e+=1){if(e>=R)return!1;if(z.has(c)||r&&c===re)return!0;if(n.has(c))return o(c,e),s()>=0;n.add(c);const t=c;if(!a(t,()=>{if(!i(16))return!1;const r=ce(t);if(!r)return _e(t,void 0,e,s,i,o);for(const n of Reflect.ownKeys(t)){const s=Object.getOwnPropertyDescriptor(t,n);if(!s)return!1;if(!he(s,r.descriptors.get(n),r.functionPrototype)){if(!i("string"==typeof n?2*n.length+8:8)||!("value"in s))return!1;"symbol"==typeof n&&o(n,e+1),o(s.value,e+1)}}return s()>=0}))return!1;c=Object.getPrototypeOf(t)}return!0}(e,n,o,s,l,u,f,d)&&!(void 0!==i&&!u(i.bytes))&&!!function(e,t,r){if("map"===t)for(const[t,n]of ne.call(e))if(!r(t,8)||!r(n,8))return!1;if("set"===t)for(const t of se.call(e))if(!r(t,8))return!1;if("headers"===t){if(!oe)return!1;for(const[t,n]of oe.call(e))if(!r(t,8)||!r(n,8))return!1}return!0}(e,i?.kind,(e,s)=>!!u(s)&&(f(e,n+1),r<=t))&&_e(e,i?.kind,n,l,u,f)})||(r=t+1)}else u(8);else r=t+1;else(e=>{if(i.has(e))return h(e),void u(8);i.add(e),d(e,()=>{if(!L)return!1;const t=Reflect.apply(L,e,[]);return u(8+2*(t?.length??0))})||(r=t+1)})(e);else u(2*e.length)};try{f(e,0)}catch{return}return r<=t?{scalarBytes:n,roots:o,nodes:a}:void 0}function me(e,t){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}function ye(e,t){return e.bytes+32+8*e.edges.size+16*t}function Ae(e){return 32+e.scalarBytes+8*e.roots.size}function ve(e,t,r,n){const s=new Set,i=[...e];for(;i.length;){if(n.remaining-=1,n.remaining<0)return;const e=i.pop();if(s.has(e))continue;const o=t.get(e)??r.get(e);if(!o)return;s.add(e);for(const e of o.edges)i.push(e)}return s}function be(e,t,r,n,s){const i=n.get(e);if(i)return s&&(i.node=s),i;const o=s??t.nodes.get(e)??r.get(e);if(!o)return;const a={node:o,ownerDelta:0};return n.set(e,a),a}function we(e,t,r,n,s,i){for(const o of e.identities){if(i.remaining-=1,i.remaining<0)return!1;if(!t.has(o)){const e=be(o,r,n,s);if(!e)return!1;e.ownerDelta-=1}}for(const o of t){if(i.remaining-=1,i.remaining<0)return!1;if(!e.identities.has(o)){const e=be(o,r,n,s);if(!e)return!1;e.ownerDelta+=1}}return!0}t.EventStream=class{constructor(){n.add(this),this.controller=new AbortController,s.set(this,void 0),i.set(this,()=>{}),o.set(this,()=>{}),a.set(this,void 0),c.set(this,()=>{}),l.set(this,()=>{}),u.set(this,Object.create(null)),h.set(this,[]),d.set(this,new WeakMap),f.set(this,new Set),p.set(this,new Set),_.set(this,0),g.set(this,!1),m.set(this,!1),y.set(this,!1),A.set(this,!1),v.set(this,void 0),k.__classPrivateFieldSet(this,s,new Promise((e,t)=>{k.__classPrivateFieldSet(this,i,e,"f"),k.__classPrivateFieldSet(this,o,t,"f")}),"f"),k.__classPrivateFieldSet(this,a,new Promise((e,t)=>{k.__classPrivateFieldSet(this,c,e,"f"),k.__classPrivateFieldSet(this,l,t,"f")}),"f"),k.__classPrivateFieldGet(this,s,"f").catch(()=>{}),k.__classPrivateFieldGet(this,a,"f").catch(()=>{})}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(e=>{t=!0,k.__classPrivateFieldGet(this,n,"m",S).call(this,e)}).then(()=>{if(!t){try{this._emitFinal()}catch(e){return void k.__classPrivateFieldGet(this,n,"m",S).call(this,e)}this._emit("end")}})},0)}_connected(){this.ended||(k.__classPrivateFieldGet(this,i,"f").call(this),this._emit("connect"))}get ended(){return k.__classPrivateFieldGet(this,g,"f")}get errored(){return k.__classPrivateFieldGet(this,m,"f")}get aborted(){return k.__classPrivateFieldGet(this,y,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted)return void this.controller.abort();if(k.__classPrivateFieldGet(this,h,"f").some(t=>t.signal===e))return;const t=()=>this.controller.abort();e.addEventListener("abort",t,{once:!0}),k.__classPrivateFieldGet(this,h,"f").push({signal:e,listener:t})}on(e,t){var r;return((r=k.__classPrivateFieldGet(this,u,"f"))[e]||(r[e]=[])).push({listener:t}),this}off(e,t){const r=k.__classPrivateFieldGet(this,u,"f")[e];if(!r)return this;const s=k.__classPrivateFieldGet(this,d,"f").get(t);if(s?.event===e&&!s.registration.removed&&!s.registration.detached)return k.__classPrivateFieldGet(this,n,"m",E).call(this,e,s.registration),this;const i=r.findIndex(e=>!e.removed&&e.listener===t);return-1!==i&&r.splice(i,1),this}once(e,t){var r;return((r=k.__classPrivateFieldGet(this,u,"f"))[e]||(r[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{k.__classPrivateFieldSet(this,A,!0,"f");const s=t=>{this.off(e,i),r(t)},i=(...r)=>{"error"!==e&&this.off("error",s),t(r.length>1?r:r[0])};"error"!==e&&k.__classPrivateFieldGet(this,n,"m",w).call(this,"error",s),k.__classPrivateFieldGet(this,n,"m",w).call(this,e,i)})}events(e){return this._createIterator(t=>{const r=(...e)=>{T.add(e);try{t(e)}finally{T.delete(e)}};return this.on(e,r),()=>this.off(e,r)},{rejectOnError:"error"!==e,rejectOnAbort:"abort"!==e})}_createIterator(e,{rejectOnError:t=!0,rejectOnAbort:r=!0,onReturn:s}={}){const i=pe(),o=pe(),a=pe(),c=function(){const e=new Map;let t=0;const r=(r,n,s)=>{const i={remaining:131072},o=new Map,a=function(e,t,r,n,s){const i=new Set([e]);for(const[e,o]of t.nodes){if(s.remaining-=1,s.remaining<0)return;const a=r.get(e);if(!a)continue;const c=!me(a.edges,o.edges);if((a.bytes!==o.bytes||c)&&be(e,t,r,n,o),c)for(const e of a.owners){if(s.remaining-=1,s.remaining<0)return;i.add(e)}}return i}(r,n,e,o,i);if(!a)return!1;const c=function(e,t,r,n,s,i){const o=new Map;for(const a of r){const r=ve(a===e?t.roots:a.roots,t.nodes,n,i);if(!r||!we(a,r,t,n,s,i))return;o.set(a,r)}return o}(r,n,a,e,o,i);if(!c)return!1;const l=function(e,t,r,n,s,i){let o=e-(n?0:Ae(t))+Ae(r);for(const[e,t]of s){const r=i.get(e),n=(r?.owners.size??0)+t.ownerDelta;if(n<0)return;r&&(o-=ye(r,r.owners.size)),n&&(o+=ye(t.node,n))}return Number.isSafeInteger(o)&&o>=0&&o<=C?o:void 0}(t,r,n,s,o,e);return void 0!==l&&(function(e,t,r){for(const[r,n]of t){const t=e.get(r);(t?.owners.size??0)+n.ownerDelta&&(t?(t.bytes=n.node.bytes,t.edges=n.node.edges):e.set(r,{bytes:n.node.bytes,edges:n.node.edges,owners:new Set}))}for(const[t,n]of r){for(const r of t.identities)n.has(r)||e.get(r)?.owners.delete(t);for(const r of n)t.identities.has(r)||e.get(r).owners.add(t);t.identities=n}for(const r of t.keys())0===e.get(r)?.owners.size&&e.delete(r)}(e,o,c),r.scalarBytes=n.scalarBytes,r.roots=n.roots,t=l,!0)};return{retain(e){const t={scalarBytes:0,roots:new Set,identities:new Set};return r(t,e,!0)?t:void 0},refresh:(e,t)=>r(e,t,!1),release:r=>{t-=Ae(r);for(const n of r.identities){const s=e.get(n);s?.owners.delete(r)&&(t-=16,0===s.owners.size&&(t-=ye(s,0),e.delete(n)))}r.identities.clear()},clear(){e.clear(),t=0}}}();let l,u=this.ended,h=!1,d=()=>{};const f=()=>({value:void 0,done:!0}),_=()=>{for(;a.length;)a.dequeue().resolve(f())},m=()=>{l&&!h&&a.length&&(h=!0,a.dequeue().reject(l))},y=()=>{d(),this.off("end",P),t&&this.off("error",E),r&&this.off("abort",E)},A=e=>{e.active=!1,e.check&&(k.__classPrivateFieldGet(this,p,"f").delete(e.check),e.check=void 0)},b=(e=!1)=>{if(e){for(;o.length;)A(o.dequeue());i.clear(),c.clear()}const t=new O.OpenAIError("Event stream iterator buffer limit exceeded (4096 events or 8388608 bytes); consume events as they arrive.");try{k.__classPrivateFieldGet(this,n,"m",S).call(this,t)}finally{this.controller.abort()}return t},w=(e,t)=>{if(!t.active||k.__classPrivateFieldGet(this,g,"f"))return;const r=ge(e,C);r&&c.refresh(t.retention,r)||b(!0)},E=e=>{l=e,i.length||m()},I=()=>{if(l)return;const e=k.__classPrivateFieldGet(this,v,"f");e&&("error"===e.kind?t:r)&&(l=e.error)},P=()=>{u=!0,I(),y(),i.length||(m(),_())};return u||(d=e(e=>{if(u)return;const t=a.dequeue();if(t)t.resolve({value:e,done:!1});else{if(i.length>=4096)return void b();const t=ge(e,C),r=t&&c.retain(t);if(!r)return void b();if("object"==typeof e&&null!==e&&T.has(e)){const t=e;for(let e=0;e<t.length;e+=1){const r=t[e];"string"==typeof r&&(t[e]=x(B(r)))}}const n={retention:r,active:!0,check:void 0};i.enqueue(e),o.enqueue(n);const s=()=>{n.check=void 0,w(e,n)};n.check=s,k.__classPrivateFieldGet(this,p,"f").add(s)}}),this.on("end",P),t&&this.on("error",E),r&&this.on("abort",E)),{next:()=>{if(i.length){const e=i.dequeue(),t=o.dequeue();A(t);const r=ge(e,C);if(!r||!c.refresh(t.retention,r)){const e=b(!0);return h=!0,Promise.reject(e)}return c.release(t.retention),Promise.resolve({value:e,done:!1})}return(u||this.ended)&&I(),l&&!h?(h=!0,Promise.reject(l)):u?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{a.enqueue({resolve:e,reject:t})})},return:()=>{for(u=!0,h=!0;o.length;)A(o.dequeue());return i.clear(),c.clear(),y(),_(),s&&(this.done().catch(()=>{}),s()),Promise.resolve({value:void 0,done:!0})},[Symbol.asyncIterator](){return this}}}async done(){k.__classPrivateFieldSet(this,A,!0,"f"),await k.__classPrivateFieldGet(this,a,"f")}_hasListeners(e){return Boolean(k.__classPrivateFieldGet(this,u,"f")[e]?.some(e=>!e.removed))}_emit(e,...t){if(k.__classPrivateFieldGet(this,g,"f"))return;"end"===e&&(k.__classPrivateFieldGet(this,n,"m",b).call(this),k.__classPrivateFieldSet(this,g,!0,"f"),k.__classPrivateFieldGet(this,c,"f").call(this));const r=k.__classPrivateFieldGet(this,u,"f")[e];let s,i=!1;try{if(r){k.__classPrivateFieldGet(this,u,"f")[e]=r.filter(e=>(e.once&&(e.detached=!0),!e.once&&!e.removed)),k.__classPrivateFieldSet(this,_,k.__classPrivateFieldGet(this,_,"f")+1,"f");try{for(const e of r)if(!e.removed){const{listener:r}=e;r(...t)}}finally{if(k.__classPrivateFieldSet(this,_,k.__classPrivateFieldGet(this,_,"f")-1,"f"),0===k.__classPrivateFieldGet(this,_,"f")){k.__classPrivateFieldGet(this,n,"m",I).call(this);for(const e of k.__classPrivateFieldGet(this,p,"f"))k.__classPrivateFieldGet(this,p,"f").delete(e),k.__classPrivateFieldGet(this,g,"f")||e()}}}}catch(e){s=e,i=!0}try{k.__classPrivateFieldGet(this,n,"m",P).call(this,e,t,Boolean(r?.length))}catch(e){i||(s=e,i=!0)}if(i)throw s}_emitFinal(){}},s=new WeakMap,i=new WeakMap,o=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,_=new WeakMap,g=new WeakMap,m=new WeakMap,y=new WeakMap,A=new WeakMap,v=new WeakMap,n=new WeakSet,b=function(){for(const{signal:e,listener:t}of k.__classPrivateFieldGet(this,h,"f").splice(0))e.removeEventListener("abort",t)},w=function(e,t){const r=k.__classPrivateFieldGet(this,u,"f")[e],n=r?.length??0;this.once(e,t);const s=k.__classPrivateFieldGet(this,u,"f")[e],[i]=s?.slice(-1)??[];void 0!==r&&s!==r||s?.length!==n+1||i?.listener!==t||!i.once||k.__classPrivateFieldGet(this,d,"f").set(t,{event:e,registration:i})},E=function(e,t){t.removed||(t.removed=!0,k.__classPrivateFieldGet(this,d,"f").delete(t.listener),k.__classPrivateFieldGet(this,f,"f").add(e),0===k.__classPrivateFieldGet(this,_,"f")&&k.__classPrivateFieldGet(this,n,"m",I).call(this))},I=function(){for(const e of k.__classPrivateFieldGet(this,f,"f")){const t=e,r=k.__classPrivateFieldGet(this,u,"f")[t];r&&(k.__classPrivateFieldGet(this,u,"f")[t]=r.filter(e=>!e.removed))}k.__classPrivateFieldGet(this,f,"f").clear()},S=function(e){if(k.__classPrivateFieldSet(this,m,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new O.APIUserAbortError),e instanceof O.APIUserAbortError)return k.__classPrivateFieldSet(this,y,!0,"f"),this._emit("abort",e);if(e instanceof O.OpenAIError)return this._emit("error",e);if(e instanceof Error){const t=new O.OpenAIError(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new O.OpenAIError(String(e)))},P=function(e,t,r){if("abort"===e){const e=t[0];return k.__classPrivateFieldSet(this,v,k.__classPrivateFieldGet(this,v,"f")??{kind:"abort",error:e},"f"),k.__classPrivateFieldGet(this,A,"f")||r||Promise.reject(e),k.__classPrivateFieldGet(this,o,"f").call(this,e),k.__classPrivateFieldGet(this,l,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];k.__classPrivateFieldSet(this,v,k.__classPrivateFieldGet(this,v,"f")??{kind:"error",error:e},"f"),k.__classPrivateFieldGet(this,A,"f")||r||Promise.reject(e),k.__classPrivateFieldGet(this,o,"f").call(this,e),k.__classPrivateFieldGet(this,l,"f").call(this,e),this._emit("end")}}},2987(e,t,r){"use strict";t.maybeParseResponse=function(e,t){if(!t||!function(e){return!!(0,n.isParseableResponseFormat)(e.text?.format)||Array.isArray(e.tools)&&e.tools.some(e=>o(e)||"function"===e.type&&!0===e.strict||"namespace"===e.type&&e.tools.some(e=>"function"===e.type&&(o(e)||!0===e.strict)))}(t)){const t={...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return a(e,t)&&c(t),t}return s(e,t)},t.parseResponse=s,t.addOutputText=c;r(2154);const n=r(1489);function s(e,t){const r=!e.status||"completed"===e.status,s=e.output.map(e=>{if("function_call"===e.type)return r?function(e,t){const r=function(e,t,r){for(const n of e)if(null==r){if("function"===n.type&&n.name===t)return n}else if("namespace"===n.type&&n.name===r)return n.tools.find(e=>"function"===e.type&&e.name===t)}(e.tools??[],t.name,t.namespace);let s=null;return o(r)?s=r.$parseRaw(t.arguments):r?.strict&&(s=(0,n.parseResponseFormatContent)({type:"json_schema",$parseRaw:void 0},t.arguments)),{...t,parsed_arguments:s}}(t,e):{...e,parsed_arguments:null};if("message"===e.type){const n=e.content.map(e=>"output_text"===e.type?{...e,parsed:r?i(t,e.text):null}:e);return{...e,content:n}}return e}),l={...e,output:s};return a(e,l)&&c(l),Object.defineProperty(l,"output_parsed",{enumerable:!0,get(){for(const e of l.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),l}function i(e,t){return(0,n.parseResponseFormatContent)(e.text?.format,t)}function o(e){return"auto-parseable-tool"===e?.$brand}function a(e,t){return!Object.getOwnPropertyDescriptor(e,"output_text")||null==t.output_text}function c(e){const t=[];for(const r of e.output)if("message"===r.type)for(const e of r.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}},8615(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ParsingToolFunction=void 0,t.isRunnableFunctionWithParse=function(e){return"function"==typeof e.parse},t.ParsingToolFunction=class{constructor(e){this.type="function",this.function=e}}},1206(e,t){"use strict";t.allSettledWithThrow=void 0,t.allSettledWithThrow=async e=>{const t=await Promise.allSettled(e),r=t.filter(e=>"rejected"===e.status);if(r.length)throw Object.defineProperty(new Error(`${r.length} promise(s) failed`),"rejections",{configurable:!0,value:r.map(({reason:e})=>e),writable:!0});const n=[];for(const e of t)"fulfilled"===e.status&&n.push(e.value);return n}},2888(e,t,r){"use strict";var n,s,i,o,a,c,l,u,h,d,f,p,_,g,m,y,A;t.AgentSessionStream=void 0;const v=r(6316),b=r(1876),w=r(144),E=r(3098),I=r(5263),S=r(8874);function P(e){if(!(0,S.isObj)(e))return!1;const t=e;let r;if("input_text"===t.type)r="text";else{if("input_image"!==t.type)return!1;r="image_url"}return(0,S.hasOwn)(t,"type")&&(0,S.hasOwn)(t,r)&&"string"==typeof t[r]}function k(e){if(null===e)return null;if("string"==typeof e||Array.isArray(e)&&e.every(P))return e;throw new w.OpenAIError("Tool output must be text, content, a JSON object, or null")}class O{constructor(e,t,r,p){n.add(this),this.controller=new AbortController,s.set(this,!1),i.set(this,void 0),o.set(this,void 0),a.set(this,!1),c.set(this,void 0),l.set(this,void 0),u.set(this,void 0),h.set(this,void 0),d.set(this,void 0),f.set(this,void 0);const _="string"==typeof r.input?[{role:"user",content:[{type:"input_text",text:r.input}]}]:r.input;if(0===r.input.length)throw new w.OpenAIError("input must not be empty");v.__classPrivateFieldSet(this,c,e,"f"),v.__classPrivateFieldSet(this,l,t,"f"),v.__classPrivateFieldSet(this,u,{type:"agent.session.input.message",input:_},"f"),v.__classPrivateFieldSet(this,h,new Map(Object.entries(r.toolHandlers??{})),"f");const g=(0,E.buildHeaders)([p?.headers]);v.__classPrivateFieldSet(this,d,g.nulls.has("idempotency-key")?void 0:g.values.get("idempotency-key")??r.idempotencyKey??p?.idempotencyKey??(0,I.uuid4)(),"f"),g.values.delete("idempotency-key"),g.nulls.delete("idempotency-key");const{idempotencyKey:m,...y}=p??{};v.__classPrivateFieldSet(this,f,{...y,headers:g},"f")}abort(e){this.controller.abort(e),v.__classPrivateFieldGet(this,i,"f")?.controller.abort(this.controller.signal.reason),v.__classPrivateFieldGet(this,a,"f")||async function(e){try{await(e?.body?.cancel())}catch{}}(v.__classPrivateFieldGet(this,o,"f"))}[(s=new WeakMap,i=new WeakMap,o=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,h=new WeakMap,d=new WeakMap,f=new WeakMap,n=new WeakSet,Symbol.asyncIterator)](){if(v.__classPrivateFieldGet(this,s,"f"))throw new w.OpenAIError("An AgentSessionStream can only be consumed once");return v.__classPrivateFieldSet(this,s,!0,"f"),v.__classPrivateFieldGet(this,n,"m",p).call(this)}}t.AgentSessionStream=O,p=async function*(){const e=v.__classPrivateFieldGet(this,f,"f").signal,t=()=>this.abort(e?.aborted?e.reason:this.controller.signal.reason);e?.addEventListener("abort",t,{once:!0}),this.controller.signal.addEventListener("abort",t,{once:!0});const r={...v.__classPrivateFieldGet(this,f,"f"),signal:this.controller.signal},s=new b.TurnState;try{if(e?.aborted&&this.abort(e.reason),v.__classPrivateFieldGet(this,n,"m",g).call(this),"idle"!==(await v.__classPrivateFieldGet(this,c,"f").retrieve(v.__classPrivateFieldGet(this,l,"f"),r)).status)throw new w.OpenAIError("sessions.stream requires an idle session; use sessions.events.stream for active sessions");const t=await v.__classPrivateFieldGet(this,c,"f").events.stream(v.__classPrivateFieldGet(this,l,"f"),r).withResponse();v.__classPrivateFieldSet(this,i,t.data,"f"),v.__classPrivateFieldSet(this,o,t.response,"f"),v.__classPrivateFieldGet(this,n,"m",g).call(this),await v.__classPrivateFieldGet(this,c,"f").events.create(v.__classPrivateFieldGet(this,l,"f"),{events:[v.__classPrivateFieldGet(this,u,"f")],...void 0===v.__classPrivateFieldGet(this,d,"f")?{}:{"Idempotency-Key":v.__classPrivateFieldGet(this,d,"f")}},{...r,headers:(0,E.buildHeaders)([r.headers,{"Idempotency-Key":v.__classPrivateFieldGet(this,d,"f")??null}])}),v.__classPrivateFieldGet(this,n,"m",g).call(this),v.__classPrivateFieldSet(this,a,!0,"f");for await(const e of v.__classPrivateFieldGet(this,i,"f")){if(v.__classPrivateFieldGet(this,n,"m",g).call(this),!s.accept(e))continue;const t=s.terminal(e),o=s.call(e),a=o&&v.__classPrivateFieldGet(this,h,"f").get(o.name),c=o&&a?structuredClone(o):void 0;if(t&&v.__classPrivateFieldGet(this,i,"f").controller.abort(),yield e,t)return;if(v.__classPrivateFieldGet(this,n,"m",g).call(this),!c||!a)continue;const l=await v.__classPrivateFieldGet(this,n,"m",_).call(this,c,a);v.__classPrivateFieldGet(this,n,"m",g).call(this),await v.__classPrivateFieldGet(this,n,"m",A).call(this,l,r)}throw v.__classPrivateFieldGet(this,n,"m",g).call(this),new w.OpenAIError("Session event stream ended before the turn reached idle or failed")}finally{e?.removeEventListener("abort",t),this.controller.signal.removeEventListener("abort",t),this.abort()}},_=async function(e,t){try{const r="string"==typeof e.arguments?JSON.parse(e.arguments):e.arguments;if(null===r||"object"!=typeof r||Array.isArray(r))throw new w.OpenAIError("Function arguments must be a JSON object");return function(e,t){const r=null===t||"object"!=typeof t||Array.isArray(t)?t:JSON.stringify(t),n=JSON.stringify(r);if(void 0===n)throw new w.OpenAIError("Tool output must be JSON serializable");return{type:"agent.session.input.tool_result",turn_id:e.turn_id,call_id:e.call_id,success:!0,output:k("string"==typeof r?r:JSON.parse(n))}}(e,await v.__classPrivateFieldGet(this,n,"m",y).call(this,()=>t(r)))}catch{return v.__classPrivateFieldGet(this,n,"m",g).call(this),{type:"agent.session.input.tool_result",turn_id:e.turn_id,call_id:e.call_id,success:!1,error:"Tool handler failed."}}},g=function(){if(this.controller.signal.aborted)throw v.__classPrivateFieldGet(this,n,"m",m).call(this)},m=function(){const e=new w.APIUserAbortError;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e},y=async function(e){let t;const r=new Promise((e,r)=>{t=()=>r(v.__classPrivateFieldGet(this,n,"m",m).call(this)),this.controller.signal.addEventListener("abort",t,{once:!0})});try{v.__classPrivateFieldGet(this,n,"m",g).call(this);const t=async()=>await e();return await Promise.race([t(),r])}finally{t&&this.controller.signal.removeEventListener("abort",t)}},A=async function e(t,r,s=(0,I.uuid4)(),i=0){v.__classPrivateFieldGet(this,n,"m",g).call(this);try{await v.__classPrivateFieldGet(this,c,"f").events.create(v.__classPrivateFieldGet(this,l,"f"),{events:[t],"Idempotency-Key":s},r)}catch(o){const a=[100,300,600][i];if(!(void 0!==a&&o instanceof w.BadRequestError&&"invalid_request_error"===o.code&&o.error&&"message"in o.error&&o.error.message===`Unknown pending tool call: ${t.call_id}`))throw o;let c;try{await v.__classPrivateFieldGet(this,n,"m",y).call(this,()=>new Promise(e=>{c=setTimeout(e,a)}))}finally{void 0!==c&&clearTimeout(c)}await v.__classPrivateFieldGet(this,n,"m",e).call(this,t,r,s,i+1)}}},1876(e,t,r){"use strict";var n,s,i,o;t.TurnState=void 0;const a=r(6316);t.TurnState=class{constructor(){n.set(this,void 0),s.set(this,!1),i.set(this,new Set),o.set(this,new Set)}accept(e){if(a.__classPrivateFieldGet(this,i,"f").has(e.event_id))return!1;if(1024===a.__classPrivateFieldGet(this,i,"f").size){const e=a.__classPrivateFieldGet(this,i,"f").values().next();e.done||a.__classPrivateFieldGet(this,i,"f").delete(e.value)}return a.__classPrivateFieldGet(this,i,"f").add(e.event_id),"agent.session.turn.created"===e.type&&null===e.turn.subagent_id&&void 0===a.__classPrivateFieldGet(this,n,"f")&&a.__classPrivateFieldSet(this,n,e.turn_id,"f"),"agent.session.turn.completed"!==e.type&&"agent.session.turn.failed"!==e.type&&"agent.session.turn.cancelled"!==e.type||void 0===a.__classPrivateFieldGet(this,n,"f")||e.turn_id!==a.__classPrivateFieldGet(this,n,"f")||a.__classPrivateFieldSet(this,s,!0,"f"),!0}terminal(e){return"agent.session.failed"===e.type||"agent.session.idle"===e.type&&a.__classPrivateFieldGet(this,s,"f")}call(e){if("agent.session.turn.item.added"!==e.type||"function_call"!==e.item.type)return;const t=e.item,r=JSON.stringify([t.turn_id,t.call_id]);return a.__classPrivateFieldGet(this,o,"f").has(r)?void 0:(a.__classPrivateFieldGet(this,o,"f").add(r),t)}},n=new WeakMap,s=new WeakMap,i=new WeakMap,o=new WeakMap},1686(e,t,r){"use strict";t.pollAssistantRun=function(e,t,r,s){return(0,n.pollWithResponse)(n=>e.retrieve(t,r,{...s,headers:{...s?.headers,...n}}),["queued","in_progress","cancelling"],["requires_action","incomplete","cancelled","completed","failed","expired"],s)};const n=r(4131)},9277(e,t){"use strict";t.isToolMessage=t.isAssistantMessage=void 0,t.isAssistantMessage=e=>"assistant"===e?.role,t.isToolMessage=e=>"tool"===e?.role},316(e,t,r){"use strict";t.createEmbedding=function(e,t,r){const s=!!t.encoding_format,i=s?t.encoding_format:"base64";s&&(0,n.loggerFor)(e).debug("embeddings/user defined encoding_format:",t.encoding_format);const o={body:{...t,encoding_format:i},...r,__security:{bearerAuth:!0}},a=e.post("/embeddings",o);return s?a:((0,n.loggerFor)(e).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(e=>{const t=e?.data;if(void 0!==t){if(!Array.isArray(t))throw new TypeError("Expected embeddings response data to be an array");const{length:e}=t;for(let r=0;r<e;r+=1)if(r in t){const e=t[r],{embedding:s}=e;if(Array.isArray(s))continue;e.embedding=(0,n.toFloat32Array)(s)}}return e}))};const n=r(4737)},7998(e,t,r){"use strict";t.waitForFileProcessing=async function(e,t,r,i){const o=new Set(["processed","error","deleted"]),a=performance.now();let c=await e.retrieve(t);for(;!c.status||!o.has(c.status);)if(await(0,s.sleep)(r),c=await e.retrieve(t),performance.now()-a>i)throw new n.APIConnectionTimeoutError({message:`Giving up on waiting for file ${t} to finish processing after ${i} milliseconds.`});return c};const n=r(2154),s=r(8233)},1489(e,t,r){"use strict";t.isChatCompletionFunctionTool=s,t.isParseableResponseFormat=i,t.parseResponseFormatContent=o,t.isAutoParsableTool=a,t.maybeParseChatCompletion=function(e,t){return t&&u(t)?c(e,t):{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}},t.parseChatCompletion=c,t.shouldParseToolCall=function(e,t){if(!e||!("tools"in e)||!e.tools||"function"!==t.type)return!1;const r=e.tools?.find(e=>s(e)&&e.function?.name===t.function?.name);return s(r)&&(a(r)||r?.function.strict||!1)},t.hasAutoParseableInput=u,t.validateInputTools=function(e){for(const t of e??[])if("custom"!==t.type){if("function"!==t.type){const e=t.type;throw new n.OpenAIError(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${e}\``)}if(!0!==t.function.strict)throw new n.OpenAIError(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}};const n=r(2154);function s(e){return void 0!==e&&"function"in e&&void 0!==e.function}function i(e){return t=e,"auto-parseable-response-format"===t?.$brand||"json_schema"===e?.type;var t}function o(e,t){if(!i(e))return null;if("object"==typeof e&&null!==e&&"$parseRaw"in e&&"function"==typeof e.$parseRaw)return e.$parseRaw(t);try{return JSON.parse(t)}catch(e){if(e instanceof SyntaxError)throw new SyntaxError("Error reading response: invalid structured output JSON.");throw e}}function a(e){return"auto-parseable-tool"===e?.$brand}function c(e,t){const r=e.choices.map(e=>{if("length"===e.finish_reason)throw new n.LengthFinishReasonError;if("content_filter"===e.finish_reason)throw new n.ContentFilterFinishReasonError;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>function(e,t){if("custom"===t.type)return t;if("function"!==t.type){const e=t.type;throw new n.OpenAIError(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${e}\``)}const r=e.tools?.find(e=>s(e)&&e.function?.name===t.function.name);let i=null;return a(r)?i=r.$parseRaw(t.function.arguments):r?.function.strict&&(i=o({type:"json_schema",$parseRaw:void 0},t.function.arguments)),{...t,function:{...t.function,parsed_arguments:i}}}(t,e))??void 0}:void 0,parsed:null===e.message.content||void 0===e.message.content||e.message.refusal||""===e.message.content&&(e.message.tool_calls?.length||e.message.function_call)?null:l(t,e.message.content)}}});return{...e,choices:r}}function l(e,t){return o(e.response_format,t)}function u(e){return!!i(e.response_format)||(e.tools?.some(e=>a(e)||"function"===e.type&&!0===e.function.strict)??!1)}},4131(e,t,r){"use strict";t.pollWithResponse=async function(e,t,r,n){const a=(0,s.buildHeaders)([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:s,response:c}=await e(a).withResponse(),{status:l}=s;if(t.includes(l)){let e=5e3;const t=n?.pollIntervalMs;if(t||0===t)e=t;else{const t=c.headers.get("openai-poll-after-ms");if(t){const r=Number.parseInt(t);Number.isNaN(r)||(e=r)}}const r=n&&Object.prototype.propertyIsEnumerable.call(n,"signal")?n.signal:void 0;await(r?o(e,r):(0,i.sleep)(e))}else if(r.includes(l))return s}};const n=r(144),s=r(3098),i=r(8233);function o(e,t){return new Promise((r,s)=>{let i,o,a=!1;const c=e=>{try{t.removeEventListener("abort",e)}catch{}},l=()=>{if(void 0!==i&&(clearTimeout(i),i=void 0),o){const e=o;o=void 0,c(e)}},u=()=>{if(!a){a=!0,l();try{const e=new n.APIUserAbortError;Object.defineProperty(e,"cause",{value:t.reason,writable:!0,configurable:!0}),s(e)}catch(e){s(e)}}};if(t.aborted)u();else{i=setTimeout(()=>{a||(a=!0,l(),r())},e),o=u;try{t.addEventListener("abort",u,{once:!0}),a?c(u):t.aborted&&u()}catch(e){a?c(u):(a=!0,l(),s(e))}}})}},7800(e,t,r){"use strict";var n,s,i,o,a,c,l,u;t.ResponseStream=void 0;const h=r(6316),d=r(2154),f=r(528),p=r(7695),_=r(2987),g=r(3528);class m extends f.EventStream{constructor(e){super(),n.add(this),s.set(this,void 0),i.set(this,void 0),o.set(this,void 0),a.set(this,(0,p.createResponseContext)()),h.__classPrivateFieldSet(this,s,e,"f")}static createResponse(e,t,r){const n=new m(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,__metadata:{...r?.__metadata,helperMethod:"stream"}})),n}static fromReadableStream(e){const t=new m(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,r){let s;this._listenForAbort(r?.signal),h.__classPrivateFieldGet(this,n,"m",c).call(this);let i=null;"response_id"in t?(s=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):s=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const e of s)h.__classPrivateFieldGet(this,n,"m",l).call(this,e,i);if(s.controller.signal?.aborted)throw new d.APIUserAbortError;return h.__classPrivateFieldGet(this,n,"m",u).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),h.__classPrivateFieldGet(this,n,"m",c).call(this),this._connected();const r=g.Stream.fromReadableStream(e,this.controller);for await(const e of r)h.__classPrivateFieldGet(this,n,"m",l).call(this,e,null);if(r.controller.signal?.aborted)throw new d.APIUserAbortError;return h.__classPrivateFieldGet(this,n,"m",u).call(this)}[(s=new WeakMap,i=new WeakMap,o=new WeakMap,a=new WeakMap,n=new WeakSet,c=function(){this.ended||(h.__classPrivateFieldSet(this,i,void 0,"f"),h.__classPrivateFieldSet(this,a,(0,p.createResponseContext)(),"f"))},l=function(e,t){if(this.ended)return;const r=(e,r)=>{(null==t||r.sequence_number>t)&&this._emit(e,r)};if("error"===e.type){const t="error"in e&&"object"==typeof e.error&&null!==e.error?e.error:e;throw new d.APIError(void 0,t,e.message,void 0)}let n=e;const s=(0,p.accumulateResponseWithContext)(e,h.__classPrivateFieldGet(this,i,"f"),h.__classPrivateFieldGet(this,a,"f"),!0,e=>{n=e});switch(h.__classPrivateFieldSet(this,i,s,"f"),r("event",e),n.type){case"response.output_text.delta":{const e=s.output[n.output_index];if(!e)throw new d.OpenAIError(`missing output at index ${n.output_index}`);if("message"===e.type){const t=e.content[n.content_index];if(!t)throw new d.OpenAIError(`missing content at index ${n.content_index}`);if("output_text"!==t.type)throw new d.OpenAIError(`expected content to be 'output_text', got ${t.type}`);r("response.output_text.delta",{...n,type:n.type,item_id:n.item_id,output_index:n.output_index,content_index:n.content_index,snapshot:t.text})}break}case"response.function_call_arguments.delta":{const e=s.output[n.output_index];if(!e)throw new d.OpenAIError(`missing output at index ${n.output_index}`);"function_call"===e.type&&r("response.function_call_arguments.delta",{...n,type:n.type,item_id:n.item_id,output_index:n.output_index,snapshot:e.arguments});break}default:r(n.type,e)}},u=function(){if(this.ended)throw new d.OpenAIError("stream has ended, this shouldn't happen");const e=h.__classPrivateFieldGet(this,i,"f");if(!e)throw new d.OpenAIError("request ended without sending any events");h.__classPrivateFieldSet(this,i,void 0,"f"),h.__classPrivateFieldSet(this,a,(0,p.createResponseContext)(),"f");const t=function(e,t){return(0,_.maybeParseResponse)(e,t)}(e,h.__classPrivateFieldGet(this,s,"f"));return h.__classPrivateFieldSet(this,o,t,"f"),t},Symbol.asyncIterator)](){return this._createIterator(e=>{const t=t=>e(t);return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();const e=h.__classPrivateFieldGet(this,o,"f");if(!e)throw new d.OpenAIError("stream ended without producing a Response");return e}}t.ResponseStream=m},6471(e,t,r){"use strict";t.pollVectorStoreFile=function(e,t,r,s){return(0,n.pollWithResponse)(n=>e.retrieve(r,{vector_store_id:t},{...s,headers:n}),["in_progress"],["failed","cancelled","completed"],s)},t.pollVectorStoreFileBatch=function(e,t,r,s){return(0,n.pollWithResponse)(n=>e.retrieve(r,{vector_store_id:t},{...s,headers:n}),["in_progress"],["failed","cancelled","completed"],s)};const n=r(4131)},6507(e,t,r){"use strict";t.uploadAndPollVectorStoreFileBatch=async function(e,t,r,s,i,o){if(null==s||0===s.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=o?.maxConcurrency??5,c=Math.min(a,s.length);if(0===c)throw new RangeError("maxConcurrency must be greater than 0");const l=s.values(),u=[...i];async function h(e){for(const r of e){const e=await t.files.create({file:r,purpose:"assistants"},o);u.push(e.id)}}const d=[];d.length=c;for(let e=0;e<d.length;e+=1)d[e]=h(l);return await(0,n.allSettledWithThrow)(d),await e.createAndPoll(r,{file_ids:u},o)};const n=r(1206)},9110(e,t,r){"use strict";t.webhookSignatureRequiresSigning=o,t.verifyWebhookSignature=async function(e,t,r,l,u,h){const d=Number.parseInt(r,10);if(Number.isNaN(d))throw new n.InvalidWebhookSignatureError("Invalid webhook timestamp format");const f=Math.floor(Date.now()/1e3);if(f-d>h)throw new n.InvalidWebhookSignatureError("Webhook timestamp is too old");if(d>f+h)throw new n.InvalidWebhookSignatureError("Webhook timestamp is too new");const p=o(t),_=p?function(e){for(const t of a(e)){const e=c(t);if(e)return e}}(t):void 0;if(p&&!_)throw new n.InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");const g=Uint8Array.from(u.startsWith("whsec_")?(0,s.fromBase64)(u.slice(6)):(0,i.encodeUTF8)(u)),m=l?`${l}.${r}.${e}`:`${r}.${e}`,y=Uint8Array.from((0,i.encodeUTF8)(m)),A=await crypto.subtle.importKey("raw",g,{name:"HMAC",hash:"SHA-256"},!1,p?["sign","verify"]:["verify"]);if(p&&_){const e=function(e,t,r){let n=r;for(const r of a(e)){const e=c(r);if(!e)continue;let s=0;for(const[r,n]of e.entries())s|=n^(t[r]??0);0===s&&(n=e)}return n}(t,new Uint8Array(await crypto.subtle.sign("HMAC",A,y)),_);try{if(await crypto.subtle.verify("HMAC",A,Uint8Array.from(e),y))return}catch{}throw new n.InvalidWebhookSignatureError("The given webhook signature does not match the expected signature")}for(const e of a(t))try{const t=Uint8Array.from((0,s.fromBase64)(e));if(await crypto.subtle.verify("HMAC",A,t,y))return}catch{}throw new n.InvalidWebhookSignatureError("The given webhook signature does not match the expected signature")};const n=r(2154),s=r(7739),i=r(4545);function o(e){return e.split(" ",33).length>32}function*a(e){let t=0;for(;t<=e.length;){const r=e.indexOf(" ",t),n=e.slice(t,-1===r?void 0:r);if(yield n.startsWith("v1,")?n.slice(3):n,-1===r)break;t=r+1}}function c(e){try{const t=(0,s.fromBase64)(e);return 32===t.byteLength?t:void 0}catch{return}}},2157(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Admin=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(1881)),o=r(1881);class a extends s.APIResource{constructor(){super(...arguments),this.organization=new i.Organization(this._client)}}t.Admin=a,a.Organization=o.Organization},2339(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AdminAPIKeys=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i.path`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",s.CursorPage,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i.path`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}t.AdminAPIKeys=o},4423(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AuditLogs=void 0;const n=r(2596),s=r(3604);class i extends n.APIResource{list(e={},t){return this._client.getAPIList("/organization/audit_logs",s.ConversationCursorPage,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}t.AuditLogs=i},7278(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Certificates=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i.path`/organization/certificates/${e}`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i.path`/organization/certificates/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",s.ConversationCursorPage,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i.path`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",s.Page,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",s.Page,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}}t.Certificates=o},2233(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataRetention=void 0;const n=r(2596);class s extends n.APIResource{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/data_retention",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}}t.DataRetention=s},5253(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Groups=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(5376)),o=r(5376),a=n.__importStar(r(5653)),c=r(5653),l=r(3604),u=r(8491);class h extends s.APIResource{constructor(){super(...arguments),this.users=new a.Users(this._client),this.roles=new i.Roles(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(u.path`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(u.path`/organization/groups/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",l.NextCursorPage,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(u.path`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}t.Groups=h,h.Users=c.Users,h.Roles=o.Roles},5376(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Roles=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t,r){return this._client.post(i.path`/organization/groups/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{group_id:n}=t;return this._client.get(i.path`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i.path`/organization/groups/${e}/roles`,s.NextCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{group_id:n}=t;return this._client.delete(i.path`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.Roles=o},5653(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Users=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t,r){return this._client.post(i.path`/organization/groups/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{group_id:n}=t;return this._client.get(i.path`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i.path`/organization/groups/${e}/users`,s.NextCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{group_id:n}=t;return this._client.delete(i.path`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.Users=o},8622(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Invites=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i.path`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",s.ConversationCursorPage,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i.path`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}t.Invites=o},1881(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Organization=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(2339)),o=r(2339),a=n.__importStar(r(4423)),c=r(4423),l=n.__importStar(r(7278)),u=r(7278),h=n.__importStar(r(2233)),d=r(2233),f=n.__importStar(r(8622)),p=r(8622),_=n.__importStar(r(4421)),g=r(4421),m=n.__importStar(r(5494)),y=r(5494),A=n.__importStar(r(9022)),v=r(9022),b=n.__importStar(r(19)),w=r(19),E=n.__importStar(r(5253)),I=r(5253),S=n.__importStar(r(5305)),P=r(5305),k=n.__importStar(r(895)),O=r(895);class C extends s.APIResource{constructor(){super(...arguments),this.auditLogs=new a.AuditLogs(this._client),this.adminAPIKeys=new i.AdminAPIKeys(this._client),this.usage=new b.Usage(this._client),this.invites=new f.Invites(this._client),this.users=new k.Users(this._client),this.groups=new E.Groups(this._client),this.roles=new _.Roles(this._client),this.dataRetention=new h.DataRetention(this._client),this.spendLimit=new A.SpendLimit(this._client),this.spendAlerts=new m.SpendAlerts(this._client),this.certificates=new l.Certificates(this._client),this.projects=new S.Projects(this._client)}}t.Organization=C,C.AuditLogs=c.AuditLogs,C.AdminAPIKeys=o.AdminAPIKeys,C.Usage=w.Usage,C.Invites=p.Invites,C.Users=O.Users,C.Groups=I.Groups,C.Roles=g.Roles,C.DataRetention=d.DataRetention,C.SpendLimit=v.SpendLimit,C.SpendAlerts=y.SpendAlerts,C.Certificates=u.Certificates,C.Projects=P.Projects},2168(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.APIKeys=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{retrieve(e,t,r){const{project_id:n}=t;return this._client.get(i.path`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i.path`/organization/projects/${e}/api_keys`,s.ConversationCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:n}=t;return this._client.delete(i.path`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.APIKeys=o},23(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Certificates=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{list(e,t={},r){return this._client.getAPIList(i.path`/organization/projects/${e}/certificates`,s.ConversationCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,t,r){return this._client.getAPIList(i.path`/organization/projects/${e}/certificates/activate`,s.Page,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,r){return this._client.getAPIList(i.path`/organization/projects/${e}/certificates/deactivate`,s.Page,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}}t.Certificates=o},7672(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataRetention=void 0;const n=r(2596),s=r(8491);class i extends n.APIResource{retrieve(e,t){return this._client.get(s.path`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(s.path`/organization/projects/${e}/data_retention`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}}t.DataRetention=i},4394(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Groups=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(3893)),o=r(3893),a=r(3604),c=r(8491);class l extends s.APIResource{constructor(){super(...arguments),this.roles=new i.Roles(this._client)}create(e,t,r){return this._client.post(c.path`/organization/projects/${e}/groups`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:n,...s}=t;return this._client.get(c.path`/organization/projects/${n}/groups/${e}`,{query:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(c.path`/organization/projects/${e}/groups`,a.NextCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:n}=t;return this._client.delete(c.path`/organization/projects/${n}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.Groups=l,l.Roles=o.Roles},3893(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Roles=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t,r){const{project_id:n,...s}=t;return this._client.post(i.path`/projects/${n}/groups/${e}/roles`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:n,group_id:s}=t;return this._client.get(i.path`/projects/${n}/groups/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){const{project_id:n,...o}=t;return this._client.getAPIList(i.path`/projects/${n}/groups/${e}/roles`,s.NextCursorPage,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:n,group_id:s}=t;return this._client.delete(i.path`/projects/${n}/groups/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.Roles=o},1970(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HostedToolPermissions=void 0;const n=r(2596),s=r(8491);class i extends n.APIResource{retrieve(e,t){return this._client.get(s.path`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(s.path`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}}t.HostedToolPermissions=i},9799(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ModelPermissions=void 0;const n=r(2596),s=r(8491);class i extends n.APIResource{retrieve(e,t){return this._client.get(s.path`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(s.path`/organization/projects/${e}/model_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(s.path`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}}t.ModelPermissions=i},5305(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Projects=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(2168)),o=r(2168),a=n.__importStar(r(23)),c=r(23),l=n.__importStar(r(7672)),u=r(7672),h=n.__importStar(r(1970)),d=r(1970),f=n.__importStar(r(9799)),p=r(9799),_=n.__importStar(r(2370)),g=r(2370),m=n.__importStar(r(2278)),y=r(2278),A=n.__importStar(r(3459)),v=r(3459),b=n.__importStar(r(6129)),w=r(6129),E=n.__importStar(r(4394)),I=r(4394),S=n.__importStar(r(7074)),P=r(7074),k=n.__importStar(r(356)),O=r(356),C=r(3604),R=r(8491);class B extends s.APIResource{constructor(){super(...arguments),this.users=new k.Users(this._client),this.serviceAccounts=new S.ServiceAccounts(this._client),this.apiKeys=new i.APIKeys(this._client),this.rateLimits=new _.RateLimits(this._client),this.modelPermissions=new f.ModelPermissions(this._client),this.hostedToolPermissions=new h.HostedToolPermissions(this._client),this.groups=new E.Groups(this._client),this.roles=new m.Roles(this._client),this.dataRetention=new l.DataRetention(this._client),this.spendLimit=new b.SpendLimit(this._client),this.spendAlerts=new A.SpendAlerts(this._client),this.certificates=new a.Certificates(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(R.path`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(R.path`/organization/projects/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",C.ConversationCursorPage,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(R.path`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}}t.Projects=B,B.Users=O.Users,B.ServiceAccounts=P.ServiceAccounts,B.APIKeys=o.APIKeys,B.RateLimits=g.RateLimits,B.ModelPermissions=p.ModelPermissions,B.HostedToolPermissions=d.HostedToolPermissions,B.Groups=I.Groups,B.Roles=y.Roles,B.DataRetention=u.DataRetention,B.SpendLimit=w.SpendLimit,B.SpendAlerts=v.SpendAlerts,B.Certificates=c.Certificates},2370(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RateLimits=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{listRateLimits(e,t={},r){return this._client.getAPIList(i.path`/organization/projects/${e}/rate_limits`,s.ConversationCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,r){const{project_id:n,...s}=t;return this._client.post(i.path`/organization/projects/${n}/rate_limits/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}}t.RateLimits=o},2278(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Roles=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t,r){return this._client.post(i.path`/projects/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:n}=t;return this._client.get(i.path`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){const{project_id:n,...s}=t;return this._client.post(i.path`/projects/${n}/roles/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i.path`/projects/${e}/roles`,s.NextCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:n}=t;return this._client.delete(i.path`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.Roles=o},3071(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.APIKeys=void 0;const n=r(2596),s=r(8491);class i extends n.APIResource{create(e,t,r){const{project_id:n,...i}=t;return this._client.post(s.path`/organization/projects/${n}/service_accounts/${e}/api_keys`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}}t.APIKeys=i},7074(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceAccounts=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(3071)),o=r(3071),a=r(3604),c=r(8491);class l extends s.APIResource{constructor(){super(...arguments),this.apiKeys=new i.APIKeys(this._client)}create(e,t,r){return this._client.post(c.path`/organization/projects/${e}/service_accounts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:n}=t;return this._client.get(c.path`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){const{project_id:n,...s}=t;return this._client.post(c.path`/organization/projects/${n}/service_accounts/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(c.path`/organization/projects/${e}/service_accounts`,a.ConversationCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:n}=t;return this._client.delete(c.path`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.ServiceAccounts=l,l.APIKeys=o.APIKeys},3459(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpendAlerts=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t,r){return this._client.post(i.path`/organization/projects/${e}/spend_alerts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:n}=t;return this._client.get(i.path`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){const{project_id:n,...s}=t;return this._client.post(i.path`/organization/projects/${n}/spend_alerts/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i.path`/organization/projects/${e}/spend_alerts`,s.ConversationCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:n}=t;return this._client.delete(i.path`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.SpendAlerts=o},6129(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpendLimit=void 0;const n=r(2596),s=r(8491);class i extends n.APIResource{retrieve(e,t){return this._client.get(s.path`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(s.path`/organization/projects/${e}/spend_limit`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(s.path`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}}t.SpendLimit=i},8034(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Roles=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t,r){const{project_id:n,...s}=t;return this._client.post(i.path`/projects/${n}/users/${e}/roles`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:n,user_id:s}=t;return this._client.get(i.path`/projects/${n}/users/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){const{project_id:n,...o}=t;return this._client.getAPIList(i.path`/projects/${n}/users/${e}/roles`,s.NextCursorPage,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:n,user_id:s}=t;return this._client.delete(i.path`/projects/${n}/users/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.Roles=o},356(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Users=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(8034)),o=r(8034),a=r(3604),c=r(8491);class l extends s.APIResource{constructor(){super(...arguments),this.roles=new i.Roles(this._client)}create(e,t,r){return this._client.post(c.path`/organization/projects/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{project_id:n}=t;return this._client.get(c.path`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){const{project_id:n,...s}=t;return this._client.post(c.path`/organization/projects/${n}/users/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(c.path`/organization/projects/${e}/users`,a.ConversationCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{project_id:n}=t;return this._client.delete(c.path`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.Users=l,l.Roles=o.Roles},4421(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Roles=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i.path`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i.path`/organization/roles/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",s.NextCursorPage,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i.path`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}t.Roles=o},5494(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpendAlerts=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i.path`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i.path`/organization/spend_alerts/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",s.ConversationCursorPage,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i.path`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}t.SpendAlerts=o},9022(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SpendLimit=void 0;const n=r(2596);class s extends n.APIResource{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/spend_limit",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}}t.SpendLimit=s},19(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Usage=void 0;const n=r(2596);class s extends n.APIResource{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get("/organization/usage/completions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get("/organization/costs",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get("/organization/usage/embeddings",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get("/organization/usage/images",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get("/organization/usage/moderations",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}t.Usage=s},9370(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Roles=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t,r){return this._client.post(i.path`/organization/users/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){const{user_id:n}=t;return this._client.get(i.path`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i.path`/organization/users/${e}/roles`,s.NextCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{user_id:n}=t;return this._client.delete(i.path`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.Roles=o},895(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Users=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(9370)),o=r(9370),a=r(3604),c=r(8491);class l extends s.APIResource{constructor(){super(...arguments),this.roles=new i.Roles(this._client)}retrieve(e,t){return this._client.get(c.path`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(c.path`/organization/users/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",a.ConversationCursorPage,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(c.path`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}t.Users=l,l.Roles=o.Roles},4425(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Audio=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(3565)),o=r(3565),a=n.__importStar(r(8682)),c=r(8682),l=n.__importStar(r(6123)),u=r(6123);class h extends s.APIResource{constructor(){super(...arguments),this.transcriptions=new a.Transcriptions(this._client),this.translations=new l.Translations(this._client),this.speech=new i.Speech(this._client)}}t.Audio=h,h.Transcriptions=c.Transcriptions,h.Translations=u.Translations,h.Speech=o.Speech},3565(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Speech=void 0;const n=r(2596),s=r(3098);class i extends n.APIResource{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:(0,s.buildHeaders)([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}t.Speech=i},8682(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Transcriptions=void 0;const n=r(2596),s=r(1598);class i extends n.APIResource{create(e,t){return this._client.post("/audio/transcriptions",(0,s.multipartFormRequestOptions)({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}t.Transcriptions=i},6123(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Translations=void 0;const n=r(2596),s=r(1598);class i extends n.APIResource{create(e,t){return this._client.post("/audio/translations",(0,s.multipartFormRequestOptions)({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}t.Translations=i},8398(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Batches=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i.path`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",s.CursorPage,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i.path`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}}t.Batches=o},756(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Agents=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(2181)),o=r(2181),a=n.__importStar(r(911)),c=r(911),l=n.__importStar(r(775)),u=r(775),h=r(3604),d=r(3098),f=r(8491);class p extends s.APIResource{constructor(){super(...arguments),this.environments=new i.Environments(this._client),this.vaults=new l.Vaults(this._client),this.sessions=new a.Sessions(this._client)}create(e,t){return this._client.post("/agents",{body:e,...t,headers:(0,d.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(f.path`/agents/${e}`,{...t,headers:(0,d.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},r){return this._client.post(f.path`/agents/${e}`,{body:t,...r,headers:(0,d.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents",h.CursorPage,{query:e,...t,headers:(0,d.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(f.path`/agents/${e}`,{...t,headers:(0,d.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}t.Agents=p,p.Environments=o.Environments,p.Vaults=u.Vaults,p.Sessions=c.Sessions},2181(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Environments=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(896)),o=r(896),a=n.__importStar(r(9108)),c=r(9108),l=r(3098),u=r(8491);class h extends s.APIResource{constructor(){super(...arguments),this.files=new i.Files(this._client),this.templates=new a.Templates(this._client)}retrieve(e,t){return this._client.get(u.path`/agents/environments/${e}`,{...t,headers:(0,l.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}t.Environments=h,h.Files=o.Files,h.Templates=c.Templates},896(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Files=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{create(e,t,r){return this._client.post(o.path`/agents/environments/${e}/files`,{body:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(o.path`/agents/environments/${e}/files`,s.TokenPage,{query:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}}t.Files=a},9108(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Templates=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{create(e={},t){return this._client.post("/agents/environments/templates",{body:e,...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(o.path`/agents/environments/templates/${e}`,{...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},r){return this._client.post(o.path`/agents/environments/templates/${e}`,{body:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents/environments/templates",s.CursorPage,{query:e,...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(o.path`/agents/environments/templates/${e}`,{...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}t.Templates=a},2123(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Artifacts=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{retrieve(e,t,r){const{session_id:n}=t;return this._client.get(o.path`/agents/sessions/${n}/artifacts/${e}`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(o.path`/agents/sessions/${e}/artifacts`,s.CursorPage,{query:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){const{session_id:n}=t;return this._client.delete(o.path`/agents/sessions/${n}/artifacts/${e}`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}content(e,t,r){const{session_id:n}=t;return this._client.get(o.path`/agents/sessions/${n}/artifacts/${e}/content`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1",Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}t.Artifacts=a},871(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Events=void 0;const n=r(2596),s=r(3098),i=r(8491);class o extends n.APIResource{create(e,t,r){const{"Idempotency-Key":n,...o}=t;return this._client.post(i.path`/agents/sessions/${e}/events`,{body:o,...r,headers:(0,s.buildHeaders)([{"OpenAI-Beta":"agents=v1",Accept:"*/*",...null!=n?{"Idempotency-Key":n}:void 0},r?.headers]),__security:{bearerAuth:!0}})}stream(e,t){return this._client.get(i.path`/agents/sessions/${e}/events`,{...t,headers:(0,s.buildHeaders)([{"OpenAI-Beta":"agents=v1",Accept:"text/event-stream"},t?.headers]),stream:!0,__security:{bearerAuth:!0}})}}t.Events=o},9768(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Items=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{list(e,t={},r){return this._client.getAPIList(o.path`/agents/sessions/${e}/items`,s.CursorPage,{query:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}}t.Items=a},911(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sessions=void 0;const n=r(6316),s=r(2888),i=r(2596),o=n.__importStar(r(2123)),a=r(2123),c=n.__importStar(r(871)),l=r(871),u=n.__importStar(r(9768)),h=r(9768),d=n.__importStar(r(6828)),f=r(6828),p=n.__importStar(r(239)),_=r(239),g=r(3604),m=r(3098),y=r(8491);class A extends i.APIResource{constructor(){super(...arguments),this.subagents=new p.Subagents(this._client),this.artifacts=new o.Artifacts(this._client),this.items=new u.Items(this._client),this.events=new c.Events(this._client),this.turns=new d.Turns(this._client)}stream(e,t,r){return new s.AgentSessionStream(this,e,t,r)}create(e,t){return this._client.post("/agents/sessions",{body:e,...t,headers:(0,m.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(y.path`/agents/sessions/${e}`,{...t,headers:(0,m.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},r){return this._client.post(y.path`/agents/sessions/${e}`,{body:t,...r,headers:(0,m.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents/sessions",g.CursorPage,{query:e,...t,headers:(0,m.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(y.path`/agents/sessions/${e}`,{...t,headers:(0,m.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}t.Sessions=A,A.Subagents=_.Subagents,A.Artifacts=a.Artifacts,A.Items=h.Items,A.Events=l.Events,A.Turns=f.Turns},6999(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Items=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{list(e,t,r){const{session_id:n,...a}=t;return this._client.getAPIList(o.path`/agents/sessions/${n}/subagents/${e}/items`,s.CursorPage,{query:a,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}}t.Items=a},239(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Subagents=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(6999)),o=r(6999),a=n.__importStar(r(8544)),c=r(8544),l=r(3604),u=r(3098),h=r(8491);class d extends s.APIResource{constructor(){super(...arguments),this.items=new i.Items(this._client),this.turns=new a.Turns(this._client)}retrieve(e,t,r){const{session_id:n}=t;return this._client.get(h.path`/agents/sessions/${n}/subagents/${e}`,{...r,headers:(0,u.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(h.path`/agents/sessions/${e}/subagents`,l.CursorPage,{query:t,...r,headers:(0,u.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}}t.Subagents=d,d.Items=o.Items,d.Turns=c.Turns},6188(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Items=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{list(e,t,r){const{session_id:n,subagent_id:a,...c}=t;return this._client.getAPIList(o.path`/agents/sessions/${n}/subagents/${a}/turns/${e}/items`,s.CursorPage,{query:c,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}}t.Items=a},8544(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Turns=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(6188)),o=r(6188),a=r(3604),c=r(3098),l=r(8491);class u extends s.APIResource{constructor(){super(...arguments),this.items=new i.Items(this._client)}retrieve(e,t,r){const{session_id:n,subagent_id:s}=t;return this._client.get(l.path`/agents/sessions/${n}/subagents/${s}/turns/${e}`,{...r,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t,r){const{session_id:n,...s}=t;return this._client.getAPIList(l.path`/agents/sessions/${n}/subagents/${e}/turns`,a.CursorPage,{query:s,...r,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}}t.Turns=u,u.Items=o.Items},6828(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Turns=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{retrieve(e,t,r){const{session_id:n}=t;return this._client.get(o.path`/agents/sessions/${n}/turns/${e}`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(o.path`/agents/sessions/${e}/turns`,s.CursorPage,{query:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}}t.Turns=a},5414(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Credentials=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{create(e,t,r){return this._client.post(o.path`/vaults/${e}/credentials`,{body:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){const{vault_id:n}=t;return this._client.get(o.path`/vaults/${n}/credentials/${e}`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){const{vault_id:n,...s}=t;return this._client.post(o.path`/vaults/${n}/credentials/${e}`,{body:s,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(o.path`/vaults/${e}/credentials`,s.CursorPage,{query:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){const{vault_id:n}=t;return this._client.delete(o.path`/vaults/${n}/credentials/${e}`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})}}t.Credentials=a},775(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Vaults=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(5414)),o=r(5414),a=r(3604),c=r(3098),l=r(8491);class u extends s.APIResource{constructor(){super(...arguments),this.credentials=new i.Credentials(this._client)}create(e={},t){return this._client.post("/vaults",{body:e,...t,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l.path`/vaults/${e}`,{...t,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vaults",a.CursorPage,{query:e,...t,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l.path`/vaults/${e}`,{...t,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}t.Vaults=u,u.Credentials=o.Credentials},9072(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Assistants=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(o.path`/assistants/${e}`,{...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(o.path`/assistants/${e}`,{body:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",s.CursorPage,{query:e,...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(o.path`/assistants/${e}`,{...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}t.Assistants=a},4395(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Beta=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(9072)),o=r(9072),a=n.__importStar(r(2430)),c=r(2430),l=n.__importStar(r(756)),u=r(756),h=n.__importStar(r(4322)),d=r(4322),f=n.__importStar(r(9026)),p=r(9026),_=n.__importStar(r(7486)),g=r(7486);class m extends s.APIResource{constructor(){super(...arguments),this.realtime=new a.Realtime(this._client),this.agents=new l.Agents(this._client),this.responses=new f.Responses(this._client),this.chatkit=new h.ChatKit(this._client),this.assistants=new i.Assistants(this._client),this.threads=new _.Threads(this._client)}}t.Beta=m,m.Realtime=c.Realtime,m.Agents=u.Agents,m.Responses=p.Responses,m.ChatKit=d.ChatKit,m.Assistants=o.Assistants,m.Threads=g.Threads},4322(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatKit=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(8791)),o=r(8791),a=n.__importStar(r(6565)),c=r(6565);class l extends s.APIResource{constructor(){super(...arguments),this.sessions=new i.Sessions(this._client),this.threads=new a.Threads(this._client)}}t.ChatKit=l,l.Sessions=o.Sessions,l.Threads=c.Threads},8791(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sessions=void 0;const n=r(2596),s=r(3098),i=r(8491);class o extends n.APIResource{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:(0,s.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i.path`/chatkit/sessions/${e}/cancel`,{...t,headers:(0,s.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}}t.Sessions=o},6565(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Threads=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{retrieve(e,t){return this._client.get(o.path`/chatkit/threads/${e}`,{...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",s.ConversationCursorPage,{query:e,...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(o.path`/chatkit/threads/${e}`,{...t,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},r){return this._client.getAPIList(o.path`/chatkit/threads/${e}/items`,s.ConversationCursorPage,{query:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}}t.Threads=a},2430(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Realtime=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(3406)),o=r(3406),a=n.__importStar(r(669)),c=r(669);class l extends s.APIResource{constructor(){super(...arguments),this.sessions=new i.Sessions(this._client),this.transcriptionSessions=new a.TranscriptionSessions(this._client)}}t.Realtime=l,l.Sessions=o.Sessions,l.TranscriptionSessions=c.TranscriptionSessions},3406(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sessions=void 0;const n=r(2596),s=r(3098);class i extends n.APIResource{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:(0,s.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}t.Sessions=i},669(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TranscriptionSessions=void 0;const n=r(2596),s=r(3098);class i extends n.APIResource{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:(0,s.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}t.TranscriptionSessions=i},7871(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InputItems=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{list(e,t={},r){const{betas:n,...a}=t??{};return this._client.getAPIList(o.path`/responses/${e}/input_items?beta=true`,s.CursorPage,{query:a,...r,headers:(0,i.buildHeaders)([{...null!=n?.toString()?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}}t.InputItems=a},3609(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InputTokens=void 0;const n=r(2596),s=r(3098);class i extends n.APIResource{count(e={},t){const{betas:r,...n}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:n,...t,headers:(0,s.buildHeaders)([{...null!=r?.toString()?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}}t.InputTokens=i},9026(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Responses=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(7871)),o=r(7871),a=n.__importStar(r(3609)),c=r(3609),l=r(3098),u=r(8491);class h extends s.APIResource{constructor(){super(...arguments),this.inputItems=new i.InputItems(this._client),this.inputTokens=new a.InputTokens(this._client)}create(e,t){const{betas:r,...n}=e;return this._client.post("/responses?beta=true",{body:n,...t,headers:(0,l.buildHeaders)([{...null!=r?.toString()?{"openai-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},r){const{betas:n,...s}=t??{};return this._client.get(u.path`/responses/${e}?beta=true`,{query:s,...r,headers:(0,l.buildHeaders)([{...null!=n?.toString()?{"openai-beta":n?.toString()}:void 0},r?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},r){const{betas:n}=t??{};return this._client.delete(u.path`/responses/${e}?beta=true`,{...r,headers:(0,l.buildHeaders)([{Accept:"*/*",...null!=n?.toString()?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},r){const{betas:n}=t??{};return this._client.post(u.path`/responses/${e}/cancel?beta=true`,{...r,headers:(0,l.buildHeaders)([{...null!=n?.toString()?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}compact(e,t){const{betas:r,...n}=e;return this._client.post("/responses/compact?beta=true",{body:n,...t,headers:(0,l.buildHeaders)([{...null!=r?.toString()?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}}t.Responses=h,h.InputItems=o.InputItems,h.InputTokens=c.InputTokens},5343(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Messages=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{create(e,t,r){return this._client.post(o.path`/threads/${e}/messages`,{body:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){const{thread_id:n}=t;return this._client.get(o.path`/threads/${n}/messages/${e}`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){const{thread_id:n,...s}=t;return this._client.post(o.path`/threads/${n}/messages/${e}`,{body:s,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(o.path`/threads/${e}/messages`,s.CursorPage,{query:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){const{thread_id:n}=t;return this._client.delete(o.path`/threads/${n}/messages/${e}`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}}t.Messages=a},5870(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Runs=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(3873)),o=r(3873),a=r(3604),c=r(3098),l=r(7288),u=r(1686),h=r(8491);class d extends s.APIResource{constructor(){super(...arguments),this.steps=new i.Steps(this._client)}create(e,t,r){const{include:n,...s}=t;return this._client.post(h.path`/threads/${e}/runs`,{query:{include:n},body:s,...r,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,r){const{thread_id:n}=t;return this._client.get(h.path`/threads/${n}/runs/${e}`,{...r,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){const{thread_id:n,...s}=t;return this._client.post(h.path`/threads/${n}/runs/${e}`,{body:s,...r,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(h.path`/threads/${e}/runs`,a.CursorPage,{query:t,...r,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){const{thread_id:n}=t;return this._client.post(h.path`/threads/${n}/runs/${e}/cancel`,{...r,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return l.AssistantStream.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){return await(0,u.pollAssistantRun)(this,e,t,r)}stream(e,t,r){return l.AssistantStream.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:n,...s}=t;return this._client.post(h.path`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:s,...r,headers:(0,c.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,r){const n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return l.AssistantStream.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}t.Runs=d,d.Steps=o.Steps},3873(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Steps=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(8491);class a extends n.APIResource{retrieve(e,t,r){const{thread_id:n,run_id:s,...a}=t;return this._client.get(o.path`/threads/${n}/runs/${s}/steps/${e}`,{query:a,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t,r){const{thread_id:n,...a}=t;return this._client.getAPIList(o.path`/threads/${n}/runs/${e}/steps`,s.CursorPage,{query:a,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}}t.Steps=a},7486(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Threads=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(5343)),o=r(5343),a=n.__importStar(r(5870)),c=r(5870),l=r(3098),u=r(7288),h=r(8491);class d extends s.APIResource{constructor(){super(...arguments),this.runs=new a.Runs(this._client),this.messages=new i.Messages(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:(0,l.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(h.path`/threads/${e}`,{...t,headers:(0,l.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(h.path`/threads/${e}`,{body:t,...r,headers:(0,l.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(h.path`/threads/${e}`,{...t,headers:(0,l.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:(0,l.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return u.AssistantStream.createThreadAssistantStream(e,this._client.beta.threads,t)}}t.Threads=d,d.Runs=c.Runs,d.Messages=o.Messages},6083(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Chat=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(8826)),o=r(8826);class a extends s.APIResource{constructor(){super(...arguments),this.completions=new i.Completions(this._client)}}t.Chat=a,a.Completions=o.Completions},8826(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatCompletionRunner=t.ChatCompletionStream=t.ParsingToolFunction=t.ChatCompletionStreamingRunner=t.Completions=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(1833)),o=r(1833),a=r(3604),c=r(8491),l=r(7460),u=r(6942),h=r(8634),d=r(1489);class f extends s.APIResource{constructor(){super(...arguments),this.messages=new i.Messages(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(c.path`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(c.path`/chat/completions/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",a.CursorPage,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(c.path`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return(0,d.validateInputTools)(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:"chat.completions.parse"}})._thenUnwrap(t=>(0,d.parseChatCompletion)(t,e))}runTools(e,t){return e.stream?u.ChatCompletionStreamingRunner.runTools(this._client,e,t):l.ChatCompletionRunner.runTools(this._client,e,t)}stream(e,t){return h.ChatCompletionStream.createChatCompletion(this._client,e,t)}}t.Completions=f;var p=r(6942);Object.defineProperty(t,"ChatCompletionStreamingRunner",{enumerable:!0,get:function(){return p.ChatCompletionStreamingRunner}});var _=r(8615);Object.defineProperty(t,"ParsingToolFunction",{enumerable:!0,get:function(){return _.ParsingToolFunction}});var g=r(8634);Object.defineProperty(t,"ChatCompletionStream",{enumerable:!0,get:function(){return g.ChatCompletionStream}});var m=r(7460);Object.defineProperty(t,"ChatCompletionRunner",{enumerable:!0,get:function(){return m.ChatCompletionRunner}}),f.Messages=o.Messages},9153(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Messages=t.Completions=void 0;const n=r(6316);var s=r(8826);Object.defineProperty(t,"Completions",{enumerable:!0,get:function(){return s.Completions}}),n.__exportStar(r(8826),t);var i=r(1833);Object.defineProperty(t,"Messages",{enumerable:!0,get:function(){return i.Messages}})},1833(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Messages=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{list(e,t={},r){return this._client.getAPIList(i.path`/chat/completions/${e}/messages`,s.CursorPage,{query:t,...r,__security:{bearerAuth:!0}})}}t.Messages=o},3353(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Completions=t.Chat=void 0;var n=r(6083);Object.defineProperty(t,"Chat",{enumerable:!0,get:function(){return n.Chat}});var s=r(9153);Object.defineProperty(t,"Completions",{enumerable:!0,get:function(){return s.Completions}})},2873(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Completions=void 0;const n=r(2596);class s extends n.APIResource{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}t.Completions=s},8743(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Containers=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(4624)),o=r(4624),a=r(3604),c=r(3098),l=r(8491);class u extends s.APIResource{constructor(){super(...arguments),this.files=new i.Files(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l.path`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",a.CursorPage,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l.path`/containers/${e}`,{...t,headers:(0,c.buildHeaders)([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}}t.Containers=u,u.Files=o.Files},8922(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Content=void 0;const n=r(2596),s=r(3098),i=r(8491);class o extends n.APIResource{retrieve(e,t,r){const{container_id:n}=t;return this._client.get(i.path`/containers/${n}/files/${e}/content`,{...r,headers:(0,s.buildHeaders)([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}t.Content=o},4624(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Files=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(8922)),o=r(8922),a=r(3604),c=r(3098),l=r(1598),u=r(8491);class h extends s.APIResource{constructor(){super(...arguments),this.content=new i.Content(this._client)}create(e,t,r){return this._client.post(u.path`/containers/${e}/files`,(0,l.maybeMultipartFormRequestOptions)({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){const{container_id:n}=t;return this._client.get(u.path`/containers/${n}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(u.path`/containers/${e}/files`,a.CursorPage,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){const{container_id:n}=t;return this._client.delete(u.path`/containers/${n}/files/${e}`,{...r,headers:(0,c.buildHeaders)([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}}t.Files=h,h.Content=o.Content},8077(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ContentProvenanceChecks=void 0;const n=r(2596),s=r(1598);class i extends n.APIResource{create(e,t){return this._client.post("/content_provenance_checks",(0,s.multipartFormRequestOptions)({body:e,...t,__security:{bearerAuth:!0}},this._client))}}t.ContentProvenanceChecks=i},9609(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Conversations=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(3025)),o=r(3025),a=r(8491);class c extends s.APIResource{constructor(){super(...arguments),this.items=new i.Items(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a.path`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(a.path`/conversations/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a.path`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}}t.Conversations=c,c.Items=o.Items},3025(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Items=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t,r){const{include:n,...s}=t;return this._client.post(i.path`/conversations/${e}/items`,{query:{include:n},body:s,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){const{conversation_id:n,...s}=t;return this._client.get(i.path`/conversations/${n}/items/${e}`,{query:s,...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i.path`/conversations/${e}/items`,s.ConversationCursorPage,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){const{conversation_id:n}=t;return this._client.delete(i.path`/conversations/${n}/items/${e}`,{...r,__security:{bearerAuth:!0}})}}t.Items=o},6566(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Embeddings=void 0;const n=r(2596),s=r(316);class i extends n.APIResource{create(e,t){return(0,s.createEmbedding)(this._client,e,t)}}t.Embeddings=i},5733(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Evals=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(1511)),o=r(1511),a=r(3604),c=r(8491);class l extends s.APIResource{constructor(){super(...arguments),this.runs=new i.Runs(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(c.path`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(c.path`/evals/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",a.CursorPage,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(c.path`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}}t.Evals=l,l.Runs=o.Runs},9825(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OutputItems=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{retrieve(e,t,r){const{eval_id:n,run_id:s}=t;return this._client.get(i.path`/evals/${n}/runs/${s}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t,r){const{eval_id:n,...o}=t;return this._client.getAPIList(i.path`/evals/${n}/runs/${e}/output_items`,s.CursorPage,{query:o,...r,__security:{bearerAuth:!0}})}}t.OutputItems=o},1511(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Runs=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(9825)),o=r(9825),a=r(3604),c=r(8491);class l extends s.APIResource{constructor(){super(...arguments),this.outputItems=new i.OutputItems(this._client)}create(e,t,r){return this._client.post(c.path`/evals/${e}/runs`,{body:t,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){const{eval_id:n}=t;return this._client.get(c.path`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(c.path`/evals/${e}/runs`,a.CursorPage,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){const{eval_id:n}=t;return this._client.delete(c.path`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,t,r){const{eval_id:n}=t;return this._client.post(c.path`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}}t.Runs=l,l.OutputItems=o.OutputItems},7225(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Files=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(1598),a=r(7998),c=r(8491);class l extends n.APIResource{create(e,t){return this._client.post("/files",(0,o.multipartFormRequestOptions)({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(c.path`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",s.CursorPage,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(c.path`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(c.path`/files/${e}/content`,{...t,headers:(0,i.buildHeaders)([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=18e5}={}){return await(0,a.waitForFileProcessing)(this,e,t,r)}}t.Files=l},6312(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Alpha=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(6976)),o=r(6976);class a extends s.APIResource{constructor(){super(...arguments),this.graders=new i.Graders(this._client)}}t.Alpha=a,a.Graders=o.Graders},6976(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Graders=void 0;const n=r(2596);class s extends n.APIResource{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}}t.Graders=s},2432(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Checkpoints=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(703)),o=r(703);class a extends s.APIResource{constructor(){super(...arguments),this.permissions=new i.Permissions(this._client)}}t.Checkpoints=a,a.Permissions=o.Permissions},703(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Permissions=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{create(e,t,r){return this._client.getAPIList(i.path`/fine_tuning/checkpoints/${e}/permissions`,s.Page,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i.path`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i.path`/fine_tuning/checkpoints/${e}/permissions`,s.ConversationCursorPage,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){const{fine_tuned_model_checkpoint:n}=t;return this._client.delete(i.path`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}t.Permissions=o},5857(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FineTuning=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(7269)),o=r(7269),a=n.__importStar(r(6312)),c=r(6312),l=n.__importStar(r(2432)),u=r(2432),h=n.__importStar(r(1338)),d=r(1338);class f extends s.APIResource{constructor(){super(...arguments),this.methods=new i.Methods(this._client),this.jobs=new h.Jobs(this._client),this.checkpoints=new l.Checkpoints(this._client),this.alpha=new a.Alpha(this._client)}}t.FineTuning=f,f.Methods=o.Methods,f.Jobs=d.Jobs,f.Checkpoints=u.Checkpoints,f.Alpha=c.Alpha},279(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Checkpoints=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{list(e,t={},r){return this._client.getAPIList(i.path`/fine_tuning/jobs/${e}/checkpoints`,s.CursorPage,{query:t,...r,__security:{bearerAuth:!0}})}}t.Checkpoints=o},1338(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Jobs=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(279)),o=r(279),a=r(3604),c=r(8491);class l extends s.APIResource{constructor(){super(...arguments),this.checkpoints=new i.Checkpoints(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(c.path`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",a.CursorPage,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(c.path`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},r){return this._client.getAPIList(c.path`/fine_tuning/jobs/${e}/events`,a.CursorPage,{query:t,...r,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(c.path`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(c.path`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}}t.Jobs=l,l.Checkpoints=o.Checkpoints},7269(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Methods=void 0;const n=r(2596);class s extends n.APIResource{}t.Methods=s},37(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GraderModels=void 0;const n=r(2596);class s extends n.APIResource{}t.GraderModels=s},4149(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Graders=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(37)),o=r(37);class a extends s.APIResource{constructor(){super(...arguments),this.graderModels=new i.GraderModels(this._client)}}t.Graders=a,a.GraderModels=o.GraderModels},2566(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Images=void 0;const n=r(2596),s=r(1598);class i extends n.APIResource{createVariation(e,t){return this._client.post("/images/variations",(0,s.multipartFormRequestOptions)({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",(0,s.multipartFormRequestOptions)({body:e,...t,stream:e.stream??!1,__metadata:{...t?.__metadata,...null==e.model?{}:{model:e.model}},__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}t.Images=i},3998(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Webhooks=t.Videos=t.VectorStores=t.Uploads=t.Skills=t.Safety=t.Responses=t.Realtime=t.Moderations=t.Models=t.Live=t.Images=t.Graders=t.FineTuning=t.Files=t.Evals=t.Embeddings=t.Conversations=t.ContentProvenanceChecks=t.Containers=t.Completions=t.Beta=t.Batches=t.Audio=t.Admin=void 0;const n=r(6316);n.__exportStar(r(3353),t),n.__exportStar(r(425),t);var s=r(2157);Object.defineProperty(t,"Admin",{enumerable:!0,get:function(){return s.Admin}});var i=r(4425);Object.defineProperty(t,"Audio",{enumerable:!0,get:function(){return i.Audio}});var o=r(8398);Object.defineProperty(t,"Batches",{enumerable:!0,get:function(){return o.Batches}});var a=r(4395);Object.defineProperty(t,"Beta",{enumerable:!0,get:function(){return a.Beta}});var c=r(2873);Object.defineProperty(t,"Completions",{enumerable:!0,get:function(){return c.Completions}});var l=r(8743);Object.defineProperty(t,"Containers",{enumerable:!0,get:function(){return l.Containers}});var u=r(8077);Object.defineProperty(t,"ContentProvenanceChecks",{enumerable:!0,get:function(){return u.ContentProvenanceChecks}});var h=r(9609);Object.defineProperty(t,"Conversations",{enumerable:!0,get:function(){return h.Conversations}});var d=r(6566);Object.defineProperty(t,"Embeddings",{enumerable:!0,get:function(){return d.Embeddings}});var f=r(5733);Object.defineProperty(t,"Evals",{enumerable:!0,get:function(){return f.Evals}});var p=r(7225);Object.defineProperty(t,"Files",{enumerable:!0,get:function(){return p.Files}});var _=r(5857);Object.defineProperty(t,"FineTuning",{enumerable:!0,get:function(){return _.FineTuning}});var g=r(4149);Object.defineProperty(t,"Graders",{enumerable:!0,get:function(){return g.Graders}});var m=r(2566);Object.defineProperty(t,"Images",{enumerable:!0,get:function(){return m.Images}});var y=r(5819);Object.defineProperty(t,"Live",{enumerable:!0,get:function(){return y.Live}});var A=r(9662);Object.defineProperty(t,"Models",{enumerable:!0,get:function(){return A.Models}});var v=r(1955);Object.defineProperty(t,"Moderations",{enumerable:!0,get:function(){return v.Moderations}});var b=r(8725);Object.defineProperty(t,"Realtime",{enumerable:!0,get:function(){return b.Realtime}});var w=r(1713);Object.defineProperty(t,"Responses",{enumerable:!0,get:function(){return w.Responses}});var E=r(6399);Object.defineProperty(t,"Safety",{enumerable:!0,get:function(){return E.Safety}});var I=r(8667);Object.defineProperty(t,"Skills",{enumerable:!0,get:function(){return I.Skills}});var S=r(4077);Object.defineProperty(t,"Uploads",{enumerable:!0,get:function(){return S.Uploads}});var P=r(4953);Object.defineProperty(t,"VectorStores",{enumerable:!0,get:function(){return P.VectorStores}});var k=r(9360);Object.defineProperty(t,"Videos",{enumerable:!0,get:function(){return k.Videos}});var O=r(4626);Object.defineProperty(t,"Webhooks",{enumerable:!0,get:function(){return O.Webhooks}})},954(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Forks=void 0;const n=r(2596);class s extends n.APIResource{}t.Forks=s},5819(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Live=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(240)),o=r(240),a=n.__importStar(r(954)),c=r(954),l=n.__importStar(r(4036)),u=r(4036);class h extends s.APIResource{constructor(){super(...arguments),this.sideband=new l.Sideband(this._client),this.forks=new a.Forks(this._client),this.sessions=new i.Sessions(this._client)}create(e,t){return this._client.post("/live/sessions",{body:e,...t,__security:{bearerAuth:!0}})}}t.Live=h,h.Sideband=u.Sideband,h.Forks=c.Forks,h.Sessions=o.Sessions},240(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sessions=void 0;const n=r(2596),s=r(3098),i=r(8491);class o extends n.APIResource{accept(e,t,r){return this._client.post(i.path`/live/sessions/${e}/accept`,{body:t,...r,headers:(0,s.buildHeaders)([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}downloadRecording(e,t){return this._client.get(i.path`/live/sessions/${e}/content`,{...t,headers:(0,s.buildHeaders)([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}fork(e,t,r){return this._client.post(i.path`/live/sessions/${e}/fork`,{body:t,...r,__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(i.path`/live/sessions/${e}/hangup`,{...t,headers:(0,s.buildHeaders)([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post(i.path`/live/sessions/${e}/refer`,{body:t,...r,headers:(0,s.buildHeaders)([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t,r){return this._client.post(i.path`/live/sessions/${e}/reject`,{body:t,...r,headers:(0,s.buildHeaders)([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}}t.Sessions=o},4036(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Sideband=void 0;const n=r(2596);class s extends n.APIResource{}t.Sideband=s},9662(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Models=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{retrieve(e,t){return this._client.get(i.path`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",s.Page,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i.path`/models/${e}`,{...t,__security:{bearerAuth:!0}})}}t.Models=o},1955(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Moderations=void 0;const n=r(2596);class s extends n.APIResource{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}}t.Moderations=s},4299(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Calls=void 0;const n=r(2596),s=r(3098),i=r(8491),o=r(4184);class a extends n.APIResource{create(e,t){return this._client.post("/realtime/calls",(0,o.encodedMultipartFormRequestOptions)({body:e,...t,headers:(0,s.buildHeaders)([{Accept:"application/sdp"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0},this._client,{sdp:{content_type:"application/sdp",json:!1},session:{content_type:"application/json",json:!0}},"sdp"))}accept(e,t,r){return this._client.post(i.path`/realtime/calls/${e}/accept`,{body:t,...r,headers:(0,s.buildHeaders)([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(i.path`/realtime/calls/${e}/hangup`,{...t,headers:(0,s.buildHeaders)([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post(i.path`/realtime/calls/${e}/refer`,{body:t,...r,headers:(0,s.buildHeaders)([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post(i.path`/realtime/calls/${e}/reject`,{body:t,...r,headers:(0,s.buildHeaders)([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}}t.Calls=a},5795(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ClientSecrets=void 0;const n=r(2596);class s extends n.APIResource{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}}t.ClientSecrets=s},8725(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Realtime=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(4299)),o=r(4299),a=n.__importStar(r(5795)),c=r(5795);class l extends s.APIResource{constructor(){super(...arguments),this.clientSecrets=new a.ClientSecrets(this._client),this.calls=new i.Calls(this._client)}}t.Realtime=l,l.ClientSecrets=c.ClientSecrets,l.Calls=o.Calls},2012(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InputItems=void 0;const n=r(2596),s=r(3604),i=r(8491);class o extends n.APIResource{list(e,t={},r){return this._client.getAPIList(i.path`/responses/${e}/input_items`,s.CursorPage,{query:t,...r,__security:{bearerAuth:!0}})}}t.InputItems=o},507(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.InputTokens=void 0;const n=r(2596);class s extends n.APIResource{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}}t.InputTokens=s},1713(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Responses=void 0;const n=r(6316),s=r(2987),i=r(7800),o=r(2596),a=n.__importStar(r(2012)),c=r(2012),l=n.__importStar(r(507)),u=r(507),h=r(3098),d=r(8491);class f extends o.APIResource{constructor(){super(...arguments),this.inputItems=new a.InputItems(this._client),this.inputTokens=new l.InputTokens(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>("object"in e&&"response"===e.object&&(0,s.addOutputText)(e),e))}retrieve(e,t={},r){return this._client.get(d.path`/responses/${e}`,{query:t,...r,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>("object"in e&&"response"===e.object&&(0,s.addOutputText)(e),e))}delete(e,t){return this._client.delete(d.path`/responses/${e}`,{...t,headers:(0,h.buildHeaders)([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>(0,s.parseResponse)(t,e))}stream(e,t){return i.ResponseStream.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(d.path`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}}t.Responses=f,f.InputItems=c.InputItems,f.InputTokens=u.InputTokens},9114(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Alerts=void 0;const n=r(2596),s=r(8491);class i extends n.APIResource{retrieve(e,t){return this._client.get(s.path`/safety/alerts/${e}`,{...t,__security:{bearerAuth:!0}})}}t.Alerts=i},6399(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Safety=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(9114)),o=r(9114);class a extends s.APIResource{constructor(){super(...arguments),this.alerts=new i.Alerts(this._client)}}t.Safety=a,a.Alerts=o.Alerts},425(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},5660(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Content=void 0;const n=r(2596),s=r(3098),i=r(8491);class o extends n.APIResource{retrieve(e,t){return this._client.get(i.path`/skills/${e}/content`,{...t,headers:(0,s.buildHeaders)([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}t.Content=o},8667(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Skills=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(5660)),o=r(5660),a=n.__importStar(r(6498)),c=r(6498),l=r(3604),u=r(1598),h=r(8491);class d extends s.APIResource{constructor(){super(...arguments),this.content=new i.Content(this._client),this.versions=new a.Versions(this._client)}create(e={},t){return this._client.post("/skills",(0,u.maybeMultipartFormRequestOptions)({body:e,...t,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t){return this._client.get(h.path`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(h.path`/skills/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",l.CursorPage,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(h.path`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}}t.Skills=d,d.Content=o.Content,d.Versions=c.Versions},9642(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Content=void 0;const n=r(2596),s=r(3098),i=r(8491);class o extends n.APIResource{retrieve(e,t,r){const{skill_id:n}=t;return this._client.get(i.path`/skills/${n}/versions/${e}/content`,{...r,headers:(0,s.buildHeaders)([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}t.Content=o},6498(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Versions=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(9642)),o=r(9642),a=r(3604),c=r(1598),l=r(8491);class u extends s.APIResource{constructor(){super(...arguments),this.content=new i.Content(this._client)}create(e,t={},r){return this._client.post(l.path`/skills/${e}/versions`,(0,c.maybeMultipartFormRequestOptions)({body:t,...r,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t,r){const{skill_id:n}=t;return this._client.get(l.path`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(l.path`/skills/${e}/versions`,a.CursorPage,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){const{skill_id:n}=t;return this._client.delete(l.path`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}}t.Versions=u,u.Content=o.Content},6337(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Parts=void 0;const n=r(2596),s=r(1598),i=r(8491);class o extends n.APIResource{create(e,t,r){return this._client.post(i.path`/uploads/${e}/parts`,(0,s.multipartFormRequestOptions)({body:t,...r,__security:{bearerAuth:!0}},this._client))}}t.Parts=o},4077(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Uploads=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(6337)),o=r(6337),a=r(8491);class c extends s.APIResource{constructor(){super(...arguments),this.parts=new i.Parts(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a.path`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,r){return this._client.post(a.path`/uploads/${e}/complete`,{body:t,...r,__security:{bearerAuth:!0}})}}t.Uploads=c,c.Parts=o.Parts},9382(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FileBatches=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(6471),a=r(6507),c=r(8491);class l extends n.APIResource{create(e,t,r){return this._client.post(c.path`/vector_stores/${e}/file_batches`,{body:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){const{vector_store_id:n}=t;return this._client.get(c.path`/vector_stores/${n}/file_batches/${e}`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){const{vector_store_id:n}=t;return this._client.post(c.path`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(e,n.id,r)}listFiles(e,t,r){const{vector_store_id:n,...o}=t;return this._client.getAPIList(c.path`/vector_stores/${n}/file_batches/${e}/files`,s.CursorPage,{query:o,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){return await(0,o.pollVectorStoreFileBatch)(this,e,t,r)}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){return await(0,a.uploadAndPollVectorStoreFileBatch)(this,this._client,e,t,r,n)}}t.FileBatches=l},5506(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Files=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(6471),a=r(8491);class c extends n.APIResource{create(e,t,r){return this._client.post(a.path`/vector_stores/${e}/files`,{body:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){const{vector_store_id:n}=t;return this._client.get(a.path`/vector_stores/${n}/files/${e}`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){const{vector_store_id:n,...s}=t;return this._client.post(a.path`/vector_stores/${n}/files/${e}`,{body:s,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(a.path`/vector_stores/${e}/files`,s.CursorPage,{query:t,...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){const{vector_store_id:n}=t;return this._client.delete(a.path`/vector_stores/${n}/files/${e}`,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){return await(0,o.pollVectorStoreFile)(this,e,t,r)}async upload(e,t,r){const n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){const n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){const{vector_store_id:n}=t;return this._client.getAPIList(a.path`/vector_stores/${n}/files/${e}/content`,s.Page,{...r,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}}t.Files=c},4953(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.VectorStores=void 0;const n=r(6316),s=r(2596),i=n.__importStar(r(9382)),o=r(9382),a=n.__importStar(r(5506)),c=r(5506),l=r(3604),u=r(3098),h=r(8491);class d extends s.APIResource{constructor(){super(...arguments),this.files=new a.Files(this._client),this.fileBatches=new i.FileBatches(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:(0,u.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(h.path`/vector_stores/${e}`,{...t,headers:(0,u.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(h.path`/vector_stores/${e}`,{body:t,...r,headers:(0,u.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",l.CursorPage,{query:e,...t,headers:(0,u.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(h.path`/vector_stores/${e}`,{...t,headers:(0,u.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,r){return this._client.getAPIList(h.path`/vector_stores/${e}/search`,l.Page,{body:t,method:"post",...r,headers:(0,u.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}}t.VectorStores=d,d.Files=c.Files,d.FileBatches=o.FileBatches},9360(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Videos=void 0;const n=r(2596),s=r(3604),i=r(3098),o=r(1598),a=r(8491);class c extends n.APIResource{create(e,t){return this._client.post("/videos",(0,o.multipartFormRequestOptions)({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(a.path`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",s.ConversationCursorPage,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a.path`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",(0,o.multipartFormRequestOptions)({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get(a.path`/videos/${e}/content`,{query:t,...r,headers:(0,i.buildHeaders)([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",(0,o.multipartFormRequestOptions)({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",(0,o.multipartFormRequestOptions)({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(a.path`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,r){return this._client.post(a.path`/videos/${e}/remix`,(0,o.maybeMultipartFormRequestOptions)({body:t,...r,__security:{bearerAuth:!0}},this._client))}}t.Videos=c},4626(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(6316).__exportStar(r(209),t)},209(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(6316).__exportStar(r(4015),t)},4015(e,t,r){"use strict";var n,s,i;Object.defineProperty(t,"__esModule",{value:!0}),t.Webhooks=void 0;const o=r(6316),a=r(2596),c=r(3098),l=r(9110);class u extends a.APIResource{constructor(){super(...arguments),n.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,a=300){if("undefined"==typeof crypto||"function"!=typeof crypto.subtle?.importKey||"function"!=typeof crypto.subtle.verify)throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");o.__classPrivateFieldGet(this,n,"m",s).call(this,r);const u=(0,c.buildHeaders)([t]).values,h=o.__classPrivateFieldGet(this,n,"m",i).call(this,u,"webhook-signature"),d=o.__classPrivateFieldGet(this,n,"m",i).call(this,u,"webhook-timestamp"),f=o.__classPrivateFieldGet(this,n,"m",i).call(this,u,"webhook-id");if((0,l.webhookSignatureRequiresSigning)(h)&&"function"!=typeof crypto.subtle.sign)throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");return await(0,l.verifyWebhookSignature)(e,h,d,f,r,a)}}t.Webhooks=u,n=new WeakSet,s=function(e){if("string"!=typeof e||0===e.length)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},i=function(e,t){if(!e)throw new Error("Headers are required");const r=e.get(t);if(null==r)throw new Error(`Missing required header: ${t}`);return r}},3528(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(6316).__exportStar(r(7542),t)},3284(e,t){"use strict";t.VERSION=void 0,t.VERSION="7.15.0"},8342(e){"use strict";e.exports={rE:"1.17.0"}}};const t={};function r(n){const s=t[n];if(void 0!==s)return s.exports;const i=t[n]={id:n,loaded:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}void 0!==r&&(r.ab=__dirname+"/native_modules/"),r.nmd=e=>(e.paths=[],e.children||(e.children=[]),e);let n=r(82);module.exports=n})();
|
|
2
|
+
//# sourceMappingURL=index.js.map
|