diff --git a/.github/workflows/vim-release.yml b/.github/workflows/vim-release.yml new file mode 100644 index 0000000..002de04 --- /dev/null +++ b/.github/workflows/vim-release.yml @@ -0,0 +1,19 @@ +name: Release Vim Plugin + +on: + workflow_dispatch: + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + - uses: olivr/copybara-action@v1.2.3 + with: + ssh_key: ${{ secrets.VIM_RELEASE_SSH_KEY }} + access_token: ${{ secrets.VIM_RELEASE_GH_TOKEN }} + sot_repo: TabbyML/tabby + destination_repo: TabbyML/vim-tabby + push_include: "clients/vim/**" diff --git a/clients/vim/LICENSE b/clients/vim/LICENSE new file mode 100644 index 0000000..af66488 --- /dev/null +++ b/clients/vim/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [2023] [TabbyML] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/clients/vim/README.md b/clients/vim/README.md index 253c42d..6c23f96 100644 --- a/clients/vim/README.md +++ b/clients/vim/README.md @@ -18,6 +18,8 @@ If you encounter any problem or have any suggestion, please [open an issue](http - [Node.js Binary Path](#nodejs-binary-path) - [Completion Trigger Mode](#completion-trigger-mode) - [KeyBindings](#keybindings) + - [Contributing](#contributing) + - [License](#license) ## Requirements @@ -165,3 +167,11 @@ let g:tabby_keybinding_trigger_or_dismiss = '' vim.g.tabby_keybinding_accept = '' vim.g.tabby_keybinding_trigger_or_dismiss = '' ``` + +## Contributing + +Repository [TabbyML/vim-tabby](https://github.com/TabbyML/vim-tabby) is for releasing Tabby plugin for Vim and NeoVim. If you want to contribute to Tabby plugin, please check our main repository [TabbyML/tabby](https://github.com/TabbyML/tabby/tree/main/clients/vim). + +## License + +[Apache-2.0](https://github.com/TabbyML/tabby/blob/main/LICENSE) diff --git a/clients/vim/autoload/tabby/globals.vim b/clients/vim/autoload/tabby/globals.vim index 166af97..34eba03 100644 --- a/clients/vim/autoload/tabby/globals.vim +++ b/clients/vim/autoload/tabby/globals.vim @@ -50,5 +50,5 @@ function! tabby#globals#Load() " Version of Tabby plugin. Not configurable. - let g:tabby_version = "1.0.0-dev" + let g:tabby_version = "1.0.0" endfunction \ No newline at end of file diff --git a/clients/vim/node_scripts/tabby-agent.js b/clients/vim/node_scripts/tabby-agent.js index 1a7a2c3..e97017a 100755 --- a/clients/vim/node_scripts/tabby-agent.js +++ b/clients/vim/node_scripts/tabby-agent.js @@ -194,7 +194,7 @@ Use "options.replacer" or "options.ignoreUnknown" # disable = false # set to true to disable `,bn=(()=>{let t=z("events"),e=Al(),r=sS(),n=n0();class s extends t{constructor(c){super();this.data={};this.watcher=null;this.logger=(Nt(),zo(Zw)).rootLogger.child({component:"ConfigFile"});this.filepath=c;}get config(){return this.data}async load(){try{let c=await e.readFile(this.filepath,"utf8");if(c.trim()===oq.trim())return await this.createTemplate(),await this.load();this.data=r.parse(c),super.emit("updated",this.data);}catch(c){c.code==="ENOENT"?await this.createTemplate():this.logger.error({error:c},"Failed to load config file");}}async createTemplate(){try{await e.outputFile(this.filepath,aq);}catch(c){this.logger.error({error:c},"Failed to create config template file");}}watch(){this.watcher=n.watch(this.filepath,{interval:1e3}),this.watcher.on("add",this.load.bind(this)),this.watcher.on("change",this.load.bind(this));}}let i=z("path").join(z("os").homedir(),".tabby-client","agent","config.toml");return new s(i)})();var wi=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,s0=new Set,vc=typeof process=="object"&&process?process:{},o0=(t,e,r,n)=>{typeof vc.emitWarning=="function"?vc.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`);},xo=globalThis.AbortController,i0=globalThis.AbortSignal;if(typeof xo>"u"){i0=class{constructor(){ne(this,"onabort");ne(this,"_onabort",[]);ne(this,"reason");ne(this,"aborted",!1);}addEventListener(n,s){this._onabort.push(s);}},xo=class{constructor(){ne(this,"signal",new i0);e();}abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let s of this.signal._onabort)s(n);this.signal.onabort?.(n);}}};let t=vc.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,o0("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e));};}var lq=t=>!s0.has(t),yr=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),a0=t=>yr(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?En:null:null,En=class extends Array{constructor(e){super(e),this.fill(0);}},An,Mr=class Mr{constructor(e,r){ne(this,"heap");ne(this,"length");if(!S(Mr,An))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0;}static create(e){let r=a0(e);if(!r)return [];re(Mr,An,!0);let n=new Mr(e,r);return re(Mr,An,!1),n}push(e){this.heap[this.length++]=e;}pop(){return this.heap[--this.length]}};An=new WeakMap,ae(Mr,An,!1);var wc=Mr,Ct,ft,jt,Rt,_n,Te,Ot,$e,Se,oe,Je,ht,ze,qe,Pt,Ue,Yt,Jt,Tt,Bt,wr,it,bi,Sc,jr,Xt,Ei,pt,Ro,l0,Br,xn,Ai,Ht,mr,Ut,vr,_i,bc,Cn,Ao,Rn,_o,ve,be,xi,Ec,Hr,Si,Ac=class Ac{constructor(e){ae(this,bi);ae(this,Ro);ae(this,Ht);ae(this,Ut);ae(this,_i);ae(this,Cn);ae(this,Rn);ae(this,ve);ae(this,xi);ae(this,Hr);ae(this,Ct,void 0);ae(this,ft,void 0);ae(this,jt,void 0);ae(this,Rt,void 0);ae(this,_n,void 0);ne(this,"ttl");ne(this,"ttlResolution");ne(this,"ttlAutopurge");ne(this,"updateAgeOnGet");ne(this,"updateAgeOnHas");ne(this,"allowStale");ne(this,"noDisposeOnSet");ne(this,"noUpdateTTL");ne(this,"maxEntrySize");ne(this,"sizeCalculation");ne(this,"noDeleteOnFetchRejection");ne(this,"noDeleteOnStaleGet");ne(this,"allowStaleOnFetchAbort");ne(this,"allowStaleOnFetchRejection");ne(this,"ignoreFetchAbort");ae(this,Te,void 0);ae(this,Ot,void 0);ae(this,$e,void 0);ae(this,Se,void 0);ae(this,oe,void 0);ae(this,Je,void 0);ae(this,ht,void 0);ae(this,ze,void 0);ae(this,qe,void 0);ae(this,Pt,void 0);ae(this,Ue,void 0);ae(this,Yt,void 0);ae(this,Jt,void 0);ae(this,Tt,void 0);ae(this,Bt,void 0);ae(this,wr,void 0);ae(this,it,void 0);ae(this,jr,()=>{});ae(this,Xt,()=>{});ae(this,Ei,()=>{});ae(this,pt,()=>!1);ae(this,Br,e=>{});ae(this,xn,(e,r,n)=>{});ae(this,Ai,(e,r,n,s)=>{if(n||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0});let{max:r=0,ttl:n,ttlResolution:s=1,ttlAutopurge:i,updateAgeOnGet:o,updateAgeOnHas:l,allowStale:c,dispose:p,disposeAfter:u,noDisposeOnSet:g,noUpdateTTL:y,maxSize:m=0,maxEntrySize:v=0,sizeCalculation:b,fetchMethod:_,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:O,allowStaleOnFetchAbort:I,ignoreFetchAbort:F}=e;if(r!==0&&!yr(r))throw new TypeError("max option must be a nonnegative integer");let U=r?a0(r):Array;if(!U)throw new Error("invalid max value: "+r);if(re(this,Ct,r),re(this,ft,m),this.maxEntrySize=v||S(this,ft),this.sizeCalculation=b,this.sizeCalculation){if(!S(this,ft)&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(_!==void 0&&typeof _!="function")throw new TypeError("fetchMethod must be a function if specified");if(re(this,_n,_),re(this,wr,!!_),re(this,$e,new Map),re(this,Se,new Array(r).fill(void 0)),re(this,oe,new Array(r).fill(void 0)),re(this,Je,new U(r)),re(this,ht,new U(r)),re(this,ze,0),re(this,qe,0),re(this,Pt,wc.create(r)),re(this,Te,0),re(this,Ot,0),typeof p=="function"&&re(this,jt,p),typeof u=="function"?(re(this,Rt,u),re(this,Ue,[])):(re(this,Rt,void 0),re(this,Ue,void 0)),re(this,Bt,!!S(this,jt)),re(this,it,!!S(this,Rt)),this.noDisposeOnSet=!!g,this.noUpdateTTL=!!y,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!O,this.allowStaleOnFetchAbort=!!I,this.ignoreFetchAbort=!!F,this.maxEntrySize!==0){if(S(this,ft)!==0&&!yr(S(this,ft)))throw new TypeError("maxSize must be a positive integer if specified");if(!yr(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");ee(this,Ro,l0).call(this);}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!l,this.ttlResolution=yr(s)||s===0?s:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!yr(this.ttl))throw new TypeError("ttl must be a positive integer if specified");ee(this,bi,Sc).call(this);}if(S(this,Ct)===0&&this.ttl===0&&S(this,ft)===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!S(this,Ct)&&!S(this,ft)){let H="LRU_CACHE_UNBOUNDED";lq(H)&&(s0.add(H),o0("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",H,Ac));}}static unsafeExposeInternals(e){return {starts:S(e,Jt),ttls:S(e,Tt),sizes:S(e,Yt),keyMap:S(e,$e),keyList:S(e,Se),valList:S(e,oe),next:S(e,Je),prev:S(e,ht),get head(){return S(e,ze)},get tail(){return S(e,qe)},free:S(e,Pt),isBackgroundFetch:r=>{var n;return ee(n=e,ve,be).call(n,r)},backgroundFetch:(r,n,s,i)=>{var o;return ee(o=e,Rn,_o).call(o,r,n,s,i)},moveToTail:r=>{var n;return ee(n=e,Hr,Si).call(n,r)},indexes:r=>{var n;return ee(n=e,Ht,mr).call(n,r)},rindexes:r=>{var n;return ee(n=e,Ut,vr).call(n,r)},isStale:r=>{var n;return S(n=e,pt).call(n,r)}}}get max(){return S(this,Ct)}get maxSize(){return S(this,ft)}get calculatedSize(){return S(this,Ot)}get size(){return S(this,Te)}get fetchMethod(){return S(this,_n)}get dispose(){return S(this,jt)}get disposeAfter(){return S(this,Rt)}getRemainingTTL(e){return S(this,$e).has(e)?1/0:0}*entries(){for(let e of ee(this,Ht,mr).call(this))S(this,oe)[e]!==void 0&&S(this,Se)[e]!==void 0&&!ee(this,ve,be).call(this,S(this,oe)[e])&&(yield [S(this,Se)[e],S(this,oe)[e]]);}*rentries(){for(let e of ee(this,Ut,vr).call(this))S(this,oe)[e]!==void 0&&S(this,Se)[e]!==void 0&&!ee(this,ve,be).call(this,S(this,oe)[e])&&(yield [S(this,Se)[e],S(this,oe)[e]]);}*keys(){for(let e of ee(this,Ht,mr).call(this)){let r=S(this,Se)[e];r!==void 0&&!ee(this,ve,be).call(this,S(this,oe)[e])&&(yield r);}}*rkeys(){for(let e of ee(this,Ut,vr).call(this)){let r=S(this,Se)[e];r!==void 0&&!ee(this,ve,be).call(this,S(this,oe)[e])&&(yield r);}}*values(){for(let e of ee(this,Ht,mr).call(this))S(this,oe)[e]!==void 0&&!ee(this,ve,be).call(this,S(this,oe)[e])&&(yield S(this,oe)[e]);}*rvalues(){for(let e of ee(this,Ut,vr).call(this))S(this,oe)[e]!==void 0&&!ee(this,ve,be).call(this,S(this,oe)[e])&&(yield S(this,oe)[e]);}[Symbol.iterator](){return this.entries()}find(e,r={}){for(let n of ee(this,Ht,mr).call(this)){let s=S(this,oe)[n],i=ee(this,ve,be).call(this,s)?s.__staleWhileFetching:s;if(i!==void 0&&e(i,S(this,Se)[n],this))return this.get(S(this,Se)[n],r)}}forEach(e,r=this){for(let n of ee(this,Ht,mr).call(this)){let s=S(this,oe)[n],i=ee(this,ve,be).call(this,s)?s.__staleWhileFetching:s;i!==void 0&&e.call(r,i,S(this,Se)[n],this);}}rforEach(e,r=this){for(let n of ee(this,Ut,vr).call(this)){let s=S(this,oe)[n],i=ee(this,ve,be).call(this,s)?s.__staleWhileFetching:s;i!==void 0&&e.call(r,i,S(this,Se)[n],this);}}purgeStale(){let e=!1;for(let r of ee(this,Ut,vr).call(this,{allowStale:!0}))S(this,pt).call(this,r)&&(this.delete(S(this,Se)[r]),e=!0);return e}dump(){let e=[];for(let r of ee(this,Ht,mr).call(this,{allowStale:!0})){let n=S(this,Se)[r],s=S(this,oe)[r],i=ee(this,ve,be).call(this,s)?s.__staleWhileFetching:s;if(i===void 0||n===void 0)continue;let o={value:i};if(S(this,Tt)&&S(this,Jt)){o.ttl=S(this,Tt)[r];let l=wi.now()-S(this,Jt)[r];o.start=Math.floor(Date.now()-l);}S(this,Yt)&&(o.size=S(this,Yt)[r]),e.unshift([n,o]);}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let s=Date.now()-n.start;n.start=wi.now()-s;}this.set(r,n.value,n);}}set(e,r,n={}){var y,m;if(r===void 0)return this.delete(e),this;let{ttl:s=this.ttl,start:i,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:l=this.sizeCalculation,status:c}=n,{noUpdateTTL:p=this.noUpdateTTL}=n,u=S(this,Ai).call(this,e,r,n.size||0,l);if(this.maxEntrySize&&u>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.delete(e),this;let g=S(this,Te)===0?void 0:S(this,$e).get(e);if(g===void 0)g=S(this,Te)===0?S(this,qe):S(this,Pt).length!==0?S(this,Pt).pop():S(this,Te)===S(this,Ct)?ee(this,Cn,Ao).call(this,!1):S(this,Te),S(this,Se)[g]=e,S(this,oe)[g]=r,S(this,$e).set(e,g),S(this,Je)[S(this,qe)]=g,S(this,ht)[g]=S(this,qe),re(this,qe,g),Di(this,Te)._++,S(this,xn).call(this,g,u,c),c&&(c.set="add"),p=!1;else {ee(this,Hr,Si).call(this,g);let v=S(this,oe)[g];if(r!==v){if(S(this,wr)&&ee(this,ve,be).call(this,v)?v.__abortController.abort(new Error("replaced")):o||(S(this,Bt)&&((y=S(this,jt))==null||y.call(this,v,e,"set")),S(this,it)&&S(this,Ue)?.push([v,e,"set"])),S(this,Br).call(this,g),S(this,xn).call(this,g,u,c),S(this,oe)[g]=r,c){c.set="replace";let b=v&&ee(this,ve,be).call(this,v)?v.__staleWhileFetching:v;b!==void 0&&(c.oldValue=b);}}else c&&(c.set="update");}if(s!==0&&!S(this,Tt)&&ee(this,bi,Sc).call(this),S(this,Tt)&&(p||S(this,Ei).call(this,g,s,i),c&&S(this,Xt).call(this,c,g)),!o&&S(this,it)&&S(this,Ue)){let v=S(this,Ue),b;for(;b=v?.shift();)(m=S(this,Rt))==null||m.call(this,...b);}return this}pop(){var e;try{for(;S(this,Te);){let r=S(this,oe)[S(this,ze)];if(ee(this,Cn,Ao).call(this,!0),ee(this,ve,be).call(this,r)){if(r.__staleWhileFetching)return r.__staleWhileFetching}else if(r!==void 0)return r}}finally{if(S(this,it)&&S(this,Ue)){let r=S(this,Ue),n;for(;n=r?.shift();)(e=S(this,Rt))==null||e.call(this,...n);}}}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:s}=r,i=S(this,$e).get(e);if(i!==void 0){let o=S(this,oe)[i];if(ee(this,ve,be).call(this,o)&&o.__staleWhileFetching===void 0)return !1;if(S(this,pt).call(this,i))s&&(s.has="stale",S(this,Xt).call(this,s,i));else return n&&S(this,jr).call(this,i),s&&(s.has="hit",S(this,Xt).call(this,s,i)),!0}else s&&(s.has="miss");return !1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,s=S(this,$e).get(e);if(s!==void 0&&(n||!S(this,pt).call(this,s))){let i=S(this,oe)[s];return ee(this,ve,be).call(this,i)?i.__staleWhileFetching:i}}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:l=this.noDisposeOnSet,size:c=0,sizeCalculation:p=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:g=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:y=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:v=this.allowStaleOnFetchAbort,context:b,forceRefresh:_=!1,status:x,signal:A}=r;if(!S(this,wr))return x&&(x.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:i,status:x});let O={allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:i,ttl:o,noDisposeOnSet:l,size:c,sizeCalculation:p,noUpdateTTL:u,noDeleteOnFetchRejection:g,allowStaleOnFetchRejection:y,allowStaleOnFetchAbort:v,ignoreFetchAbort:m,status:x,signal:A},I=S(this,$e).get(e);if(I===void 0){x&&(x.fetch="miss");let F=ee(this,Rn,_o).call(this,e,I,O,b);return F.__returned=F}else {let F=S(this,oe)[I];if(ee(this,ve,be).call(this,F)){let j=n&&F.__staleWhileFetching!==void 0;return x&&(x.fetch="inflight",j&&(x.returnedStale=!0)),j?F.__staleWhileFetching:F.__returned=F}let U=S(this,pt).call(this,I);if(!_&&!U)return x&&(x.fetch="hit"),ee(this,Hr,Si).call(this,I),s&&S(this,jr).call(this,I),x&&S(this,Xt).call(this,x,I),F;let H=ee(this,Rn,_o).call(this,e,I,O,b),k=H.__staleWhileFetching!==void 0&&n;return x&&(x.fetch=U?"stale":"refresh",k&&U&&(x.returnedStale=!0)),k?H.__staleWhileFetching:H.__returned=H}}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:o}=r,l=S(this,$e).get(e);if(l!==void 0){let c=S(this,oe)[l],p=ee(this,ve,be).call(this,c);return o&&S(this,Xt).call(this,o,l),S(this,pt).call(this,l)?(o&&(o.get="stale"),p?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(i||this.delete(e),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),p?c.__staleWhileFetching:(ee(this,Hr,Si).call(this,l),s&&S(this,jr).call(this,l),c))}else o&&(o.get="miss");}delete(e){var n,s;let r=!1;if(S(this,Te)!==0){let i=S(this,$e).get(e);if(i!==void 0)if(r=!0,S(this,Te)===1)this.clear();else {S(this,Br).call(this,i);let o=S(this,oe)[i];ee(this,ve,be).call(this,o)?o.__abortController.abort(new Error("deleted")):(S(this,Bt)||S(this,it))&&(S(this,Bt)&&((n=S(this,jt))==null||n.call(this,o,e,"delete")),S(this,it)&&S(this,Ue)?.push([o,e,"delete"])),S(this,$e).delete(e),S(this,Se)[i]=void 0,S(this,oe)[i]=void 0,i===S(this,qe)?re(this,qe,S(this,ht)[i]):i===S(this,ze)?re(this,ze,S(this,Je)[i]):(S(this,Je)[S(this,ht)[i]]=S(this,Je)[i],S(this,ht)[S(this,Je)[i]]=S(this,ht)[i]),Di(this,Te)._--,S(this,Pt).push(i);}}if(S(this,it)&&S(this,Ue)?.length){let i=S(this,Ue),o;for(;o=i?.shift();)(s=S(this,Rt))==null||s.call(this,...o);}return r}clear(){var e,r;for(let n of ee(this,Ut,vr).call(this,{allowStale:!0})){let s=S(this,oe)[n];if(ee(this,ve,be).call(this,s))s.__abortController.abort(new Error("deleted"));else {let i=S(this,Se)[n];S(this,Bt)&&((e=S(this,jt))==null||e.call(this,s,i,"delete")),S(this,it)&&S(this,Ue)?.push([s,i,"delete"]);}}if(S(this,$e).clear(),S(this,oe).fill(void 0),S(this,Se).fill(void 0),S(this,Tt)&&S(this,Jt)&&(S(this,Tt).fill(0),S(this,Jt).fill(0)),S(this,Yt)&&S(this,Yt).fill(0),re(this,ze,0),re(this,qe,0),S(this,Pt).length=0,re(this,Ot,0),re(this,Te,0),S(this,it)&&S(this,Ue)){let n=S(this,Ue),s;for(;s=n?.shift();)(r=S(this,Rt))==null||r.call(this,...s);}}};Ct=new WeakMap,ft=new WeakMap,jt=new WeakMap,Rt=new WeakMap,_n=new WeakMap,Te=new WeakMap,Ot=new WeakMap,$e=new WeakMap,Se=new WeakMap,oe=new WeakMap,Je=new WeakMap,ht=new WeakMap,ze=new WeakMap,qe=new WeakMap,Pt=new WeakMap,Ue=new WeakMap,Yt=new WeakMap,Jt=new WeakMap,Tt=new WeakMap,Bt=new WeakMap,wr=new WeakMap,it=new WeakMap,bi=new WeakSet,Sc=function(){let e=new En(S(this,Ct)),r=new En(S(this,Ct));re(this,Tt,e),re(this,Jt,r),re(this,Ei,(i,o,l=wi.now())=>{if(r[i]=o!==0?l:0,e[i]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{S(this,pt).call(this,i)&&this.delete(S(this,Se)[i]);},o+1);c.unref&&c.unref();}}),re(this,jr,i=>{r[i]=e[i]!==0?wi.now():0;}),re(this,Xt,(i,o)=>{if(e[o]){let l=e[o],c=r[o];i.ttl=l,i.start=c,i.now=n||s();let p=i.now-c;i.remainingTTL=l-p;}});let n=0,s=()=>{let i=wi.now();if(this.ttlResolution>0){n=i;let o=setTimeout(()=>n=0,this.ttlResolution);o.unref&&o.unref();}return i};this.getRemainingTTL=i=>{let o=S(this,$e).get(i);if(o===void 0)return 0;let l=e[o],c=r[o];if(l===0||c===0)return 1/0;let p=(n||s())-c;return l-p},re(this,pt,i=>e[i]!==0&&r[i]!==0&&(n||s())-r[i]>e[i]);},jr=new WeakMap,Xt=new WeakMap,Ei=new WeakMap,pt=new WeakMap,Ro=new WeakSet,l0=function(){let e=new En(S(this,Ct));re(this,Ot,0),re(this,Yt,e),re(this,Br,r=>{re(this,Ot,S(this,Ot)-e[r]),e[r]=0;}),re(this,Ai,(r,n,s,i)=>{if(ee(this,ve,be).call(this,n))return 0;if(!yr(s))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(s=i(n,r),!yr(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return s}),re(this,xn,(r,n,s)=>{if(e[r]=n,S(this,ft)){let i=S(this,ft)-e[r];for(;S(this,Ot)>i;)ee(this,Cn,Ao).call(this,!0);}re(this,Ot,S(this,Ot)+e[r]),s&&(s.entrySize=n,s.totalCalculatedSize=S(this,Ot));});},Br=new WeakMap,xn=new WeakMap,Ai=new WeakMap,Ht=new WeakSet,mr=function*({allowStale:e=this.allowStale}={}){if(S(this,Te))for(let r=S(this,qe);!(!ee(this,_i,bc).call(this,r)||((e||!S(this,pt).call(this,r))&&(yield r),r===S(this,ze)));)r=S(this,ht)[r];},Ut=new WeakSet,vr=function*({allowStale:e=this.allowStale}={}){if(S(this,Te))for(let r=S(this,ze);!(!ee(this,_i,bc).call(this,r)||((e||!S(this,pt).call(this,r))&&(yield r),r===S(this,qe)));)r=S(this,Je)[r];},_i=new WeakSet,bc=function(e){return e!==void 0&&S(this,$e).get(S(this,Se)[e])===e},Cn=new WeakSet,Ao=function(e){var i;let r=S(this,ze),n=S(this,Se)[r],s=S(this,oe)[r];return S(this,wr)&&ee(this,ve,be).call(this,s)?s.__abortController.abort(new Error("evicted")):(S(this,Bt)||S(this,it))&&(S(this,Bt)&&((i=S(this,jt))==null||i.call(this,s,n,"evict")),S(this,it)&&S(this,Ue)?.push([s,n,"evict"])),S(this,Br).call(this,r),e&&(S(this,Se)[r]=void 0,S(this,oe)[r]=void 0,S(this,Pt).push(r)),S(this,Te)===1?(re(this,ze,re(this,qe,0)),S(this,Pt).length=0):re(this,ze,S(this,Je)[r]),S(this,$e).delete(n),Di(this,Te)._--,r},Rn=new WeakSet,_o=function(e,r,n,s){let i=r===void 0?void 0:S(this,oe)[r];if(ee(this,ve,be).call(this,i))return i;let o=new xo,{signal:l}=n;l?.addEventListener("abort",()=>o.abort(l.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:s},p=(b,_=!1)=>{let{aborted:x}=o.signal,A=n.ignoreFetchAbort&&b!==void 0;if(n.status&&(x&&!_?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,A&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),x&&!A&&!_)return g(o.signal.reason);let O=m;return S(this,oe)[r]===m&&(b===void 0?O.__staleWhileFetching?S(this,oe)[r]=O.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,b,c.options))),b},u=b=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=b),g(b)),g=b=>{let{aborted:_}=o.signal,x=_&&n.allowStaleOnFetchAbort,A=x||n.allowStaleOnFetchRejection,O=A||n.noDeleteOnFetchRejection,I=m;if(S(this,oe)[r]===m&&(!O||I.__staleWhileFetching===void 0?this.delete(e):x||(S(this,oe)[r]=I.__staleWhileFetching)),A)return n.status&&I.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),I.__staleWhileFetching;if(I.__returned===I)throw b},y=(b,_)=>{var A;let x=(A=S(this,_n))==null?void 0:A.call(this,e,i,c);x&&x instanceof Promise&&x.then(O=>b(O),_),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(b(),n.allowStaleOnFetchAbort&&(b=O=>p(O,!0)));});};n.status&&(n.status.fetchDispatched=!0);let m=new Promise(y).then(p,u),v=Object.assign(m,{__abortController:o,__staleWhileFetching:i,__returned:void 0});return r===void 0?(this.set(e,v,{...c.options,status:void 0}),r=S(this,$e).get(e)):S(this,oe)[r]=v,v},ve=new WeakSet,be=function(e){if(!S(this,wr))return !1;let r=e;return !!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof xo},xi=new WeakSet,Ec=function(e,r){S(this,ht)[r]=e,S(this,Je)[e]=r;},Hr=new WeakSet,Si=function(e){e!==S(this,qe)&&(e===S(this,ze)?re(this,ze,S(this,Je)[e]):ee(this,xi,Ec).call(this,S(this,ht)[e],S(this,Je)[e]),ee(this,xi,Ec).call(this,S(this,qe),e),re(this,qe,e));};var Co=Ac;var g0=Nn(d0());function cq(t){return t.trimEnd().split("").every(e=>ws.includes(e))}var Sr=class{constructor(e){this.filepath=e.filepath,this.language=e.language,this.text=e.text,this.position=e.position,this.prefix=e.text.slice(0,e.position),this.suffix=e.text.slice(e.position),this.prefixLines=Pe(this.prefix),this.suffixLines=Pe(this.suffix);let r=cq(this.suffixLines[0]??"");this.mode=r?"default":"fill-in-line",this.hash=(0, g0.default)({filepath:e.filepath,language:e.language,text:e.text,position:e.position});}};var y0=["statusChanged","configUpdated","authRequired","issuesUpdated"];Nt();var Oo=class{constructor(){this.logger=Ce.child({component:"CompletionCache"});this.options={maxCount:1e4,prebuildCache:{enabled:!0,perCharacter:{lines:1,max:50},perLine:{max:10},autoClosingPairCheck:{max:3}}};this.cache=new Co({max:this.options.maxCount});}has(e){return this.cache.has(e.hash)}buildCache(e,r){this.logger.debug({key:e,value:r},"Starting to build cache");let n=this.createCacheEntries(e,r);n.forEach(s=>{this.cache.set(s.key.hash,{value:s.value,rebuildFlag:s.rebuildFlag});}),this.logger.debug({newEntries:n.length,cacheSize:this.cache.size},"Cache updated");}get(e){let r=this.cache.get(e.hash);return r?.rebuildFlag&&this.buildCache(e,r?.value),r?.value}createCacheEntries(e,r){let n=[{key:e,value:r,rebuildFlag:!1}];if(this.options.prebuildCache.enabled)for(let i of r.choices){let o=i.text.slice(e.position-i.replaceRange.start),l=this.getPerLinePositions(o);this.logger.trace({completionText:o,perLinePositions:l},"Calculate per-line cache positions");for(let p of l){let u=o.slice(0,p),g=this.generateAutoClosedPrefixes(u);for(let y of [u,...g]){let m={key:new Sr({...e,text:e.text.slice(0,e.position)+y+e.text.slice(e.position),position:e.position+p}),value:{...r,choices:[{index:i.index,text:o.slice(p),replaceRange:{start:e.position+p,end:e.position+p}}]},rebuildFlag:!0};this.logger.trace({prefix:y,entry:m},"Build per-line cache entry"),n.push(m);}}let c=this.getPerCharacterPositions(o);this.logger.trace({completionText:o,perCharacterPositions:c},"Calculate per-character cache positions");for(let p of c){let u=p;for(;u>0&&o[u-1]!==` -`;)u--;let g=o.slice(0,p),y=this.generateAutoClosedPrefixes(g);for(let m of [g,...y]){let v={key:new Sr({...e,text:e.text.slice(0,e.position)+m+e.text.slice(e.position),position:e.position+p}),value:{...r,choices:[{index:i.index,text:o.slice(u),replaceRange:{start:e.position+u,end:e.position+p}}]},rebuildFlag:!1};this.logger.trace({prefix:m,entry:v},"Build per-character cache entry"),n.push(v);}}}return n.reduce((i,o)=>{let l=i.find(c=>c.key.hash===o.key.hash);return l?(l.value.choices.push(...o.value.choices),l.rebuildFlag=l.rebuildFlag||o.rebuildFlag):i.push(o),i},[])}getPerLinePositions(e){let r=[],n=this.options.prebuildCache,s=Pe(e),i=0,o=0;for(;is;s++){let o=Fg.indexOf(n[n.length-1-s]);if(o<0)break;i=i+ws[o],r.push(e+i);}return r}};Nt();function Cc(t,e,r){return Math.max(t,Math.min(e,r))}var Po=class{constructor(){this.logger=Ce.child({component:"CompletionDebounce"});this.lastCalledTimeStamp=0;this.baseInterval=200;this.calledIntervalHistory=[];this.options={baseIntervalSlideWindowAvg:{minSize:20,maxSize:100,min:100,max:400},adaptiveRate:{min:1.5,max:3},contextScoreWeights:{triggerCharacter:.5,noSuffixInCurrentLine:.4,noSuffix:.1},requestDelay:{min:100,max:1e3}};}async debounce(e,r){let{request:n,config:s,responseTime:i}=e;if(n.manually)return this.sleep(0,r);if(s.mode==="fixed")return this.sleep(s.interval,r);let o=Date.now();this.updateBaseInterval(o-this.lastCalledTimeStamp),this.lastCalledTimeStamp=o;let l=this.calcContextScore(n),p=(this.options.adaptiveRate.max-(this.options.adaptiveRate.max-this.options.adaptiveRate.min)*l)*this.baseInterval,u=Cc(this.options.requestDelay.min,this.options.requestDelay.max,p-i);return this.sleep(u,r)}async sleep(e,r){return new Promise((n,s)=>{let i=setTimeout(n,Math.min(e,2147483647));r?.signal&&(r.signal.aborted?(clearTimeout(i),s(r.signal.reason)):r.signal.addEventListener("abort",()=>{clearTimeout(i),s(r.signal.reason);}));})}updateBaseInterval(e){if(!(e>this.options.baseIntervalSlideWindowAvg.max)&&(this.calledIntervalHistory.push(e),this.calledIntervalHistory.length>this.options.baseIntervalSlideWindowAvg.maxSize&&this.calledIntervalHistory.shift(),this.calledIntervalHistory.length>this.options.baseIntervalSlideWindowAvg.minSize)){let r=this.calledIntervalHistory.reduce((n,s)=>n+s,0)/this.calledIntervalHistory.length;this.baseInterval=Cc(this.options.baseIntervalSlideWindowAvg.min,this.options.baseIntervalSlideWindowAvg.max,r);}}calcContextScore(e){let r=0,n=this.options.contextScoreWeights,s=e.text[e.position-1]??"";r+=s.match(/^\W*$/)?n.triggerCharacter:0;let i=e.text.slice(e.position)??"",o=Pe(i)[0]??"";return r+=o.match(/^\W*$/)?n.noSuffixInCurrentLine:0,r+=i.match(/^\W*$/)?n.noSuffix:0,r=Cc(0,1,r),r}};Nt();var $t=Ce.child({component:"Postprocess"});Array.prototype.distinct||(Array.prototype.distinct=function(t){return [...new Map(this.map(e=>[t?.(e)??e,e])).values()]});function It(t,e){return async r=>(r.choices=(await Promise.all(r.choices.map(async n=>{let s=e.position-n.replaceRange.start,i=await t(n.text.slice(s));return n.text=n.text.slice(0,s)+(i??""),n}))).filter(n=>!!n.text).distinct(n=>n.text),r)}function fq(t){return /\n(\s*)\n/g}var m0=t=>e=>{let r=e.split(fq()),n=0,s=2,i=r.length-2;for(;i>=1;){if(ge(r[i])){i--;continue}let o=i-1;for(;o>=0&&ge(r[o]);)o--;if(o<0)break;let l=r[i].trim(),c=r[o].trim(),p=Math.max(.1*l.length,.1*c.length);if(on(l,c)<=p)n++,i--;else break}return n>=s?($t.debug({inputBlocks:r,repetitionCount:n},"Remove repetitive blocks."),r.slice(0,i+1).join("").trimEnd()):e};var v0=()=>t=>{let e=Pe(t),r=0,n=5,s=e.length-2;for(;s>=1;){if(ge(e[s])){s--;continue}let i=s-1;for(;i>=0&&ge(e[i]);)i--;if(i<0)break;let o=e[s].trim(),l=e[i].trim(),c=Math.max(.1*o.length,.1*l.length);if(on(o,l)<=c)r++,s=i;else break}return r>=n?($t.debug({inputLines:e,repetitionCount:r},"Remove repetitive lines."),e.slice(0,s+1).join("").trimEnd()):t};var hq=[/(.{3,}?)\1{5,}$/g,/(.{10,}?)\1{3,}$/g],w0=()=>t=>{let e=Pe(t),r=e.length-1;for(;r>=0&&ge(e[r]);)r--;if(r<0)return t;for(let n of hq){let s=e[r].match(n);if(s)return $t.debug({inputLines:e,lineNumber:r,match:s},"Remove line ends with repetition."),r<1?null:e.slice(0,r).join("").trimEnd()}return t};function br(t){return t.match(/^[ \t]*/)?.[0]?.length??0}function pq(t,e){return e>=t.length-1?!1:br(t[e])n};if(t.length==0||e.length==0)return s;let i=e[e.length-1],o=ge(i),l=e.length-1;for(;l>=0&&ge(e[l]);)l--;if(l<0)return s;let c=e[l],p=br(c),u=t[0],g=ge(u),y=0;for(;y=t.length)return s;let m=t[y],v;g?v=br(m):v=br(i+m),!g&&!o?(s.indentLevelLimit=p+1,n=!!t[1]&&br(t[1])>p):v>p?(s.indentLevelLimit=p+1,n=!0):(s.indentLevelLimit=p,n=!0);let b=1;for(;b{let x=_.startsWith(r[b])||r[b].startsWith(_);return n&&!x}),s}var S0=t=>e=>{let{prefix:r,suffix:n,prefixLines:s,suffixLines:i}=t,o=Pe(e);if(t.mode==="fill-in-line"&&o.length>1)return $t.debug({input:e,prefix:r,suffix:n},"Drop content with multiple lines"),null;let l=dq(o,s,i),c;for(c=1;ce=>{let {prefixLines:r,suffixLines:n}=t;Pe(e);let i=e,o=r[r.length-1]??"",l=n[0]??"";return !ge(o)&&o.match(/\s$/)&&(i=i.trimStart()),(ge(l)||!ge(l)&&l.match(/^\s/))&&(i=i.trimEnd()),i};var Oc=t=>e=>{let{suffixLines:r}=t,n=Pe(e),s=0;for(;st=>ge(t)?null:t;async function b0(t,e){return Promise.resolve(e).then(It(w0(),t)).then(It(Oc(t),t)).then(It(Rc(t),t)).then(It(Pc(),t))}async function E0(t,e){return Promise.resolve(e).then(It(m0(),t)).then(It(v0(),t)).then(It(S0(t),t)).then(It(Oc(t),t)).then(It(Rc(t),t)).then(It(Pc(),t))}Nt();var _0="tabby-agent",x0="0.4.0-dev";Jn();Nt();var To=class t{constructor(){this.anonymousUsageTrackingApi=Or({baseUrl:"https://app.tabbyml.com/api"});this.logger=Ce.child({component:"AnonymousUsage"});this.systemData={agent:`${_0}, ${x0}`,browser:void 0,node:`${process.version} ${process.platform} ${z("os").arch()} ${z("os").release()}`};this.sessionProperties={};this.userProperties={};this.userPropertiesUpdated=!1;this.emittedUniqueEvent=[];this.dataStore=null;}static async create(e){let r=new t;return r.dataStore=e.dataStore||Fs,await r.checkAnonymousId(),r}async checkAnonymousId(){if(this.dataStore){try{await this.dataStore.load();}catch(e){this.logger.debug({error:e},"Error when loading anonymousId");}if(typeof this.dataStore.data.anonymousId=="string")this.anonymousId=this.dataStore.data.anonymousId;else {this.anonymousId=Ar(),this.dataStore.data.anonymousId=this.anonymousId;try{await this.dataStore.save();}catch(e){this.logger.debug({error:e},"Error when saving anonymousId");}}}else this.anonymousId=Ar();}setSessionProperties(e,r){sn(this.sessionProperties,e,r);}setUserProperties(e,r){sn(this.userProperties,e,r),this.userPropertiesUpdated=!0;}async uniqueEvent(e,r={}){await this.event(e,r,!0);}async event(e,r={},n=!1){if(this.disabled||n&&this.emittedUniqueEvent.indexOf(e)>=0)return;n&&this.emittedUniqueEvent.push(e);let s={...this.systemData,...this.sessionProperties,...r};this.userPropertiesUpdated&&(s.$set=this.userProperties,this.userPropertiesUpdated=!1);try{await this.anonymousUsageTrackingApi.POST("/usage",{body:{distinctId:this.anonymousId,event:e,properties:s}});}catch(i){this.logger.error({error:i},"Error when sending anonymous usage data");}}};var kc=Nn(P0());Nt();var $o=class{constructor(){this.sum=0;this.quantity=0;}add(e){this.sum+=e,this.quantity+=1;}mean(){if(this.quantity!==0)return this.sum/this.quantity}count(){return this.quantity}},Io=class{constructor(e){this.values=[];this.maxSize=e;}add(e){this.values.push(e),this.values.length>this.maxSize&&this.values.shift();}getValues(){return this.values}},Ti=class{constructor(){this.logger=Ce.child({component:"CompletionProviderStats"});this.autoCompletionCount=0;this.manualCompletionCount=0;this.cacheHitCount=0;this.cacheMissCount=0;this.eventMap=new Map;this.completionRequestLatencyStats=new kc.Univariate;this.completionRequestCanceledStats=new $o;this.completionRequestTimeoutCount=0;this.recentCompletionRequestLatencies=new Io(10);}add(e){let{triggerMode:r,cacheHit:n,aborted:s,requestSent:i,requestLatency:o,requestCanceled:l,requestTimeout:c}=e;s||(r==="auto"?this.autoCompletionCount+=1:this.manualCompletionCount+=1,n?this.cacheHitCount+=1:this.cacheMissCount+=1),i&&(l?this.completionRequestCanceledStats.add(o):c?this.completionRequestTimeoutCount+=1:this.completionRequestLatencyStats.add(o),l||this.recentCompletionRequestLatencies.add(o));}addEvent(e){let r=this.eventMap.get(e)||0;this.eventMap.set(e,r+1);}reset(){this.autoCompletionCount=0,this.manualCompletionCount=0,this.cacheHitCount=0,this.cacheMissCount=0,this.eventMap=new Map,this.completionRequestLatencyStats=new kc.Univariate,this.completionRequestCanceledStats=new $o,this.completionRequestTimeoutCount=0;}resetWindowed(){this.recentCompletionRequestLatencies=new Io(10);}stats(){let e=Object.fromEntries(Array.from(this.eventMap.entries()).map(([r,n])=>["count_"+r,n]));return {completion:{count_auto:this.autoCompletionCount,count_manual:this.manualCompletionCount,cache_hit:this.cacheHitCount,cache_miss:this.cacheMissCount,...e},completion_request:{count:this.completionRequestLatencyStats.count(),latency_avg:this.completionRequestLatencyStats.mean(),latency_p50:this.completionRequestLatencyStats.percentile(50),latency_p95:this.completionRequestLatencyStats.percentile(95),latency_p99:this.completionRequestLatencyStats.percentile(99)},completion_request_canceled:{count:this.completionRequestCanceledStats.count(),latency_avg:this.completionRequestCanceledStats.mean()},completion_request_timeout:{count:this.completionRequestTimeoutCount}}}windowed(){let e=this.recentCompletionRequestLatencies.getValues(),r=e.filter(i=>Number.isNaN(i)),n=e.filter(i=>!Number.isNaN(i)),s=n.reduce((i,o)=>i+o,0)/n.length;return {values:e,stats:{total:e.length,timeouts:r.length,responses:n.length,averageResponseTime:s}}}static check(e){let{values:r,stats:{total:n,timeouts:s,responses:i,averageResponseTime:o}}=e;return r.slice(-3).every(l=>l<3e3)?"healthy":s/n>.5&&s>=3?"highTimeoutRate":i>=3&&o>4e3?"slowResponseTime":null}};var Wr=class Wr extends events.EventEmitter{constructor(){super();this.logger=Ce.child({component:"TabbyAgent"});this.config=mc;this.userConfig={};this.clientConfig={};this.status="notInitialized";this.issues=[];this.serverHealthState=null;this.dataStore=null;this.completionCache=new Oo;this.completionDebounce=new Po;this.nonParallelProvideCompletionAbortController=null;this.completionProviderStats=new Ti;this.tryingConnectTimer=null;this.submitStatsTimer=null;this.tryingConnectTimer=setInterval(async()=>{this.status==="disconnected"&&(this.logger.debug("Trying to connect..."),await this.healthCheck());},Wr.tryConnectInterval),this.submitStatsTimer=setInterval(async()=>{await this.submitStats();},Wr.submitStatsInterval);}static async create(r){let n=new Wr;return n.dataStore=r?.dataStore,n.anonymousUsageLogger=await To.create({dataStore:r?.dataStore}),n}async applyConfig(){let r=this.config,n=this.status;this.config=_g(mc,this.userConfig,this.clientConfig),gn.forEach(i=>i.level=this.config.logs.level),this.anonymousUsageLogger.disabled=this.config.anonymousUsageTracking.disable,this.config.server.requestHeaders.Authorization===void 0?this.config.server.endpoint!==this.auth?.endpoint&&(this.auth=await ro.create({endpoint:this.config.server.endpoint,dataStore:this.dataStore}),this.auth.on("updated",this.setupApi.bind(this))):this.auth=null,await this.setupApi(),(0, Lc.default)(r.server,this.config.server)||(this.serverHealthState=null,this.completionProviderStats.resetWindowed(),this.popIssue("slowCompletionResponseTime"),this.popIssue("highCompletionTimeoutRate"),n==="unauthorized"&&this.status==="unauthorized"&&this.emitAuthRequired());let s={event:"configUpdated",config:this.config};this.logger.debug({event:s},"Config updated"),super.emit("configUpdated",s);}async setupApi(){this.api=Or({baseUrl:this.config.server.endpoint.replace(/\/+$/,""),headers:{Authorization:this.auth?.token?`Bearer ${this.auth.token}`:void 0,...this.config.server.requestHeaders}}),await this.healthCheck();}changeStatus(r){if(this.status!=r){this.status=r;let n={event:"statusChanged",status:r};this.logger.debug({event:n},"Status changed"),super.emit("statusChanged",n),this.status==="unauthorized"&&this.emitAuthRequired();}}issueFromName(r){switch(r){case"highCompletionTimeoutRate":return {name:"highCompletionTimeoutRate",completionResponseStats:this.completionProviderStats.windowed().stats};case"slowCompletionResponseTime":return {name:"slowCompletionResponseTime",completionResponseStats:this.completionProviderStats.windowed().stats}}}pushIssue(r){this.issues.indexOf(r)===-1&&(this.issues.push(r),this.logger.debug({issue:r},"Issues Pushed"),this.emitIssueUpdated());}popIssue(r){let n=this.issues.indexOf(r);n>=0&&(this.issues.splice(n,1),this.logger.debug({issue:r},"Issues Popped"),this.emitIssueUpdated());}emitAuthRequired(){let r={event:"authRequired",server:this.config.server};super.emit("authRequired",r);}emitIssueUpdated(){let r={event:"issuesUpdated",issues:this.issues};super.emit("issuesUpdated",r);}async submitStats(){let r=this.completionProviderStats.stats();r.completion_request.count>0&&(await this.anonymousUsageLogger.event("AgentStats",{stats:r}),this.completionProviderStats.reset(),this.logger.debug({stats:r},"Stats submitted"));}async post(r,n,s){let i=Ar();this.logger.debug({requestId:i,path:r,requestOptions:n,abortOptions:s},"API request");try{let o=Math.min(2147483647,s?.timeout||this.config.server.requestTimeout),l=Yn([AbortSignal.timeout(o),s?.signal]),c=await this.api.POST(r,{...n,signal:l});if(c.error)throw new at(c.response);return this.logger.debug({requestId:i,path:r,response:c.data},"API response"),this.changeStatus("ready"),c.data}catch(o){throw bs(o)?this.logger.debug({requestId:i,path:r,error:o},"API request timeout"):an(o)?this.logger.debug({requestId:i,path:r,error:o},"API request canceled"):o instanceof at&&[401,403,405].indexOf(o.status)!==-1&&new URL(this.config.server.endpoint).hostname.endsWith("app.tabbyml.com")&&this.config.server.requestHeaders.Authorization===void 0?(this.logger.debug({requestId:i,path:r,error:o},"API unauthorized"),this.changeStatus("unauthorized")):o instanceof at?(this.logger.error({requestId:i,path:r,error:o},"API error"),this.changeStatus("disconnected")):(this.logger.error({requestId:i,path:r,error:o},"API request failed with unknown error"),this.changeStatus("disconnected")),o}}async healthCheck(r){try{let n=await this.post("/v1/health",{},r);typeof n=="object"&&n.model!==void 0&&n.device!==void 0&&(this.serverHealthState=n,this.status==="ready"&&this.anonymousUsageLogger.uniqueEvent("AgentConnected",n));}catch{this.changeStatus("disconnected"),this.serverHealthState=null;}}createSegments(r){let n=this.config.completion.prompt.maxPrefixLines,s=this.config.completion.prompt.maxSuffixLines,{prefixLines:i,suffixLines:o}=r;return {prefix:i.slice(Math.max(i.length-n,0)).join(""),suffix:o.slice(0,s).join("")}}calculateReplaceRange(r,n){let{suffixLines:s}=n,i=s[0]?.trimEnd()||"";if(ge(i))return r;for(let o of r.choices){let l=o.text.slice(n.position-o.replaceRange.start),c=Ss(l);ge(c)||(i.startsWith(c)?(o.replaceRange.end=n.position+c.length,this.logger.trace({context:n,completion:o.text,range:o.replaceRange,unpaired:c},"Adjust replace range")):c.startsWith(i)&&(o.replaceRange.end=n.position+i.length,this.logger.trace({context:n,completion:o.text,range:o.replaceRange,unpaired:c},"Adjust replace range")));}return r}async initialize(r){if(r.clientProperties){let{user:n,session:s}=r.clientProperties;gn.forEach(i=>i.setBindings?.({...s})),s&&Object.entries(s).forEach(([i,o])=>{this.anonymousUsageLogger.setSessionProperties(i,o);}),n&&Object.entries(n).forEach(([i,o])=>{this.anonymousUsageLogger.setUserProperties(i,o);});}return bn&&(await bn.load(),this.userConfig=bn.config,bn.on("updated",async n=>{this.userConfig=n,await this.applyConfig();}),bn.watch()),r.config&&(this.clientConfig=r.config),await this.applyConfig(),await this.anonymousUsageLogger.uniqueEvent("AgentInitialized"),this.logger.debug({options:r},"Initialized"),this.status!=="notInitialized"}async finalize(){return this.status==="finalized"?!1:(await this.submitStats(),this.tryingConnectTimer&&(clearInterval(this.tryingConnectTimer),this.tryingConnectTimer=null),this.submitStatsTimer&&(clearInterval(this.submitStatsTimer),this.submitStatsTimer=null),this.changeStatus("finalized"),!0)}async updateClientProperties(r,n,s){switch(r){case"session":let i={};sn(i,n,s),gn.forEach(o=>o.setBindings?.(i)),this.anonymousUsageLogger.setSessionProperties(n,s);break;case"user":this.anonymousUsageLogger.setUserProperties(n,s);break}return !0}async updateConfig(r,n){let s=Og(this.clientConfig,r);return (0, Lc.default)(s,n)||(n===void 0?Pg(this.clientConfig,r):sn(this.clientConfig,r,n),await this.applyConfig()),!0}async clearConfig(r){return await this.updateConfig(r,void 0)}getConfig(){return this.config}getStatus(){return this.status}getIssues(){return this.issues}getIssueDetail(r){return r.index!==void 0?this.issueFromName(this.issues[r.index]):r.name!==void 0&&this.issues.indexOf(r.name)!==-1?this.issueFromName(r.name):null}getServerHealthState(){return this.serverHealthState}async requestAuthUrl(r){if(this.status==="notInitialized")throw new Error("Agent is not initialized");return await this.healthCheck(r),this.status!=="unauthorized"?null:await this.auth.requestAuthUrl(r)}async waitForAuthToken(r,n){if(this.status==="notInitialized")throw new Error("Agent is not initialized");await this.auth.pollingToken(r,n),await this.setupApi();}async provideCompletions(r,n){if(this.status==="notInitialized")throw new Error("Agent is not initialized");this.logger.trace({request:r},"Call provideCompletions"),this.nonParallelProvideCompletionAbortController&&this.nonParallelProvideCompletionAbortController.abort(),this.nonParallelProvideCompletionAbortController=new AbortController;let s=Yn([this.nonParallelProvideCompletionAbortController.signal,n?.signal]),i=null,o={triggerMode:r.manually?"manual":"auto",cacheHit:!1,aborted:!1,requestSent:!1,requestLatency:0,requestCanceled:!1,requestTimeout:!1},l=null,c=new Sr(r);try{if(this.completionCache.has(c))o.cacheHit=!0,this.logger.debug({context:c},"Completion cache hit"),await this.completionDebounce.debounce({request:r,config:this.config.completion.debounce,responseTime:0},{signal:s}),i=this.completionCache.get(c);else {o.cacheHit=!1;let p=this.createSegments(c);if(ge(p.prefix))o=null,this.logger.debug("Segment prefix is blank, returning empty completion response"),i={id:"agent-"+Ar(),choices:[]};else {await this.completionDebounce.debounce({request:r,config:this.config.completion.debounce,responseTime:this.completionProviderStats.stats().averageResponseTime},n),o.requestSent=!0,l=performance.now();try{let u=await this.post("/v1/completions",{body:{language:r.language,segments:p,user:this.auth?.user}},{signal:s,timeout:r.manually?this.config.completion.timeout.manually:this.config.completion.timeout.auto});o.requestLatency=performance.now()-l,i={id:u.id,choices:u.choices.map(g=>({index:g.index,text:g.text,replaceRange:{start:r.position,end:r.position}}))};}catch(u){throw an(u)&&(o.requestCanceled=!0,o.requestLatency=performance.now()-l),bs(u)&&(o.requestTimeout=!0,o.requestLatency=NaN),u}if(i=await b0(c,i),n?.signal?.aborted)throw n.signal.reason;this.completionCache.buildCache(c,i);}}if(i=await E0(c,i),n?.signal?.aborted)throw n.signal.reason;i=this.calculateReplaceRange(i,c);}catch(p){throw an(p)||bs(p)?o&&(o.aborted=!0):o=null,p}finally{if(o&&(this.completionProviderStats.add(o),o.requestSent&&!o.requestCanceled)){let p=this.completionProviderStats.windowed();switch(Ti.check(p)){case"healthy":this.popIssue("slowCompletionResponseTime"),this.popIssue("highCompletionTimeoutRate");break;case"highTimeoutRate":this.popIssue("slowCompletionResponseTime"),this.pushIssue("highCompletionTimeoutRate");break;case"slowResponseTime":this.popIssue("highCompletionTimeoutRate"),this.pushIssue("slowCompletionResponseTime");break}}}return this.logger.trace({context:c,completionResponse:i},"Return from provideCompletions"),i}async postEvent(r,n){if(this.status==="notInitialized")throw new Error("Agent is not initialized");return this.completionProviderStats.addEvent(r.type),await this.post("/v1/events",{body:r,params:{query:{select_kind:r.select_kind}},parseAs:"text"},n),!0}};Wr.tryConnectInterval=1e3*30,Wr.submitStatsInterval=1e3*60*60*24;var ko=Wr;Nt();var Lo=class{constructor(){this.process=process;this.inStream=process.stdin;this.outStream=process.stdout;this.logger=Ce.child({component:"StdIO"});this.buffer="";this.abortControllers={};this.agent=null;}async handleInput(e){let r=e.toString();this.buffer+=r;let n=Pe(this.buffer);if(!(n.length<1)){n[n.length-1].endsWith(` +`;)u--;let g=o.slice(0,p),y=this.generateAutoClosedPrefixes(g);for(let m of [g,...y]){let v={key:new Sr({...e,text:e.text.slice(0,e.position)+m+e.text.slice(e.position),position:e.position+p}),value:{...r,choices:[{index:i.index,text:o.slice(u),replaceRange:{start:e.position+u,end:e.position+p}}]},rebuildFlag:!1};this.logger.trace({prefix:m,entry:v},"Build per-character cache entry"),n.push(v);}}}return n.reduce((i,o)=>{let l=i.find(c=>c.key.hash===o.key.hash);return l?(l.value.choices.push(...o.value.choices),l.rebuildFlag=l.rebuildFlag||o.rebuildFlag):i.push(o),i},[])}getPerLinePositions(e){let r=[],n=this.options.prebuildCache,s=Pe(e),i=0,o=0;for(;is;s++){let o=Fg.indexOf(n[n.length-1-s]);if(o<0)break;i=i+ws[o],r.push(e+i);}return r}};Nt();function Cc(t,e,r){return Math.max(t,Math.min(e,r))}var Po=class{constructor(){this.logger=Ce.child({component:"CompletionDebounce"});this.lastCalledTimeStamp=0;this.baseInterval=200;this.calledIntervalHistory=[];this.options={baseIntervalSlideWindowAvg:{minSize:20,maxSize:100,min:100,max:400},adaptiveRate:{min:1.5,max:3},contextScoreWeights:{triggerCharacter:.5,noSuffixInCurrentLine:.4,noSuffix:.1},requestDelay:{min:100,max:1e3}};}async debounce(e,r){let{request:n,config:s,responseTime:i}=e;if(n.manually)return this.sleep(0,r);if(s.mode==="fixed")return this.sleep(s.interval,r);let o=Date.now();this.updateBaseInterval(o-this.lastCalledTimeStamp),this.lastCalledTimeStamp=o;let l=this.calcContextScore(n),p=(this.options.adaptiveRate.max-(this.options.adaptiveRate.max-this.options.adaptiveRate.min)*l)*this.baseInterval,u=Cc(this.options.requestDelay.min,this.options.requestDelay.max,p-i);return this.sleep(u,r)}async sleep(e,r){return new Promise((n,s)=>{let i=setTimeout(n,Math.min(e,2147483647));r?.signal&&(r.signal.aborted?(clearTimeout(i),s(r.signal.reason)):r.signal.addEventListener("abort",()=>{clearTimeout(i),s(r.signal.reason);}));})}updateBaseInterval(e){if(!(e>this.options.baseIntervalSlideWindowAvg.max)&&(this.calledIntervalHistory.push(e),this.calledIntervalHistory.length>this.options.baseIntervalSlideWindowAvg.maxSize&&this.calledIntervalHistory.shift(),this.calledIntervalHistory.length>this.options.baseIntervalSlideWindowAvg.minSize)){let r=this.calledIntervalHistory.reduce((n,s)=>n+s,0)/this.calledIntervalHistory.length;this.baseInterval=Cc(this.options.baseIntervalSlideWindowAvg.min,this.options.baseIntervalSlideWindowAvg.max,r);}}calcContextScore(e){let r=0,n=this.options.contextScoreWeights,s=e.text[e.position-1]??"";r+=s.match(/^\W*$/)?n.triggerCharacter:0;let i=e.text.slice(e.position)??"",o=Pe(i)[0]??"";return r+=o.match(/^\W*$/)?n.noSuffixInCurrentLine:0,r+=i.match(/^\W*$/)?n.noSuffix:0,r=Cc(0,1,r),r}};Nt();var $t=Ce.child({component:"Postprocess"});Array.prototype.distinct||(Array.prototype.distinct=function(t){return [...new Map(this.map(e=>[t?.(e)??e,e])).values()]});function It(t,e){return async r=>(r.choices=(await Promise.all(r.choices.map(async n=>{let s=e.position-n.replaceRange.start,i=await t(n.text.slice(s));return n.text=n.text.slice(0,s)+(i??""),n}))).filter(n=>!!n.text).distinct(n=>n.text),r)}function fq(t){return /\n(\s*)\n/g}var m0=t=>e=>{let r=e.split(fq()),n=0,s=2,i=r.length-2;for(;i>=1;){if(ge(r[i])){i--;continue}let o=i-1;for(;o>=0&&ge(r[o]);)o--;if(o<0)break;let l=r[i].trim(),c=r[o].trim(),p=Math.max(.1*l.length,.1*c.length);if(on(l,c)<=p)n++,i--;else break}return n>=s?($t.debug({inputBlocks:r,repetitionCount:n},"Remove repetitive blocks."),r.slice(0,i+1).join("").trimEnd()):e};var v0=()=>t=>{let e=Pe(t),r=0,n=5,s=e.length-2;for(;s>=1;){if(ge(e[s])){s--;continue}let i=s-1;for(;i>=0&&ge(e[i]);)i--;if(i<0)break;let o=e[s].trim(),l=e[i].trim(),c=Math.max(.1*o.length,.1*l.length);if(on(o,l)<=c)r++,s=i;else break}return r>=n?($t.debug({inputLines:e,repetitionCount:r},"Remove repetitive lines."),e.slice(0,s+1).join("").trimEnd()):t};var hq=[/(.{3,}?)\1{5,}$/g,/(.{10,}?)\1{3,}$/g],w0=()=>t=>{let e=Pe(t),r=e.length-1;for(;r>=0&&ge(e[r]);)r--;if(r<0)return t;for(let n of hq){let s=e[r].match(n);if(s)return $t.debug({inputLines:e,lineNumber:r,match:s},"Remove line ends with repetition."),r<1?null:e.slice(0,r).join("").trimEnd()}return t};function br(t){return t.match(/^[ \t]*/)?.[0]?.length??0}function pq(t,e){return e>=t.length-1?!1:br(t[e])n};if(t.length==0||e.length==0)return s;let i=e[e.length-1],o=ge(i),l=e.length-1;for(;l>=0&&ge(e[l]);)l--;if(l<0)return s;let c=e[l],p=br(c),u=t[0],g=ge(u),y=0;for(;y=t.length)return s;let m=t[y],v;g?v=br(m):v=br(i+m),!g&&!o?(s.indentLevelLimit=p+1,n=!!t[1]&&br(t[1])>p):v>p?(s.indentLevelLimit=p+1,n=!0):(s.indentLevelLimit=p,n=!0);let b=1;for(;b{let x=_.startsWith(r[b])||r[b].startsWith(_);return n&&!x}),s}var S0=t=>e=>{let{prefix:r,suffix:n,prefixLines:s,suffixLines:i}=t,o=Pe(e);if(t.mode==="fill-in-line"&&o.length>1)return $t.debug({input:e,prefix:r,suffix:n},"Drop content with multiple lines"),null;let l=dq(o,s,i),c;for(c=1;ce=>{let {prefixLines:r,suffixLines:n}=t;Pe(e);let i=e,o=r[r.length-1]??"",l=n[0]??"";return !ge(o)&&o.match(/\s$/)&&(i=i.trimStart()),(ge(l)||!ge(l)&&l.match(/^\s/))&&(i=i.trimEnd()),i};var Oc=t=>e=>{let{suffixLines:r}=t,n=Pe(e),s=0;for(;st=>ge(t)?null:t;async function b0(t,e){return Promise.resolve(e).then(It(w0(),t)).then(It(Oc(t),t)).then(It(Rc(t),t)).then(It(Pc(),t))}async function E0(t,e){return Promise.resolve(e).then(It(m0(),t)).then(It(v0(),t)).then(It(S0(t),t)).then(It(Oc(t),t)).then(It(Rc(t),t)).then(It(Pc(),t))}Nt();var _0="tabby-agent",x0="1.0.0";Jn();Nt();var To=class t{constructor(){this.anonymousUsageTrackingApi=Or({baseUrl:"https://app.tabbyml.com/api"});this.logger=Ce.child({component:"AnonymousUsage"});this.systemData={agent:`${_0}, ${x0}`,browser:void 0,node:`${process.version} ${process.platform} ${z("os").arch()} ${z("os").release()}`};this.sessionProperties={};this.userProperties={};this.userPropertiesUpdated=!1;this.emittedUniqueEvent=[];this.dataStore=null;}static async create(e){let r=new t;return r.dataStore=e.dataStore||Fs,await r.checkAnonymousId(),r}async checkAnonymousId(){if(this.dataStore){try{await this.dataStore.load();}catch(e){this.logger.debug({error:e},"Error when loading anonymousId");}if(typeof this.dataStore.data.anonymousId=="string")this.anonymousId=this.dataStore.data.anonymousId;else {this.anonymousId=Ar(),this.dataStore.data.anonymousId=this.anonymousId;try{await this.dataStore.save();}catch(e){this.logger.debug({error:e},"Error when saving anonymousId");}}}else this.anonymousId=Ar();}setSessionProperties(e,r){sn(this.sessionProperties,e,r);}setUserProperties(e,r){sn(this.userProperties,e,r),this.userPropertiesUpdated=!0;}async uniqueEvent(e,r={}){await this.event(e,r,!0);}async event(e,r={},n=!1){if(this.disabled||n&&this.emittedUniqueEvent.indexOf(e)>=0)return;n&&this.emittedUniqueEvent.push(e);let s={...this.systemData,...this.sessionProperties,...r};this.userPropertiesUpdated&&(s.$set=this.userProperties,this.userPropertiesUpdated=!1);try{await this.anonymousUsageTrackingApi.POST("/usage",{body:{distinctId:this.anonymousId,event:e,properties:s}});}catch(i){this.logger.error({error:i},"Error when sending anonymous usage data");}}};var kc=Nn(P0());Nt();var $o=class{constructor(){this.sum=0;this.quantity=0;}add(e){this.sum+=e,this.quantity+=1;}mean(){if(this.quantity!==0)return this.sum/this.quantity}count(){return this.quantity}},Io=class{constructor(e){this.values=[];this.maxSize=e;}add(e){this.values.push(e),this.values.length>this.maxSize&&this.values.shift();}getValues(){return this.values}},Ti=class{constructor(){this.logger=Ce.child({component:"CompletionProviderStats"});this.autoCompletionCount=0;this.manualCompletionCount=0;this.cacheHitCount=0;this.cacheMissCount=0;this.eventMap=new Map;this.completionRequestLatencyStats=new kc.Univariate;this.completionRequestCanceledStats=new $o;this.completionRequestTimeoutCount=0;this.recentCompletionRequestLatencies=new Io(10);}add(e){let{triggerMode:r,cacheHit:n,aborted:s,requestSent:i,requestLatency:o,requestCanceled:l,requestTimeout:c}=e;s||(r==="auto"?this.autoCompletionCount+=1:this.manualCompletionCount+=1,n?this.cacheHitCount+=1:this.cacheMissCount+=1),i&&(l?this.completionRequestCanceledStats.add(o):c?this.completionRequestTimeoutCount+=1:this.completionRequestLatencyStats.add(o),l||this.recentCompletionRequestLatencies.add(o));}addEvent(e){let r=this.eventMap.get(e)||0;this.eventMap.set(e,r+1);}reset(){this.autoCompletionCount=0,this.manualCompletionCount=0,this.cacheHitCount=0,this.cacheMissCount=0,this.eventMap=new Map,this.completionRequestLatencyStats=new kc.Univariate,this.completionRequestCanceledStats=new $o,this.completionRequestTimeoutCount=0;}resetWindowed(){this.recentCompletionRequestLatencies=new Io(10);}stats(){let e=Object.fromEntries(Array.from(this.eventMap.entries()).map(([r,n])=>["count_"+r,n]));return {completion:{count_auto:this.autoCompletionCount,count_manual:this.manualCompletionCount,cache_hit:this.cacheHitCount,cache_miss:this.cacheMissCount,...e},completion_request:{count:this.completionRequestLatencyStats.count(),latency_avg:this.completionRequestLatencyStats.mean(),latency_p50:this.completionRequestLatencyStats.percentile(50),latency_p95:this.completionRequestLatencyStats.percentile(95),latency_p99:this.completionRequestLatencyStats.percentile(99)},completion_request_canceled:{count:this.completionRequestCanceledStats.count(),latency_avg:this.completionRequestCanceledStats.mean()},completion_request_timeout:{count:this.completionRequestTimeoutCount}}}windowed(){let e=this.recentCompletionRequestLatencies.getValues(),r=e.filter(i=>Number.isNaN(i)),n=e.filter(i=>!Number.isNaN(i)),s=n.reduce((i,o)=>i+o,0)/n.length;return {values:e,stats:{total:e.length,timeouts:r.length,responses:n.length,averageResponseTime:s}}}static check(e){let{values:r,stats:{total:n,timeouts:s,responses:i,averageResponseTime:o}}=e;return r.slice(-3).every(l=>l<3e3)?"healthy":s/n>.5&&s>=3?"highTimeoutRate":i>=3&&o>4e3?"slowResponseTime":null}};var Wr=class Wr extends events.EventEmitter{constructor(){super();this.logger=Ce.child({component:"TabbyAgent"});this.config=mc;this.userConfig={};this.clientConfig={};this.status="notInitialized";this.issues=[];this.serverHealthState=null;this.dataStore=null;this.completionCache=new Oo;this.completionDebounce=new Po;this.nonParallelProvideCompletionAbortController=null;this.completionProviderStats=new Ti;this.tryingConnectTimer=null;this.submitStatsTimer=null;this.tryingConnectTimer=setInterval(async()=>{this.status==="disconnected"&&(this.logger.debug("Trying to connect..."),await this.healthCheck());},Wr.tryConnectInterval),this.submitStatsTimer=setInterval(async()=>{await this.submitStats();},Wr.submitStatsInterval);}static async create(r){let n=new Wr;return n.dataStore=r?.dataStore,n.anonymousUsageLogger=await To.create({dataStore:r?.dataStore}),n}async applyConfig(){let r=this.config,n=this.status;this.config=_g(mc,this.userConfig,this.clientConfig),gn.forEach(i=>i.level=this.config.logs.level),this.anonymousUsageLogger.disabled=this.config.anonymousUsageTracking.disable,this.config.server.requestHeaders.Authorization===void 0?this.config.server.endpoint!==this.auth?.endpoint&&(this.auth=await ro.create({endpoint:this.config.server.endpoint,dataStore:this.dataStore}),this.auth.on("updated",this.setupApi.bind(this))):this.auth=null,await this.setupApi(),(0, Lc.default)(r.server,this.config.server)||(this.serverHealthState=null,this.completionProviderStats.resetWindowed(),this.popIssue("slowCompletionResponseTime"),this.popIssue("highCompletionTimeoutRate"),n==="unauthorized"&&this.status==="unauthorized"&&this.emitAuthRequired());let s={event:"configUpdated",config:this.config};this.logger.debug({event:s},"Config updated"),super.emit("configUpdated",s);}async setupApi(){this.api=Or({baseUrl:this.config.server.endpoint.replace(/\/+$/,""),headers:{Authorization:this.auth?.token?`Bearer ${this.auth.token}`:void 0,...this.config.server.requestHeaders}}),await this.healthCheck();}changeStatus(r){if(this.status!=r){this.status=r;let n={event:"statusChanged",status:r};this.logger.debug({event:n},"Status changed"),super.emit("statusChanged",n),this.status==="unauthorized"&&this.emitAuthRequired();}}issueFromName(r){switch(r){case"highCompletionTimeoutRate":return {name:"highCompletionTimeoutRate",completionResponseStats:this.completionProviderStats.windowed().stats};case"slowCompletionResponseTime":return {name:"slowCompletionResponseTime",completionResponseStats:this.completionProviderStats.windowed().stats}}}pushIssue(r){this.issues.indexOf(r)===-1&&(this.issues.push(r),this.logger.debug({issue:r},"Issues Pushed"),this.emitIssueUpdated());}popIssue(r){let n=this.issues.indexOf(r);n>=0&&(this.issues.splice(n,1),this.logger.debug({issue:r},"Issues Popped"),this.emitIssueUpdated());}emitAuthRequired(){let r={event:"authRequired",server:this.config.server};super.emit("authRequired",r);}emitIssueUpdated(){let r={event:"issuesUpdated",issues:this.issues};super.emit("issuesUpdated",r);}async submitStats(){let r=this.completionProviderStats.stats();r.completion_request.count>0&&(await this.anonymousUsageLogger.event("AgentStats",{stats:r}),this.completionProviderStats.reset(),this.logger.debug({stats:r},"Stats submitted"));}async post(r,n,s){let i=Ar();this.logger.debug({requestId:i,path:r,requestOptions:n,abortOptions:s},"API request");try{let o=Math.min(2147483647,s?.timeout||this.config.server.requestTimeout),l=Yn([AbortSignal.timeout(o),s?.signal]),c=await this.api.POST(r,{...n,signal:l});if(c.error)throw new at(c.response);return this.logger.debug({requestId:i,path:r,response:c.data},"API response"),this.changeStatus("ready"),c.data}catch(o){throw bs(o)?this.logger.debug({requestId:i,path:r,error:o},"API request timeout"):an(o)?this.logger.debug({requestId:i,path:r,error:o},"API request canceled"):o instanceof at&&[401,403,405].indexOf(o.status)!==-1&&new URL(this.config.server.endpoint).hostname.endsWith("app.tabbyml.com")&&this.config.server.requestHeaders.Authorization===void 0?(this.logger.debug({requestId:i,path:r,error:o},"API unauthorized"),this.changeStatus("unauthorized")):o instanceof at?(this.logger.error({requestId:i,path:r,error:o},"API error"),this.changeStatus("disconnected")):(this.logger.error({requestId:i,path:r,error:o},"API request failed with unknown error"),this.changeStatus("disconnected")),o}}async healthCheck(r){try{let n=await this.post("/v1/health",{},r);typeof n=="object"&&n.model!==void 0&&n.device!==void 0&&(this.serverHealthState=n,this.status==="ready"&&this.anonymousUsageLogger.uniqueEvent("AgentConnected",n));}catch{this.changeStatus("disconnected"),this.serverHealthState=null;}}createSegments(r){let n=this.config.completion.prompt.maxPrefixLines,s=this.config.completion.prompt.maxSuffixLines,{prefixLines:i,suffixLines:o}=r;return {prefix:i.slice(Math.max(i.length-n,0)).join(""),suffix:o.slice(0,s).join("")}}calculateReplaceRange(r,n){let{suffixLines:s}=n,i=s[0]?.trimEnd()||"";if(ge(i))return r;for(let o of r.choices){let l=o.text.slice(n.position-o.replaceRange.start),c=Ss(l);ge(c)||(i.startsWith(c)?(o.replaceRange.end=n.position+c.length,this.logger.trace({context:n,completion:o.text,range:o.replaceRange,unpaired:c},"Adjust replace range")):c.startsWith(i)&&(o.replaceRange.end=n.position+i.length,this.logger.trace({context:n,completion:o.text,range:o.replaceRange,unpaired:c},"Adjust replace range")));}return r}async initialize(r){if(r.clientProperties){let{user:n,session:s}=r.clientProperties;gn.forEach(i=>i.setBindings?.({...s})),s&&Object.entries(s).forEach(([i,o])=>{this.anonymousUsageLogger.setSessionProperties(i,o);}),n&&Object.entries(n).forEach(([i,o])=>{this.anonymousUsageLogger.setUserProperties(i,o);});}return bn&&(await bn.load(),this.userConfig=bn.config,bn.on("updated",async n=>{this.userConfig=n,await this.applyConfig();}),bn.watch()),r.config&&(this.clientConfig=r.config),await this.applyConfig(),await this.anonymousUsageLogger.uniqueEvent("AgentInitialized"),this.logger.debug({options:r},"Initialized"),this.status!=="notInitialized"}async finalize(){return this.status==="finalized"?!1:(await this.submitStats(),this.tryingConnectTimer&&(clearInterval(this.tryingConnectTimer),this.tryingConnectTimer=null),this.submitStatsTimer&&(clearInterval(this.submitStatsTimer),this.submitStatsTimer=null),this.changeStatus("finalized"),!0)}async updateClientProperties(r,n,s){switch(r){case"session":let i={};sn(i,n,s),gn.forEach(o=>o.setBindings?.(i)),this.anonymousUsageLogger.setSessionProperties(n,s);break;case"user":this.anonymousUsageLogger.setUserProperties(n,s);break}return !0}async updateConfig(r,n){let s=Og(this.clientConfig,r);return (0, Lc.default)(s,n)||(n===void 0?Pg(this.clientConfig,r):sn(this.clientConfig,r,n),await this.applyConfig()),!0}async clearConfig(r){return await this.updateConfig(r,void 0)}getConfig(){return this.config}getStatus(){return this.status}getIssues(){return this.issues}getIssueDetail(r){return r.index!==void 0?this.issueFromName(this.issues[r.index]):r.name!==void 0&&this.issues.indexOf(r.name)!==-1?this.issueFromName(r.name):null}getServerHealthState(){return this.serverHealthState}async requestAuthUrl(r){if(this.status==="notInitialized")throw new Error("Agent is not initialized");return await this.healthCheck(r),this.status!=="unauthorized"?null:await this.auth.requestAuthUrl(r)}async waitForAuthToken(r,n){if(this.status==="notInitialized")throw new Error("Agent is not initialized");await this.auth.pollingToken(r,n),await this.setupApi();}async provideCompletions(r,n){if(this.status==="notInitialized")throw new Error("Agent is not initialized");this.logger.trace({request:r},"Call provideCompletions"),this.nonParallelProvideCompletionAbortController&&this.nonParallelProvideCompletionAbortController.abort(),this.nonParallelProvideCompletionAbortController=new AbortController;let s=Yn([this.nonParallelProvideCompletionAbortController.signal,n?.signal]),i=null,o={triggerMode:r.manually?"manual":"auto",cacheHit:!1,aborted:!1,requestSent:!1,requestLatency:0,requestCanceled:!1,requestTimeout:!1},l=null,c=new Sr(r);try{if(this.completionCache.has(c))o.cacheHit=!0,this.logger.debug({context:c},"Completion cache hit"),await this.completionDebounce.debounce({request:r,config:this.config.completion.debounce,responseTime:0},{signal:s}),i=this.completionCache.get(c);else {o.cacheHit=!1;let p=this.createSegments(c);if(ge(p.prefix))o=null,this.logger.debug("Segment prefix is blank, returning empty completion response"),i={id:"agent-"+Ar(),choices:[]};else {await this.completionDebounce.debounce({request:r,config:this.config.completion.debounce,responseTime:this.completionProviderStats.stats().averageResponseTime},n),o.requestSent=!0,l=performance.now();try{let u=await this.post("/v1/completions",{body:{language:r.language,segments:p,user:this.auth?.user}},{signal:s,timeout:r.manually?this.config.completion.timeout.manually:this.config.completion.timeout.auto});o.requestLatency=performance.now()-l,i={id:u.id,choices:u.choices.map(g=>({index:g.index,text:g.text,replaceRange:{start:r.position,end:r.position}}))};}catch(u){throw an(u)&&(o.requestCanceled=!0,o.requestLatency=performance.now()-l),bs(u)&&(o.requestTimeout=!0,o.requestLatency=NaN),u}if(i=await b0(c,i),n?.signal?.aborted)throw n.signal.reason;this.completionCache.buildCache(c,i);}}if(i=await E0(c,i),n?.signal?.aborted)throw n.signal.reason;i=this.calculateReplaceRange(i,c);}catch(p){throw an(p)||bs(p)?o&&(o.aborted=!0):o=null,p}finally{if(o&&(this.completionProviderStats.add(o),o.requestSent&&!o.requestCanceled)){let p=this.completionProviderStats.windowed();switch(Ti.check(p)){case"healthy":this.popIssue("slowCompletionResponseTime"),this.popIssue("highCompletionTimeoutRate");break;case"highTimeoutRate":this.popIssue("slowCompletionResponseTime"),this.pushIssue("highCompletionTimeoutRate");break;case"slowResponseTime":this.popIssue("highCompletionTimeoutRate"),this.pushIssue("slowCompletionResponseTime");break}}}return this.logger.trace({context:c,completionResponse:i},"Return from provideCompletions"),i}async postEvent(r,n){if(this.status==="notInitialized")throw new Error("Agent is not initialized");return this.completionProviderStats.addEvent(r.type),await this.post("/v1/events",{body:r,params:{query:{select_kind:r.select_kind}},parseAs:"text"},n),!0}};Wr.tryConnectInterval=1e3*30,Wr.submitStatsInterval=1e3*60*60*24;var ko=Wr;Nt();var Lo=class{constructor(){this.process=process;this.inStream=process.stdin;this.outStream=process.stdout;this.logger=Ce.child({component:"StdIO"});this.buffer="";this.abortControllers={};this.agent=null;}async handleInput(e){let r=e.toString();this.buffer+=r;let n=Pe(this.buffer);if(!(n.length<1)){n[n.length-1].endsWith(` `)?this.buffer="":this.buffer=n.pop();for(let s of n){let i=null;try{i=JSON.parse(s);}catch(l){this.logger.error({error:l},`Failed to parse request: ${s}`);continue}this.logger.debug({request:i},"Received request");let o=await this.handleRequest(i);this.sendResponse(o),this.logger.debug({response:o},"Sent response");}}}async handleRequest(e){let r=0,n=[0,null],s=new AbortController;try{if(!this.agent)throw new Error(`Agent not bound. `);r=e[0],n[0]=r;let i=e[1].func;if(i==="cancelRequest")n[1]=this.cancelRequest(e);else {let o=this.agent[i];if(!o)throw new Error(`Unknown function: ${i}`);let l=e[1].args;l.length>0&&typeof l[l.length-1]=="object"&&l[l.length-1].signal&&(this.abortControllers[r]=s,l[l.length-1].signal=s.signal),n[1]=await o.apply(this.agent,l);}}catch(i){an(i)?this.logger.debug({error:i,request:e},"Request canceled"):this.logger.error({error:i,request:e},"Failed to handle request");}finally{return this.abortControllers[r]&&delete this.abortControllers[r],n}}cancelRequest(e){let r=e[1].args[0],n=this.abortControllers[r];return n?(n.abort(),!0):!1}sendResponse(e){this.outStream.write(JSON.stringify(e)+` `);}bind(e){this.agent=e;for(let r of y0)this.agent.on(r,n=>{this.sendResponse([0,n]);});}listen(){this.inStream.on("data",this.handleInput.bind(this)),["SIGTERM","SIGINT"].forEach(e=>{this.process.on(e,async()=>{this.agent&&this.agent.getStatus()!=="finalized"&&await this.agent.finalize(),this.process.exit(0);});});}};var T0=new Lo;ko.create().then(t=>{T0.bind(t),T0.listen();}); diff --git a/clients/vim/package.json b/clients/vim/package.json index df8eaa9..d0751b9 100644 --- a/clients/vim/package.json +++ b/clients/vim/package.json @@ -1,6 +1,6 @@ { "name": "vim-tabby", - "version": "0.0.1", + "version": "1.0.0", "description": "Vim plugin for Tabby AI coding assistant.", "repository": "https://github.com/TabbyML/tabby", "scripts": {