github-actions[bot] commited on
Commit
451814a
·
1 Parent(s): fd2adb7

Deploy: Update from GitHub Actions build

Browse files
Files changed (1) hide show
  1. dist/index.js +10 -10
dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- var Le=Object.defineProperty;var Q=(t,e)=>()=>(t&&(e=t(t=0)),e);var He=(t,e)=>{for(var o in e)Le(t,o,{get:e[o],enumerable:!0})};import W from"node:fs";function ze(){W.existsSync(I.logDir)||W.mkdirSync(I.logDir,{recursive:!0})}function Ge(...t){return t.map(e=>typeof e=="object"&&e!==null?JSON.stringify(e,null,2):String(e)).join(" ")}async function Ue(t,e){if(!I.enableFile)return;ze();let r=`[${new Date().toISOString()}] [${t}] ${e}
2
- `;try{await W.promises.appendFile(I.logFile,r)}catch(i){console.error("\u5199\u5165\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25:",i)}}function je(t,...e){if(!I.enableConsole)return;let o={[$.DEBUG]:console.debug,[$.INFO]:console.log,[$.WARN]:console.warn,[$.ERROR]:console.error}[t]||console.log,r=new Date().toLocaleTimeString();o(`[${r}] [${t}]`,...e)}function Z(t,...e){let o=Ge(...e);je(t,...e),Ue(t,o)}var $,I,n,T,k=Q(()=>{$={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},I={logFile:"./logs/app.log",logDir:"./logs",enableConsole:!0,enableFile:!0,logLevel:process.env.LOG_LEVEL||$.INFO};n=(...t)=>Z($.INFO,...t),T=(...t)=>Z($.ERROR,...t)});var oe={};He(oe,{checkCookieAvailability:()=>We,ensureDirectoryExists:()=>te,getHumanReadableTimestamp:()=>ee,loadCookies:()=>K,saveScreenshot:()=>X,waitForUserInput:()=>Ke});import R from"node:fs";import Be from"node:path";import qe from"node:readline";function ee(){return new Date().toISOString().replace(/T/,"_").replace(/:/g,"-").replace(/\..+/,"")}function te(t){R.existsSync(t)||(R.mkdirSync(t,{recursive:!0}),n(`\u5DF2\u521B\u5EFA\u76EE\u5F55: ${t}`))}function We(t,e){if(e)try{return JSON.parse(e),n("\u53D1\u73B0\u5E76\u9A8C\u8BC1\u4E86\u73AF\u5883\u53D8\u91CF\u4E2D\u7684 COOKIES\u3002"),!0}catch(o){T("\u73AF\u5883\u53D8\u91CF COOKIES \u683C\u5F0F\u65E0\u6548 (\u5FC5\u987B\u662F JSON \u6570\u7EC4\u5B57\u7B26\u4E32):",o.message)}return R.existsSync(t)?(n(`\u53D1\u73B0 Cookie \u6587\u4EF6: ${t}`),!0):(T(`Cookie \u6587\u4EF6\u4E0D\u5B58\u5728: ${t}\uFF0C\u4E14\u672A\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002`),n("\u8BF7\u5148\u8FD0\u884C `npm run login` \u6216\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002"),!1)}function K(t,e){try{if(e)return n("\u4ECE\u73AF\u5883\u53D8\u91CF COOKIES \u52A0\u8F7D Cookie..."),JSON.parse(e);if(R.existsSync(t))return n(`\u4ECE\u6587\u4EF6\u52A0\u8F7D Cookie: ${t}`),JSON.parse(R.readFileSync(t,"utf8"))}catch(o){throw T("\u52A0\u8F7D Cookie \u5931\u8D25:",o),new Error("\u65E0\u6CD5\u52A0\u8F7D\u6216\u89E3\u6790 Cookie\u3002")}return[]}async function X(t,e,o="screenshot"){te(e);let r=ee(),i=Be.join(e,`${o}_${r}.png`);return await t.screenshot({path:i,fullPage:!0}),n(`\u622A\u56FE\u5DF2\u4FDD\u5B58: ${i}`),i}function Ke(){let t=qe.createInterface({input:process.stdin,output:process.stdout});return new Promise(e=>{t.question("",()=>{t.close(),e()})})}var F=Q(()=>{k()});import{H3 as ot,serve as rt,serveStatic as ke}from"h3";import{stat as Re,readFile as Ae}from"node:fs/promises";import{join as Oe}from"node:path";import{chromium as Xe}from"playwright";import De from"dotenv";De.config();var Fe={server:{port:parseInt(process.env.PORT||"3096",10),host:process.env.HOST||"localhost"},browser:{headless:(process.env.HEADLESS||"true").toLowerCase()!=="false",timeout:parseInt(process.env.TIMEOUT||"30000",10),executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,args:["--disable-blink-features=AutomationControlled","--no-sandbox","--disable-dev-shm-usage","--disable-infobars","--disable-extensions"],userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},cookieFile:"./cookies.json",cookiesFromEnv:process.env.COOKIES,screenshotDir:"./screenshots",aiStudio:{url:process.env.AI_STUDIO_URL||"https://aistudio.google.com/prompts/new_chat",responseTimeout:parseInt(process.env.RESPONSE_TIMEOUT||"600000",10),pageTimeout:parseInt(process.env.PAGE_TIMEOUT||"30000",10)},api:{defaultModel:process.env.DEFAULT_MODEL||"gemini-pro",maxTokens:65536,temperature:1,token:process.env.API_TOKEN},models:{"gemini-2.5-pro":{displayName:"Gemini 2.5 Pro",id:"gemini-2.5-pro",object:"model",created:1704067200,owned_by:"google",permission:[],root:"gemini-2.5-pro",parent:null},"gemini-2.5-flash":{displayName:"Gemini 2.5 Flash",id:"gemini-2.5-flash",object:"model",created:1704067200,owned_by:"google",permission:[],root:"gemini-2.5-flash",parent:null},"gemini-pro":{displayName:"Gemini Pro",id:"gemini-pro",object:"model",created:1701388800,owned_by:"google",permission:[],root:"gemini-pro",parent:null},"gemini-flash":{displayName:"Gemini Flash",id:"gemini-flash",object:"model",created:1701388800,owned_by:"google",permission:[],root:"gemini-flash",parent:null}},debug:{logRequests:process.env.DEBUG_REQUESTS==="true",logResponses:process.env.DEBUG_RESPONSES==="true",saveScreenshots:process.env.SAVE_SCREENSHOTS==="true"}},c=Fe;F();k();var v=null,M=null,z=class{constructor(e=5){this.maxSize=e,this.availablePages=[],this.busyPages=new Set,this.totalPages=0}async getPage(){if(this.availablePages.length>0){let e=this.availablePages.pop();return this.busyPages.add(e),n(`\u4ECE\u9875\u9762\u6C60\u83B7\u53D6\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),e}if(this.totalPages<this.maxSize){let{context:e}=await Je(),o=await e.newPage();return this.busyPages.add(o),this.totalPages++,n(`\u521B\u5EFA\u65B0\u9875\u9762\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}\uFF0C\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),o}return n("\u9875\u9762\u6C60\u5DF2\u6EE1\uFF0C\u7B49\u5F85\u9875\u9762\u91CA\u653E..."),new Promise(e=>{let o=()=>{if(this.availablePages.length>0){let r=this.availablePages.pop();this.busyPages.add(r),n(`\u7B49\u5F85\u540E\u83B7\u53D6\u5230\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),e(r)}else setTimeout(o,100)};o()})}async releasePage(e){if(!this.busyPages.has(e)){n("\u5C1D\u8BD5\u91CA\u653E\u4E0D\u5728\u5FD9\u788C\u5217\u8868\u4E2D\u7684\u9875\u9762");return}if(e._needsRemoval){n("\u9875\u9762\u88AB\u6807\u8BB0\u4E3A\u9700\u8981\u79FB\u9664\uFF0C\u5C06\u4ECE\u6C60\u4E2D\u79FB\u9664"),await this.removePage(e);return}try{await this.cleanupPage(e),this.busyPages.delete(e),this.availablePages.push(e),n(`\u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D\uFF0C\u53EF\u7528\u9875\u9762\u6570: ${this.availablePages.length}\uFF0C\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`)}catch(o){n(`\u6E05\u7406\u9875\u9762\u65F6\u51FA\u9519\uFF0C\u5C06\u5173\u95ED\u8BE5\u9875\u9762: ${o.message}`),await this.removePage(e)}}async cleanupPage(e){try{e.removeAllListeners();try{await e.evaluate(()=>{Object.keys(window).forEach(r=>{(r.startsWith("__handleStreamChunk")||r.startsWith("__onStreamChunk")||r.startsWith("__onStreamEnd"))&&delete window[r]}),window.__streamInterceptor&&(typeof window.__streamInterceptor.deactivate=="function"&&window.__streamInterceptor.deactivate(),delete window.__streamInterceptor),delete window.__handleStreamChunk,delete window.__onStreamChunk,delete window.__onStreamEnd,delete window.__streamCallbacks})}catch(o){n(`\u6E05\u7406\u9875\u9762\u72B6\u6001\u65F6\u51FA\u73B0evaluate\u9519\u8BEF: ${o.message}`)}n("\u9875\u9762\u72B6\u6001\u5DF2\u6E05\u7406")}catch(o){throw new Error(`\u6E05\u7406\u9875\u9762\u5931\u8D25: ${o.message}`)}}async removePage(e){try{this.busyPages.delete(e);let o=this.availablePages.indexOf(e);o>-1&&this.availablePages.splice(o,1),await e.close(),this.totalPages--,n(`\u9875\u9762\u5DF2\u4ECE\u6C60\u4E2D\u79FB\u9664\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}`)}catch(o){n(`\u5173\u95ED\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}}async cleanup(){n("\u5F00\u59CB\u6E05\u7406\u9875\u9762\u6C60...");for(let e of this.busyPages)try{await e.close()}catch(o){n(`\u5173\u95ED\u5FD9\u788C\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}for(let e of this.availablePages)try{await e.close()}catch(o){n(`\u5173\u95ED\u53EF\u7528\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}this.busyPages.clear(),this.availablePages=[],this.totalPages=0,n("\u9875\u9762\u6C60\u6E05\u7406\u5B8C\u6210")}getStatus(){return{total:this.totalPages,available:this.availablePages.length,busy:this.busyPages.size,maxSize:this.maxSize}}},b=null;async function Je(){if(!v){v=await Xe.launch({headless:c.browser.headless,timeout:c.browser.timeout,args:c.browser.args,executablePath:c.browser.executablePath}),M=await v.newContext({userAgent:c.browser.userAgent});let t=K(c.cookieFile,c.cookiesFromEnv);await M.addCookies(t)}return{browser:v,context:M}}function ne(t=5){return b||(b=new z(t),n(`\u9875\u9762\u6C60\u5DF2\u521D\u59CB\u5316\uFF0C\u6700\u5927\u9875\u9762\u6570: ${t}`)),b}function ae(){return b||(b=new z,n("\u9875\u9762\u6C60\u5DF2\u81EA\u52A8\u521D\u59CB\u5316\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E")),b}async function G(){let e=await ae().getPage();return await e.bringToFront(),e}async function A(t,e,o={}){let r=t.url();console.log("\u5F53\u524D\u9875\u9762URL:",r),console.log("\u76EE\u6807URL:",e);try{return r!==e?(console.log("\u9875\u9762URL\u4E0D\u5339\u914D\uFF0C\u9700\u8981\u5BFC\u822A..."),await t.goto(e,{waitUntil:"load",timeout:3e4,...o}),console.log("\u9875\u9762\u5BFC\u822A\u5B8C\u6210"),!0):(console.log("\u9875\u9762\u5DF2\u5728\u76EE\u6807URL\uFF0C\u8FDB\u884C\u5237\u65B0\u4EE5\u786E\u4FDD\u6700\u65B0\u72B6\u6001..."),await t.bringToFront(),await t.reload({waitUntil:"load",timeout:3e4,...o}),console.log("\u9875\u9762\u5237\u65B0\u5B8C\u6210"),!0)}catch{}return!1}async function O(t){await ae().releasePage(t)}function N(){return b?b.getStatus():{total:0,available:0,busy:0,maxSize:0}}async function re(){b&&(await b.cleanup(),b=null),M&&(await M.close(),M=null),v&&(await v.close(),v=null)}async function se(t,e={}){let{minClicks:o=1,maxClicks:r=3,minDelay:i=300,maxDelay:a=500,referenceElement:s=null}=e;try{n("\u5F00\u59CB\u6A21\u62DF\u4EBA\u7C7B\u968F\u673A\u70B9\u51FB\u884C\u4E3A...");let h=Math.floor(Math.random()*(r-o+1))+o;n(`\u5C06\u8FDB\u884C ${h} \u6B21\u968F\u673A\u70B9\u51FB`);let d=null;if(s)try{let l=await s.boundingBox();l&&(d={x:l.x-50,y:Math.max(0,l.y-200),width:l.width+50,height:300},n(`\u4F7F\u7528\u8F93\u5165\u6846\u9644\u8FD1\u7684\u5B89\u5168\u533A\u57DF: x=${d.x}, y=${d.y}, w=${d.width}, h=${d.height}`))}catch(l){n(`\u83B7\u53D6\u53C2\u8003\u5143\u7D20\u4F4D\u7F6E\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: ${l.message}`)}if(!d){let l=t.viewportSize(),p=l?.width||1280,f=l?.height||720;d={x:p*.3,y:f*.3,width:p*.4,height:f*.2},n(`\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: x=${d.x}, y=${d.y}, w=${d.width}, h=${d.height}`)}for(let l=0;l<h;l++)try{let p=Math.floor(Math.random()*d.width)+d.x,f=Math.floor(Math.random()*d.height)+d.y;n(`\u7B2C ${l+1} \u6B21\u5B89\u5168\u70B9\u51FB: (${p}, ${f})`);let u=await t.locator("*").first().evaluate((m,C)=>{let w=document.elementFromPoint(C.x,C.y);if(!w)return{safe:!0};let y=w.tagName.toLowerCase(),S=w.hasAttribute("href"),E=w.hasAttribute("onclick")||w.onclick,_=y==="button"||w.type==="button",g=y==="a"||S,x=["input","textarea","select"].includes(y);return{safe:!_&&!g&&!E&&!x,tagName:y,hasHref:S,hasOnClick:E,isButton:_,isLink:g,isInput:x}},{x:p,y:f});if(u.safe?(await t.mouse.move(p,f,{steps:Math.floor(Math.random()*10)+5}),await t.waitForTimeout(Math.floor(Math.random()*200)+100),await t.mouse.click(p,f),n(`\u5B89\u5168\u70B9\u51FB\u5B8C\u6210: (${p}, ${f})`)):n(`\u8DF3\u8FC7\u4E0D\u5B89\u5168\u7684\u70B9\u51FB\u4F4D\u7F6E (${p}, ${f}): ${u.tagName}`),l<h-1){let m=Math.floor(Math.random()*(a-i+1))+i;n(`\u7B49\u5F85 ${m}ms \u540E\u8FDB\u884C\u4E0B\u4E00\u6B21\u70B9\u51FB`),await t.waitForTimeout(m)}}catch(p){n(`\u7B2C ${l+1} \u6B21\u70B9\u51FB\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u6B21: ${p.message}`)}n("\u5B89\u5168\u968F\u673A\u70B9\u51FB\u6A21\u62DF\u5B8C\u6210")}catch(h){n(`\u6A21\u62DF\u5B89\u5168\u968F\u673A\u70B9\u51FB\u65F6\u51FA\u73B0\u9519\u8BEF: ${h.message}`)}}async function ie(t,e={}){let{includeScrolling:o=!0,includeMouseMovement:r=!0,includeRandomClicks:i=!0,duration:a=3e3}=e;try{n("\u5F00\u59CB\u6A21\u62DF\u590D\u6742\u7684\u4EBA\u7C7B\u884C\u4E3A...");let s=Date.now(),h=t.viewportSize(),d=h?.width||1280,l=h?.height||720;for(;Date.now()-s<a;){let p=Math.random();if(p<.3&&o){let u=Math.random()>.5?"down":"up",m=Math.floor(Math.random()*300)+100;n(`\u6A21\u62DF\u6EDA\u52A8: ${u}, \u8DDD\u79BB: ${m}px`),await t.mouse.wheel(0,u==="down"?m:-m)}else if(p<.6&&r){let u=Math.floor(Math.random()*d),m=Math.floor(Math.random()*l);n(`\u6A21\u62DF\u9F20\u6807\u79FB\u52A8\u5230: (${u}, ${m})`),await t.mouse.move(u,m,{steps:Math.floor(Math.random()*15)+5})}else if(p<.8&&i){let u=Math.floor(Math.random()*(d*.8))+d*.1,m=Math.floor(Math.random()*(l*.8))+l*.1;n(`\u6A21\u62DF\u968F\u673A\u70B9\u51FB: (${u}, ${m})`),await t.mouse.click(u,m)}let f=Math.floor(Math.random()*800)+200;await t.waitForTimeout(f)}n("\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u6A21\u62DF\u5B8C\u6210")}catch(s){n(`\u6A21\u62DF\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u65F6\u51FA\u73B0\u9519\u8BEF: ${s.message}`)}}async function U(t,e=5e3){try{n("\u68C0\u67E5\u662F\u5426\u6709\u6B22\u8FCE\u5BF9\u8BDD\u6846\u9700\u8981\u5173\u95ED...");let o="mat-dialog-container",r='button[mat-dialog-close][aria-label="close"]';if(await t.locator(o).first().isVisible({timeout:e})){n("\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846\uFF0C\u5C1D\u8BD5\u5173\u95ED...");let a=t.locator(r).first();return await a.isVisible({timeout:2e3})?(await a.click(),n("\u5DF2\u901A\u8FC7\u5173\u95ED\u6309\u94AE\u5173\u95ED\u6B22\u8FCE\u5BF9\u8BDD\u6846"),await t.waitForTimeout(1e3),!0):(n("\u672A\u627E\u5230\u5173\u95ED\u6309\u94AE\uFF0C\u5C1D\u8BD5\u6309ESC\u952E\u5173\u95ED\u5BF9\u8BDD\u6846"),await t.keyboard.press("Escape"),await t.waitForTimeout(1e3),!0)}else return n("\u672A\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846"),!1}catch(o){return n("\u5904\u7406\u6B22\u8FCE\u5BF9\u8BDD\u6846\u65F6\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u6267\u884C:",o.message),!1}}async function le(t,e,o){try{n("\u6CE8\u5165\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u5230\u9875\u9762\u4E2D...");try{await t.evaluate(()=>{Object.keys(window).forEach(s=>{(s.startsWith("__onStreamChunk_")||s.startsWith("__onStreamEnd_"))&&delete window[s]}),delete window.__onStreamChunk,delete window.__onStreamEnd})}catch{}let r=Date.now()+"_"+Math.random().toString(36).substr(2,9),i=`__onStreamChunk_${r}`,a=`__onStreamEnd_${r}`;await t.exposeFunction(i,e),await t.exposeFunction(a,o),await t.evaluate(()=>{window.__streamInterceptor&&(typeof window.__streamInterceptor.deactivate=="function"&&window.__streamInterceptor.deactivate(),delete window.__streamInterceptor);let s=window.XMLHttpRequest.prototype.open,h=window.XMLHttpRequest.prototype.send,d=["MakerSuiteService/GenerateContent","GenerateContent","streamGenerateContent","generateContent"],l=/\[\s*null\s*,\s*null\s*,\s*null\s*,\s*\[\s*"/,p="__END_OF_STREAM__",f=!1;window.__streamInterceptor={activate:()=>{f||(console.log("\u{1F3AF} \u6FC0\u6D3B\u6D41\u5F0F\u62E6\u622A\u5668..."),f=!0,window.XMLHttpRequest.prototype.open=function(u,m,...C){return this._url=m,this._method=u,console.log(`[XHR] \u8BF7\u6C42: ${u} ${m}`),s.apply(this,[u,m,...C])},window.XMLHttpRequest.prototype.send=function(...u){let m=this._url?this._url.toString():"",C=d.some(w=>m.includes(w));if(this._url&&C){console.log("\u{1F3AF} [XHR Stream] \u62E6\u622A\u5230\u76EE\u6807\u8BF7\u6C42:",m),console.log("\u{1F3AF} [XHR Stream] \u51C6\u5907\u63A5\u6536\u6D41\u5F0F\u6570\u636E...");let w=0,y="",S=!1,E=null,_=()=>{if(S)return;S=!0,console.log("[Stream] \u5224\u5B9A\u6D41\u5DF2\u7ED3\u675F"),clearTimeout(E);let g=y.slice(w);g&&window.__streamInterceptor.sendChunk(g),window.__streamInterceptor.sendChunk(p)};this.addEventListener("progress",()=>{if(!S)try{y=this.responseText||"";let g=y.slice(w);if(g){if(console.log(`[Stream] \u6536\u5230\u6570\u636E\u5757\uFF0C\u957F\u5EA6: ${g.length}\uFF0CHTTP\u72B6\u6001: ${this.status}`),console.log(`[Stream] \u6570\u636E\u5757\u5185\u5BB9\u9884\u89C8: ${g.substring(0,100)}...`),window.__streamInterceptor.sendChunk(g),w=y.length,this.status>=400&&this.readyState===4){console.log(`[Stream] progress\u4E8B\u4EF6\u4E2D\u68C0\u6D4B\u5230HTTP\u9519\u8BEF\u72B6\u6001\u7801 ${this.status}\uFF0C\u7ACB\u5373\u7ED3\u675F\u6D41`),_();return}l.test(g)&&(console.log("[Stream] \u2705 \u68C0\u6D4B\u5230\u6700\u7EC8 ID \u7B7E\u540D\u5757\uFF0C\u786E\u8BA4\u6D41\u7ED3\u675F"),_())}}catch(g){console.error("[Stream] \u5904\u7406progress\u4E8B\u4EF6\u65F6\u51FA\u9519:",g)}}),this.addEventListener("readystatechange",()=>{if(!S&&(console.log(`[Stream] readyState: ${this.readyState}, status: ${this.status}`),this.readyState===3||this.readyState===4))try{let g=this.responseText||"",x=g.slice(w);if(x&&(console.log(`[Stream] readyState ${this.readyState} \u6536\u5230\u6570\u636E\u5757\uFF0C\u957F\u5EA6: ${x.length}`),console.log(`[Stream] \u6570\u636E\u5757\u5185\u5BB9\u9884\u89C8: ${x.substring(0,200)}...`),window.__streamInterceptor.sendChunk(x),w=g.length,y=g,l.test(x)&&(console.log("[Stream] \u2705 readyState\u4E8B\u4EF6\u4E2D\u68C0\u6D4B\u5230\u6700\u7EC8\u7B7E\u540D"),_())),this.readyState===4&&!S)if(console.log(`[Stream] \u8BF7\u6C42\u5B8C\u6210\uFF0CHTTP\u72B6\u6001\u7801: ${this.status}`),this.status>=400){if(console.log(`[Stream] \u68C0\u6D4B\u5230HTTP\u9519\u8BEF\u72B6\u6001\u7801 ${this.status}\uFF0C\u7ACB\u5373\u5904\u7406\u9519\u8BEF\u54CD\u5E94`),y&&y!==g){let q=y.slice(w);q&&(console.log(`[Stream] \u53D1\u9001\u5269\u4F59\u9519\u8BEF\u54CD\u5E94\u6570\u636E: ${q}`),window.__streamInterceptor.sendChunk(q))}_()}else S||(console.log("[Stream] \u6B63\u5E38\u8BF7\u6C42\u5B8C\u6210\uFF0C\u8BBE\u7F6E\u4FDD\u9669\u8BA1\u65F6\u5668"),E=setTimeout(_,1e3))}catch(g){console.error("[Stream] \u5904\u7406readystatechange\u4E8B\u4EF6\u65F6\u51FA\u9519:",g)}}),this.addEventListener("load",()=>{S||(console.log('[Stream] "load" \u4E8B\u4EF6\u89E6\u53D1\uFF0C\u542F\u52A8\u6700\u7EC8\u786E\u8BA4\u8BA1\u65F6\u5668'),E=setTimeout(_,1500))}),this.addEventListener("error",g=>{console.error("[Stream] XHR \u8BF7\u6C42\u51FA\u9519:",g),S||_()}),this.addEventListener("abort",()=>{console.log("[Stream] XHR \u8BF7\u6C42\u88AB\u4E2D\u6B62"),S||_()})}return h.apply(this,u)})},deactivate:()=>{f&&(console.log("\u{1F504} \u505C\u7528\u6D41\u5F0F\u62E6\u622A\u5668..."),window.XMLHttpRequest.prototype.open=s,window.XMLHttpRequest.prototype.send=h,f=!1)},sendChunk:u=>{try{console.log(`[Stream] \u53D1\u9001\u6570\u636E\u5757\u5230Playwright\uFF0C\u957F\u5EA6: ${u.length}`),window.__handleStreamChunk?window.__handleStreamChunk(u):console.error("[Stream] __handleStreamChunk \u51FD\u6570\u4E0D\u5B58\u5728")}catch(m){console.error("[Stream] \u53D1\u9001\u6570\u636E\u5757\u65F6\u51FA\u9519:",m)}}},window.__streamCallbacks={onChunk:null,onEnd:null},window.__handleStreamChunk=function(u){try{console.log("[Stream] \u5904\u7406\u6570\u636E\u5757:",u.length,"\u5B57\u7B26"),u==="__END_OF_STREAM__"?window.__streamCallbacks.onEnd&&window.__streamCallbacks.onEnd():window.__streamCallbacks.onChunk&&window.__streamCallbacks.onChunk(u)}catch(m){console.error("[Stream] \u5904\u7406\u6570\u636E\u5757\u65F6\u51FA\u9519:",m)}},console.log("[Stream] \u62E6\u622A\u5668\u548C\u5904\u7406\u51FD\u6570\u5DF2\u521B\u5EFA\u5B8C\u6210")}),await t.evaluate(s=>{window.__streamCallbacks.onChunk=window[s],console.log("[Stream] onChunk\u56DE\u8C03\u51FD\u6570\u5DF2\u8FDE\u63A5:",s)},i),await t.evaluate(s=>{window.__streamCallbacks.onEnd=window[s],console.log("[Stream] onEnd\u56DE\u8C03\u51FD\u6570\u5DF2\u8FDE\u63A5:",s)},a),n("\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u6CE8\u5165\u5B8C\u6210")}catch(r){throw n(`\u6CE8\u5165\u6D41\u5F0F\u62E6\u622A\u811A\u672C\u65F6\u51FA\u9519: ${r.message}`),r}}async function ce(t){try{await t.evaluate(()=>{window.__streamInterceptor&&window.__streamInterceptor.activate(),window.__handleStreamChunk||(console.log("[Stream] \u91CD\u65B0\u521B\u5EFA __handleStreamChunk \u51FD\u6570"),window.__handleStreamChunk=function(e){try{console.log("[Stream] \u5904\u7406\u6570\u636E\u5757:",e.length,"\u5B57\u7B26"),e==="__END_OF_STREAM__"?window.__onStreamEnd&&window.__onStreamEnd():window.__onStreamChunk&&window.__onStreamChunk(e)}catch(o){console.error("[Stream] \u5904\u7406\u6570\u636E\u5757\u65F6\u51FA\u9519:",o)}},console.log("[Stream] __handleStreamChunk \u51FD\u6570\u5DF2\u91CD\u65B0\u521B\u5EFA"))}),n("\u6D41\u5F0F\u62E6\u622A\u5668\u5DF2\u6FC0\u6D3B")}catch(e){throw n(`\u6FC0\u6D3B\u6D41\u5F0F\u62E6\u622A\u5668\u65F6\u51FA\u9519: ${e.message}`),e}}async function ue(t){try{await t.evaluate(()=>{window.__streamInterceptor&&window.__streamInterceptor.deactivate()}),n("\u6D41\u5F0F\u62E6\u622A\u5668\u5DF2\u505C\u7528")}catch(e){n(`\u505C\u7528\u6D41\u5F0F\u62E6\u622A\u5668\u65F6\u51FA\u9519: ${e.message}`)}}function me(){process.on("SIGINT",async()=>{console.log("\u6B63\u5728\u6E05\u7406\u8D44\u6E90..."),await re(),process.exit(0)}),process.on("SIGTERM",async()=>{console.log("\u6B63\u5728\u6E05\u7406\u8D44\u6E90..."),await re(),process.exit(0)})}k();var de=null;function pe(t=1e4){if(de){n("\u9875\u9762\u6C60\u76D1\u63A7\u5DF2\u5728\u8FD0\u884C\u4E2D\u3002");return}n(`\u5F00\u59CB\u76D1\u63A7\u9875\u9762\u6C60\u72B6\u6001\uFF0C\u95F4\u9694: ${t}ms`),de=setInterval(()=>{let e=N(),o=new Date().toLocaleTimeString(),r=e.total>0?(e.busy/e.total*100).toFixed(1):0;n(`[${o}] \u9875\u9762\u6C60\u72B6\u6001: \u603B\u8BA1=${e.total}, \u53EF\u7528=${e.available}, \u5FD9\u788C=${e.busy}, \u4F7F\u7528\u7387=${r}%`)},t)}function he(){let t=N(),e=new Date().toLocaleString(),o=t.total>0?(t.busy/t.total*100).toFixed(1):0;console.log(`
3
  --- \u9875\u9762\u6C60\u72B6\u6001 @ ${e} ---
4
  \u603B\u9875\u9762\u6570: ${t.total}
5
  \u53EF\u7528\u9875\u9762\u6570: ${t.available}
@@ -7,17 +7,17 @@ var Le=Object.defineProperty;var Q=(t,e)=>()=>(t&&(e=t(t=0)),e);var He=(t,e)=>{f
7
  \u6700\u5927\u9875\u9762\u6570: ${t.maxSize}
8
  \u4F7F\u7528\u7387: ${o}%
9
  ------------------------------------
10
- `)}function fe(t){let e=t.node.res.getHeaders();if(e["access-control-allow-origin"]||t.node.res.setHeader("Access-Control-Allow-Origin",process.env.CORS_ORIGIN||"*"),e["access-control-allow-methods"]||t.node.res.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),e["access-control-allow-headers"]||t.node.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),e["access-control-max-age"]||t.node.res.setHeader("Access-Control-Max-Age","86400"),t.node.req.method==="OPTIONS")return t.node.res.statusCode=204,t.node.res.end()}function we(t){t.node.res.setHeader("Content-Type","text/event-stream"),t.node.res.setHeader("Cache-Control","no-cache"),t.node.res.setHeader("Connection","keep-alive"),t.node.res.setHeader("Access-Control-Allow-Origin",process.env.CORS_ORIGIN||"*"),t.node.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization")}function ge(t){let e=N(),o=e.total>0?Math.round(e.busy/e.total*100):0;return{status:"ok",timestamp:new Date().toISOString(),version:process.env.npm_package_version||"1.0.0",pagePool:{...e,utilization:`${o}%`}}}import{readBody as et,createError as tt}from"h3";import{createError as Ve}from"h3";function ye(t){let{messages:e,stream:o=!1,model:r=c.api.defaultModel,temperature:i=c.api.temperature}=t;if(!e||!Array.isArray(e)||e.length===0)throw Ve({statusCode:400,statusMessage:"Invalid request: `messages` must be a non-empty array."});return{prompt:e.map(s=>!s.role||!s.content?"":`${s.role}: ${s.content}`).join(`
11
 
12
- `),stream:o,model:r,temperature:i,messages:e}}import{createError as J}from"h3";function Se(t){if(!c.api.token){process.env.NODE_ENV==="production"&&console.warn("\u8B66\u544A: API_TOKEN \u672A\u5728\u751F\u4EA7\u73AF\u5883\u4E2D\u914D\u7F6E\uFF0CAPI \u5BF9\u5916\u5F00\u653E\uFF01");return}let e=t.node.req.headers.authorization;if(!e)throw J({statusCode:401,statusMessage:"Unauthorized: Missing Authorization header."});let[o,r]=e.split(" ");if(o!=="Bearer"||!r)throw J({statusCode:401,statusMessage:"Unauthorized: Invalid Authorization header format. Expected: Bearer <token>."});if(r!==c.api.token)throw J({statusCode:401,statusMessage:"Unauthorized: Invalid API token."})}var L=class{constructor(e,o={}){this.page=e,this.options={enableHumanSimulation:!0,...o},this.modelMapping=Object.fromEntries(Object.entries(c.models).map(([r,i])=>[r,i.displayName]))}async waitForPageLoad(){try{return await this.page.waitForSelector("body",{timeout:15e3}),await U(this.page),!0}catch(e){return console.error("\u9875\u9762\u52A0\u8F7D\u8D85\u65F6\u6216\u5931\u8D25:",e),!1}}async findInputElement(){try{await this.page.waitForSelector("footer ms-prompt-input-wrapper",{timeout:1e4}),console.log("\u8F93\u5165\u6846\u7684\u7236\u5BB9\u5668\u5DF2\u52A0\u8F7D\u3002")}catch{console.warn("\u7B49\u5F85\u8F93\u5165\u6846\u7236\u5BB9\u5668\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u67E5\u627E...")}let e=['ms-prompt-input-wrapper textarea[aria-label*="prompt"]','textarea[placeholder="Start typing a prompt"]','textarea[aria-label="Start typing a prompt"]',"footer textarea",'textarea[placeholder*="prompt"]','textarea[aria-label*="prompt"]','div[contenteditable="true"]',"textarea"];for(let o of e)try{let r=this.page.locator(o),i=await r.count();if(i>0){console.log(`\u9009\u62E9\u5668 "${o}" \u627E\u5230\u4E86 ${i} \u4E2A\u5143\u7D20\u3002\u6B63\u5728\u68C0\u67E5\u53EF\u89C1\u6027\u548C\u53EF\u7528\u6027...`);for(let a=0;a<i;a++){let s=r.nth(a);if(await s.isVisible()&&await s.isEnabled())return console.log(`\u6210\u529F\u627E\u5230\u53EF\u7528\u8F93\u5165\u6846: ${o} (\u7D22\u5F15 ${a})`),s}console.log(`\u9009\u62E9\u5668 "${o}" \u627E\u5230\u7684\u5143\u7D20\u5747\u4E0D\u53EF\u89C1\u6216\u4E0D\u53EF\u7528\u3002`)}}catch(r){console.warn(`\u4F7F\u7528\u9009\u62E9\u5668 "${o}" \u67E5\u627E\u65F6\u51FA\u9519: ${r.message}`)}if(console.error("\u5173\u952E\u9519\u8BEF: \u5C1D\u8BD5\u4E86\u6240\u6709\u9009\u62E9\u5668\u540E\uFF0C\u4ECD\u672A\u627E\u5230\u4EFB\u4F55\u53EF\u7528\u7684\u8F93\u5165\u5143\u7D20\u3002"),c.debug.saveScreenshots){let{saveScreenshot:o}=await Promise.resolve().then(()=>(F(),oe));await o(this.page,c.screenshotDir,"find-input-failed")}return null}async findSendButton(){let e=['button[aria-label="Run"]',"button.run-button",'button[aria-label*="Send"]','button[data-testid*="send"]'];for(let o of e){let r=this.page.locator(o);if(await r.count()>0){let i=r.first();if(!await i.isDisabled())return i}}return console.error("\u672A\u627E\u5230\u4EFB\u4F55\u53EF\u7528\u7684\u53D1\u9001\u6309\u94AE\u3002"),null}async fillMessage(e){let o=await this.findInputElement();if(!o)throw new Error("\u65E0\u6CD5\u627E\u5230\u8F93\u5165\u6846\u3002");try{return this.options.enableHumanSimulation&&await se(this.page,{referenceElement:o}),await o.fill(e),await this.page.waitForTimeout(200),console.log("\u6D88\u606F\u586B\u5145\u5B8C\u6210\u3002"),!0}catch(r){return console.error("\u586B\u5145\u6D88\u606F\u5931\u8D25:",r),!1}}async waitForSendButtonEnabled(e=1e4){try{return await this.page.locator('button[aria-label="Run"]:not([disabled]), button.run-button:not([disabled])').waitFor({state:"visible",timeout:e}),console.log("\u53D1\u9001\u6309\u94AE\u5DF2\u53EF\u7528\u3002"),!0}catch{return console.warn("\u7B49\u5F85\u53D1\u9001\u6309\u94AE\u53EF\u7528\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u3002"),!1}}async sendMessage(){this.options.enableHumanSimulation&&await ie(this.page,{includeScrolling:!1,duration:1500});let e=await this.findSendButton();if(!e)throw new Error("\u65E0\u6CD5\u627E\u5230\u53EF\u7528\u7684\u53D1\u9001\u6309\u94AE\u3002");try{return await e.click(),console.log("\u6D88\u606F\u5DF2\u53D1\u9001\u3002"),!0}catch(o){console.error("\u70B9\u51FB\u53D1\u9001\u6309\u94AE\u5931\u8D25:",o);try{return console.log("\u5C1D\u8BD5\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E (Ctrl+Enter) \u53D1\u9001..."),await this.page.keyboard.press("Control+Enter"),console.log("\u5DF2\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u3002"),!0}catch(r){return console.error("\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u4E5F\u5931\u8D25:",r),!1}}}async setModel(e){try{let o=this.modelMapping[e]||e,r=this.page.locator("ms-model-selector-two-column");if(await r.count()===0)return console.log("\u672A\u627E\u5230\u6A21\u578B\u9009\u62E9\u5668\uFF0C\u8DF3\u8FC7\u6A21\u578B\u8BBE\u7F6E\u3002"),!1;if((await r.locator(".model-option-content .gmat-body-medium").textContent())?.trim()===o)return console.log("\u5F53\u524D\u5DF2\u662F\u76EE\u6807\u6A21\u578B\uFF0C\u65E0\u9700\u5207\u6362\u3002"),!0;await r.click({timeout:5e3});let a=this.page.locator(".mat-mdc-select-panel");await a.waitFor({state:"visible",timeout:5e3});let s=a.locator("mat-option.model-option",{hasText:o});return await s.count()>0?(await s.first().click({timeout:5e3}),await this.page.waitForTimeout(1e3),console.log(`\u6A21\u578B\u5DF2\u6210\u529F\u8BBE\u7F6E\u4E3A: ${o}`),!0):(console.log(`\u672A\u5728\u4E0B\u62C9\u83DC\u5355\u4E2D\u627E\u5230\u76EE\u6807\u6A21\u578B: ${o}`),await this.page.keyboard.press("Escape"),!1)}catch(o){console.error("\u8BBE\u7F6E\u6A21\u578B\u65F6\u53D1\u751F\u9519\u8BEF:",o);try{await this.page.keyboard.press("Escape")}catch{}return!1}}async setTemperature(e){try{let o=this.page.locator('[data-test-id="temperatureSliderContainer"]');if(await o.count()===0)return console.log("\u672A\u627E\u5230\u6E29\u5EA6\u8BBE\u7F6E\u5BB9\u5668\uFF0C\u8DF3\u8FC7\u3002"),!1;let r=o.locator('input[type="number"]');return await r.count()>0?(await r.fill(e.toString()),await r.dispatchEvent("change"),console.log(`\u6E29\u5EA6\u5DF2\u8BBE\u7F6E\u4E3A: ${e}`),!0):(console.log("\u672A\u627E\u5230\u6E29\u5EA6\u6570\u5B57\u8F93\u5165\u6846\uFF0C\u8DF3\u8FC7\u8BBE\u7F6E\u3002"),!1)}catch(o){return console.error("\u8BBE\u7F6E\u6E29\u5EA6\u65F6\u51FA\u9519:",o),!1}}async processMessage(e,o={}){if(console.log("\u5F00\u59CB\u5904\u7406\u6D88\u606F..."),!await this.waitForPageLoad())throw new Error("\u9875\u9762\u52A0\u8F7D\u5931\u8D25\u3002");if(o.model&&await this.setModel(o.model),o.temperature!==void 0&&await this.setTemperature(o.temperature),!await this.fillMessage(e))throw new Error("\u6D88\u606F\u586B\u5199\u5931\u8D25\u3002");if(await this.waitForSendButtonEnabled(),!await this.sendMessage())throw new Error("\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002");return console.log("\u6D88\u606F\u53D1\u9001\u6210\u529F\uFF0C\u7B49\u5F85\u7F51\u7EDC\u62E6\u622A\u83B7\u53D6\u54CD\u5E94\u3002"),!0}};function Ye(t){return t.includes("The caller does not have permission")?(console.warn("\u68C0\u6D4B\u5230\u6743\u9650\u9519\u8BEF\uFF0C\u5C06\u89E6\u53D1\u91CD\u8BD5\u673A\u5236\u3002"),{permissionError:!0,content:"\u65E0\u6743\u8BBF\u95EE AI Studio\u3002\u8BF7\u68C0\u67E5 Cookie \u6216\u767B\u5F55\u72B6\u6001\u3002"}):null}function _e(t){let e=[];if(!t)return e;if(Array.isArray(t)){if(t.length>=2&&t[0]===null&&typeof t[1]=="string"&&t[1]&&t[1]!=="model"){let o=t.length>2?"thinking":"text";e.push({type:o,content:t[1].replace(/\\n/g,`
13
- `).replace(/\\"/g,'"')})}for(let o of t)e.push(..._e(o))}return e}function V(t){let e=Ye(t);if(e)return e;try{let a=t.trim().replace(/\n/g,",").replace(/,+/g,",");a.endsWith(",")&&(a=a.slice(0,-1)),a.startsWith("[")||(a="["+a),a.endsWith("]")||(a=a+"]"),a=a.replace(/,]/g,"]").replace(/\[,/g,"[");let s=JSON.parse(a),h=_e(s);if(h.length>0){let d=!1;return h.map(l=>(d?l.type="text":l.type==="text"&&(d=!0),l))}}catch{}let o=/\[null,\s*"((?:\\"|[^"])*)"/g,r=[],i;for(;(i=o.exec(t))!==null;)try{let a=i[1].replace(/\\n/g,`
14
- `).replace(/\\"/g,'"');if(a&&a!=="model"){let s=a.trim().startsWith("**")?"thinking":"text";r.push({type:s,content:a})}}catch{}if(r.length>0){let a=!1;return r.map(s=>(a?s.type="text":s.type==="text"&&(a=!0),s))}return null}function be(t,e,o="gemini-pro"){return{id:`chatcmpl-${Date.now()}`,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:o,choices:[{index:0,delta:{content:t||"",type:e||"text"},logprobs:null,finish_reason:null}]}}function Y(t,e="gemini-pro"){return{object:"error",message:t,type:"invalid_request_error",model:e}}function Ee(t,e="gemini-pro"){return{id:`chatcmpl-${Date.now()}`,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}],usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}}var j=3,Ce=1e3;function xe(t){let e=t.message.toLowerCase();return["timeout","navigation failed","page crashed","target closed","element not found","is not visible","\u65E0\u6CD5\u627E\u5230","not find","cannot find"].some(r=>e.includes(r))}function Qe(t){let e=t.message.toLowerCase();return["permission","unauthorized","\u65E0\u6743\u8BBF\u95EE","cookie","\u767B\u5F55"].some(r=>e.includes(r))}async function Ze(t){console.log("\u9875\u9762\u72B6\u6001\u5F02\u5E38\u6216\u9047\u5230\u6743\u9650\u95EE\u9898\uFF0C\u5F00\u59CB\u91CD\u7F6E...");try{await t.reload({waitUntil:"networkidle",timeout:2e4}),console.log("\u9875\u9762\u5237\u65B0\u6210\u529F\u3002")}catch(e){console.warn("\u9875\u9762\u5237\u65B0\u5931\u8D25\uFF0C\u5C1D\u8BD5\u91CD\u65B0\u5BFC\u822A:",e.message);try{await A(t,c.aiStudio.url,{timeout:c.aiStudio.pageTimeout}),console.log("\u91CD\u65B0\u5BFC\u822A\u6210\u529F\u3002")}catch(o){throw console.error("\u9875\u9762\u91CD\u7F6E\u5931\u8D25\uFF1A\u5237\u65B0\u548C\u91CD\u65B0\u5BFC\u822A\u5747\u544A\u5931\u8D25\u3002",o),new Error("Failed to reset page state.")}}}async function Pe(t,e,o){let r=null,i=null;try{r=await G();for(let a=1;a<=j;a++)try{console.log(`[\u5C1D\u8BD5 ${a}/${j}] \u5F00\u59CB\u5904\u7406\u8BF7\u6C42...`),(a===1||!r.url().includes("aistudio.google.com"))&&await A(r,c.aiStudio.url,{timeout:c.aiStudio.pageTimeout});let s=await o(r,t,e);return await O(r),s}catch(s){if(i=s,console.warn(`[\u5C1D\u8BD5 ${a}/${j}] \u5931\u8D25: ${s.message}`),(Qe(s)||xe(s))&&a<j)console.log(`\u68C0\u6D4B\u5230\u53EF\u91CD\u8BD5\u7684\u9519\u8BEF\uFF08\u6743\u9650\u6216\u9875\u9762\u72B6\u6001\uFF09\uFF0C\u5C06\u5728 ${Ce}ms \u540E\u91CD\u8BD5...`),await Ze(r),await new Promise(h=>setTimeout(h,Ce));else throw console.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\u6216\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u5C06\u629B\u51FA\u5F02\u5E38\u3002"),s}}catch(a){throw console.error("\u5904\u7406 AI Studio \u8BF7\u6C42\u6700\u7EC8\u5931\u8D25:",a),r&&(xe(a)&&(r._needsRemoval=!0),await O(r)),i||a}}async function $e(t,e,o={}){let r=o.model||c.api.defaultModel;try{await Pe(t,o,async(i,a,s)=>new Promise(async(h,d)=>{let l=!1,p="",f=new Set,u=w=>{l||(l=!0,ue(i).catch(console.error),w?d(w):h())},m=w=>{if(l)return;p+=w;let y=V(p);if(y?.permissionError)return u(new Error(y.content));if(Array.isArray(y)&&y.length>0)for(let S of y){let E=`${S.type}::${S.content}`;S.content?.trim()&&!f.has(E)&&(e.enqueue(`data: ${JSON.stringify(be(S.content,S.type,r))}
15
 
16
- `),f.add(E))}},C=()=>{l||(console.log("\u6D41\u5DF2\u7ED3\u675F\uFF0C\u53D1\u9001 [DONE] \u4FE1\u53F7\u3002"),e.enqueue(`data: [DONE]
17
 
18
- `),e.close(),u())};try{await le(i,m,C),await ce(i),await new L(i).processMessage(a,s),setTimeout(()=>{l||u(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},c.aiStudio.responseTimeout)}catch(w){u(w)}}))}catch(i){if(e.desiredSize!==null)try{e.enqueue(`data: ${JSON.stringify(Y(i.message,r))}
19
 
20
  `),e.enqueue(`data: [DONE]
21
 
22
- `),e.close()}catch(a){console.error("\u5173\u95ED\u6D41\u63A7\u5236\u5668\u65F6\u51FA\u9519:",a)}}}async function ve(t,e={}){let o=e.model||c.api.defaultModel;try{return await Pe(t,e,async(r,i,a)=>new Promise(async(s,h)=>{let d="",l=async p=>{if(p.url().includes("GenerateContent"))try{let f=await p.text(),u=V(f);if(u?.permissionError)return h(new Error(u.content));Array.isArray(u)&&(d+=u.filter(m=>m.type==="text").map(m=>m.content).join("")),r.removeListener("response",l),s(Ee(d,o))}catch(f){h(f)}};r.on("response",l);try{await new L(r).processMessage(i,a),setTimeout(()=>{r.removeListener("response",l),h(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},c.aiStudio.responseTimeout)}catch(p){r.removeListener("response",l),h(p)}}))}catch(r){return Y(r.message,o)}}async function Te(t){try{Se(t);let e=await et(t),{prompt:o,stream:r,model:i,temperature:a}=ye(e);return r?(we(t),new ReadableStream({start(h){$e(o,h,{model:i,temperature:a})}})):await ve(o,{model:i,temperature:a})}catch(e){throw console.error("\u5904\u7406\u804A\u5929\u8BF7\u6C42\u65F6\u51FA\u9519:",e),e.statusCode?e:tt({statusCode:500,statusMessage:e.message||"An internal server error occurred."})}}import{createError as B}from"h3";async function Me(t){try{let e=Object.values(c.models).map(o=>({id:o.id,object:o.object,created:o.created,owned_by:o.owned_by,permission:o.permission,root:o.root,parent:o.parent}));return e.sort((o,r)=>r.created-o.created),{object:"list",data:e}}catch(e){throw console.error("\u83B7\u53D6\u6A21\u578B\u5217\u8868\u65F6\u51FA\u9519:",e),B({statusCode:500,statusMessage:"Failed to retrieve models list."})}}async function Ie(t){try{let e=t.context.params?.model;if(!e)throw B({statusCode:400,statusMessage:"Model ID is required."});let o=c.models[e];if(!o)throw B({statusCode:404,statusMessage:`Model '${e}' not found.`});return{id:o.id,object:o.object,created:o.created,owned_by:o.owned_by,permission:o.permission,root:o.root,parent:o.parent}}catch(e){throw console.error(`\u83B7\u53D6\u6A21\u578B '${t.context.params?.model}' \u4FE1\u606F\u65F6\u51FA\u9519:`,e),e.statusCode?e:B({statusCode:500,statusMessage:"Failed to retrieve model information."})}}F();k();var P=new ot,Ne=process.cwd();me();P.use("*",fe);P.get("/health",ge);P.get("/v1/models",Me);P.get("/v1/models/:model",Ie);P.post("/v1/chat/completions",Te);P.get("/screenshots/**",t=>{let e=t.path.substring(12),o=Oe(Ne,"screenshots",e);return ke(t,{getContents:()=>Ae(o),getMeta:async()=>{let r=await Re(o).catch(()=>{});if(r?.isFile())return{size:r.size,mtime:r.mtimeMs}}})});P.get("/**",t=>{let e=t.path==="/"?"index.html":t.path,o=Oe(Ne,"public",e);return ke(t,{getContents:()=>Ae(o),getMeta:async()=>{let r=await Re(o).catch(()=>{});if(r?.isFile())return{size:r.size,mtime:r.mtimeMs}}})});n("\u{1F527} \u521D\u59CB\u5316\u9875\u9762\u6C60...");ne(5);process.env.NODE_ENV!=="production"&&(n("\u{1F4CA} \u542F\u52A8\u9875\u9762\u6C60\u76D1\u63A7..."),pe(1e4));var H=c.server.port,D=c.server.host;rt(P,{port:H,host:D});n(`\u{1F680} \u670D\u52A1\u5668\u8FD0\u884C\u5728 http://${D}:${H}`);n(`\u{1F3E0} \u7BA1\u7406\u9762\u677F: http://${D}:${H}/`);n(`\u{1F4CB} \u5065\u5EB7\u68C0\u67E5: http://${D}:${H}/health`);n(`\u{1F4AC} \u804A\u5929\u7AEF\u70B9: http://${D}:${H}/v1/chat/completions`);n(`\u{1F3AF} AI Studio URL: ${c.aiStudio.url}`);n(`\u{1F30D} \u73AF\u5883: ${process.env.NODE_ENV||"development"}`);async function nt(){let t;try{n("\u{1F4F8} \u5F00\u59CB\u83B7\u53D6AI Studio\u9875\u9762\u622A\u56FE..."),t=await G(),n(`\u{1F310} \u667A\u80FD\u5BFC\u822A\u5230: ${c.aiStudio.url}`),await A(t,c.aiStudio.url,{timeout:c.aiStudio.pageTimeout}),await U(t),await t.waitForTimeout(2e3);let e=await X(t,"./screenshots","aistudio-startup");n(`\u2705 AI Studio\u622A\u56FE\u5DF2\u4FDD\u5B58: ${e}`)}catch(e){T("\u274C \u622A\u56FEAI Studio\u9875\u9762\u65F6\u51FA\u9519:",e.message)}finally{t&&(await O(t),n("\u{1F504} \u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D"))}}setTimeout(()=>{n(`
23
- \u{1F4CA} \u521D\u59CB\u9875\u9762\u6C60\u72B6\u6001:`),he()},1e3);setTimeout(()=>{nt()},2e3);
 
1
+ var Ae=Object.defineProperty;var Q=(t,e)=>()=>(t&&(e=t(t=0)),e);var Oe=(t,e)=>{for(var o in e)Ae(t,o,{get:e[o],enumerable:!0})};import G from"node:fs";function De(){G.existsSync(T.logDir)||G.mkdirSync(T.logDir,{recursive:!0})}function He(...t){return t.map(e=>typeof e=="object"&&e!==null?JSON.stringify(e,null,2):String(e)).join(" ")}async function Fe(t,e){if(!T.enableFile)return;De();let r=`[${new Date().toISOString()}] [${t}] ${e}
2
+ `;try{await G.promises.appendFile(T.logFile,r)}catch(i){console.error("\u5199\u5165\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25:",i)}}function qe(t,...e){if(!T.enableConsole)return;let o={[x.DEBUG]:console.debug,[x.INFO]:console.log,[x.WARN]:console.warn,[x.ERROR]:console.error}[t]||console.log,r=new Date().toLocaleTimeString();o(`[${r}] [${t}]`,...e)}function Z(t,...e){let o=He(...e);qe(t,...e),Fe(t,o)}var x,T,s,v,I=Q(()=>{x={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},T={logFile:"./logs/app.log",logDir:"./logs",enableConsole:!0,enableFile:!0,logLevel:process.env.LOG_LEVEL||x.INFO};s=(...t)=>Z(x.INFO,...t),v=(...t)=>Z(x.ERROR,...t)});var oe={};Oe(oe,{checkCookieAvailability:()=>je,ensureDirectoryExists:()=>te,getHumanReadableTimestamp:()=>ee,loadCookies:()=>B,saveScreenshot:()=>W,waitForUserInput:()=>Ge});import M from"node:fs";import ze from"node:path";import Ue from"node:readline";function ee(){return new Date().toISOString().replace(/T/,"_").replace(/:/g,"-").replace(/\..+/,"")}function te(t){M.existsSync(t)||(M.mkdirSync(t,{recursive:!0}),s(`\u5DF2\u521B\u5EFA\u76EE\u5F55: ${t}`))}function je(t,e){if(e)try{return JSON.parse(e),s("\u53D1\u73B0\u5E76\u9A8C\u8BC1\u4E86\u73AF\u5883\u53D8\u91CF\u4E2D\u7684 COOKIES\u3002"),!0}catch(o){v("\u73AF\u5883\u53D8\u91CF COOKIES \u683C\u5F0F\u65E0\u6548 (\u5FC5\u987B\u662F JSON \u6570\u7EC4\u5B57\u7B26\u4E32):",o.message)}return M.existsSync(t)?(s(`\u53D1\u73B0 Cookie \u6587\u4EF6: ${t}`),!0):(v(`Cookie \u6587\u4EF6\u4E0D\u5B58\u5728: ${t}\uFF0C\u4E14\u672A\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002`),s("\u8BF7\u5148\u8FD0\u884C `npm run login` \u6216\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002"),!1)}function B(t,e){try{if(e)return s("\u4ECE\u73AF\u5883\u53D8\u91CF COOKIES \u52A0\u8F7D Cookie..."),JSON.parse(e);if(M.existsSync(t))return s(`\u4ECE\u6587\u4EF6\u52A0\u8F7D Cookie: ${t}`),JSON.parse(M.readFileSync(t,"utf8"))}catch(o){throw v("\u52A0\u8F7D Cookie \u5931\u8D25:",o),new Error("\u65E0\u6CD5\u52A0\u8F7D\u6216\u89E3\u6790 Cookie\u3002")}return[]}async function W(t,e,o="screenshot"){te(e);let r=ee(),i=ze.join(e,`${o}_${r}.png`);return await t.screenshot({path:i,fullPage:!0}),s(`\u622A\u56FE\u5DF2\u4FDD\u5B58: ${i}`),i}function Ge(){let t=Ue.createInterface({input:process.stdin,output:process.stdout});return new Promise(e=>{t.question("",()=>{t.close(),e()})})}var D=Q(()=>{I()});import{H3 as Ze,serve as et,serveStatic as _e}from"h3";import{stat as Te,readFile as Me}from"node:fs/promises";import{join as ke}from"node:path";import{chromium as Be}from"playwright";import Ne from"dotenv";Ne.config();var Le={server:{port:parseInt(process.env.PORT||"3096",10),host:process.env.HOST||"localhost"},browser:{headless:(process.env.HEADLESS||"true").toLowerCase()!=="false",timeout:parseInt(process.env.TIMEOUT||"30000",10),executablePath:process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,args:["--disable-blink-features=AutomationControlled","--no-sandbox","--disable-dev-shm-usage","--disable-infobars","--disable-extensions"],userAgent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},cookieFile:"./cookies.json",cookiesFromEnv:process.env.COOKIES,screenshotDir:"./screenshots",aiStudio:{url:process.env.AI_STUDIO_URL||"https://aistudio.google.com/prompts/new_chat",responseTimeout:parseInt(process.env.RESPONSE_TIMEOUT||"600000",10),pageTimeout:parseInt(process.env.PAGE_TIMEOUT||"30000",10)},api:{defaultModel:process.env.DEFAULT_MODEL||"gemini-pro",maxTokens:65536,temperature:1,token:process.env.API_TOKEN},models:{"gemini-2.5-pro":{displayName:"Gemini 2.5 Pro",id:"gemini-2.5-pro",object:"model",created:1704067200,owned_by:"google",permission:[],root:"gemini-2.5-pro",parent:null},"gemini-2.5-flash":{displayName:"Gemini 2.5 Flash",id:"gemini-2.5-flash",object:"model",created:1704067200,owned_by:"google",permission:[],root:"gemini-2.5-flash",parent:null},"gemini-pro":{displayName:"Gemini Pro",id:"gemini-pro",object:"model",created:1701388800,owned_by:"google",permission:[],root:"gemini-pro",parent:null},"gemini-flash":{displayName:"Gemini Flash",id:"gemini-flash",object:"model",created:1701388800,owned_by:"google",permission:[],root:"gemini-flash",parent:null}},debug:{logRequests:process.env.DEBUG_REQUESTS==="true",logResponses:process.env.DEBUG_RESPONSES==="true",saveScreenshots:process.env.SAVE_SCREENSHOTS==="true"}},l=Le;D();I();var $=null,C=null,H=class{constructor(e=5){this.maxSize=e,this.availablePages=[],this.busyPages=new Set,this.totalPages=0}async getPage(){if(this.availablePages.length>0){let e=this.availablePages.pop();return this.busyPages.add(e),s(`\u4ECE\u9875\u9762\u6C60\u83B7\u53D6\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),e}if(this.totalPages<this.maxSize){let{context:e}=await We(),o=await e.newPage();return this.busyPages.add(o),this.totalPages++,s(`\u521B\u5EFA\u65B0\u9875\u9762\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}\uFF0C\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),o}return s("\u9875\u9762\u6C60\u5DF2\u6EE1\uFF0C\u7B49\u5F85\u9875\u9762\u91CA\u653E..."),new Promise(e=>{let o=()=>{if(this.availablePages.length>0){let r=this.availablePages.pop();this.busyPages.add(r),s(`\u7B49\u5F85\u540E\u83B7\u53D6\u5230\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),e(r)}else setTimeout(o,100)};o()})}async releasePage(e){if(!this.busyPages.has(e)){s("\u5C1D\u8BD5\u91CA\u653E\u4E0D\u5728\u5FD9\u788C\u5217\u8868\u4E2D\u7684\u9875\u9762");return}if(e._needsRemoval){s("\u9875\u9762\u88AB\u6807\u8BB0\u4E3A\u9700\u8981\u79FB\u9664\uFF0C\u5C06\u4ECE\u6C60\u4E2D\u79FB\u9664"),await this.removePage(e);return}try{await this.cleanupPage(e),this.busyPages.delete(e),this.availablePages.push(e),s(`\u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D\uFF0C\u53EF\u7528\u9875\u9762\u6570: ${this.availablePages.length}\uFF0C\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`)}catch(o){s(`\u6E05\u7406\u9875\u9762\u65F6\u51FA\u9519\uFF0C\u5C06\u5173\u95ED\u8BE5\u9875\u9762: ${o.message}`),await this.removePage(e)}}async cleanupPage(e){try{e.removeAllListeners();try{await e.evaluate(()=>{Object.keys(window).forEach(r=>{(r.startsWith("__handleStreamChunk")||r.startsWith("__onStreamChunk")||r.startsWith("__onStreamEnd"))&&delete window[r]}),window.__streamInterceptor&&(typeof window.__streamInterceptor.deactivate=="function"&&window.__streamInterceptor.deactivate(),delete window.__streamInterceptor),delete window.__handleStreamChunk,delete window.__onStreamChunk,delete window.__onStreamEnd,delete window.__streamCallbacks})}catch(o){s(`\u6E05\u7406\u9875\u9762\u72B6\u6001\u65F6\u51FA\u73B0evaluate\u9519\u8BEF: ${o.message}`)}s("\u9875\u9762\u72B6\u6001\u5DF2\u6E05\u7406")}catch(o){throw new Error(`\u6E05\u7406\u9875\u9762\u5931\u8D25: ${o.message}`)}}async removePage(e){try{this.busyPages.delete(e);let o=this.availablePages.indexOf(e);o>-1&&this.availablePages.splice(o,1),await e.close(),this.totalPages--,s(`\u9875\u9762\u5DF2\u4ECE\u6C60\u4E2D\u79FB\u9664\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}`)}catch(o){s(`\u5173\u95ED\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}}async cleanup(){s("\u5F00\u59CB\u6E05\u7406\u9875\u9762\u6C60...");for(let e of this.busyPages)try{await e.close()}catch(o){s(`\u5173\u95ED\u5FD9\u788C\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}for(let e of this.availablePages)try{await e.close()}catch(o){s(`\u5173\u95ED\u53EF\u7528\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}this.busyPages.clear(),this.availablePages=[],this.totalPages=0,s("\u9875\u9762\u6C60\u6E05\u7406\u5B8C\u6210")}getStatus(){return{total:this.totalPages,available:this.availablePages.length,busy:this.busyPages.size,maxSize:this.maxSize}}},S=null;async function We(){if(!$){$=await Be.launch({headless:l.browser.headless,timeout:l.browser.timeout,args:l.browser.args,executablePath:l.browser.executablePath}),C=await $.newContext({userAgent:l.browser.userAgent});let t=B(l.cookieFile,l.cookiesFromEnv);await C.addCookies(t)}return{browser:$,context:C}}function se(t=5){return S||(S=new H(t),s(`\u9875\u9762\u6C60\u5DF2\u521D\u59CB\u5316\uFF0C\u6700\u5927\u9875\u9762\u6570: ${t}`)),S}function ae(){return S||(S=new H,s("\u9875\u9762\u6C60\u5DF2\u81EA\u52A8\u521D\u59CB\u5316\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E")),S}async function F(){let e=await ae().getPage();return await e.bringToFront(),e}async function k(t,e,o={}){let r=t.url();console.log("\u5F53\u524D\u9875\u9762URL:",r),console.log("\u76EE\u6807URL:",e);try{return r!==e?(console.log("\u9875\u9762URL\u4E0D\u5339\u914D\uFF0C\u9700\u8981\u5BFC\u822A..."),await t.goto(e,{waitUntil:"load",timeout:3e4,...o}),console.log("\u9875\u9762\u5BFC\u822A\u5B8C\u6210"),!0):(console.log("\u9875\u9762\u5DF2\u5728\u76EE\u6807URL\uFF0C\u8FDB\u884C\u5237\u65B0\u4EE5\u786E\u4FDD\u6700\u65B0\u72B6\u6001..."),await t.bringToFront(),await t.reload({waitUntil:"load",timeout:3e4,...o}),console.log("\u9875\u9762\u5237\u65B0\u5B8C\u6210"),!0)}catch{}return!1}async function R(t){await ae().releasePage(t)}function A(){return S?S.getStatus():{total:0,available:0,busy:0,maxSize:0}}async function re(){S&&(await S.cleanup(),S=null),C&&(await C.close(),C=null),$&&(await $.close(),$=null)}async function ne(t,e={}){let{minClicks:o=1,maxClicks:r=3,minDelay:i=300,maxDelay:a=500,referenceElement:n=null}=e;try{s("\u5F00\u59CB\u6A21\u62DF\u4EBA\u7C7B\u968F\u673A\u70B9\u51FB\u884C\u4E3A...");let d=Math.floor(Math.random()*(r-o+1))+o;s(`\u5C06\u8FDB\u884C ${d} \u6B21\u968F\u673A\u70B9\u51FB`);let u=null;if(n)try{let c=await n.boundingBox();c&&(u={x:c.x-50,y:Math.max(0,c.y-200),width:c.width+50,height:300},s(`\u4F7F\u7528\u8F93\u5165\u6846\u9644\u8FD1\u7684\u5B89\u5168\u533A\u57DF: x=${u.x}, y=${u.y}, w=${u.width}, h=${u.height}`))}catch(c){s(`\u83B7\u53D6\u53C2\u8003\u5143\u7D20\u4F4D\u7F6E\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: ${c.message}`)}if(!u){let c=t.viewportSize(),m=c?.width||1280,h=c?.height||720;u={x:m*.3,y:h*.3,width:m*.4,height:h*.2},s(`\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: x=${u.x}, y=${u.y}, w=${u.width}, h=${u.height}`)}for(let c=0;c<d;c++)try{let m=Math.floor(Math.random()*u.width)+u.x,h=Math.floor(Math.random()*u.height)+u.y;s(`\u7B2C ${c+1} \u6B21\u5B89\u5168\u70B9\u51FB: (${m}, ${h})`);let f=await t.locator("*").first().evaluate((p,y)=>{let w=document.elementFromPoint(y.x,y.y);if(!w)return{safe:!0};let g=w.tagName.toLowerCase(),b=w.hasAttribute("href"),E=w.hasAttribute("onclick")||w.onclick,_=g==="button"||w.type==="button",V=g==="a"||b,Y=["input","textarea","select"].includes(g);return{safe:!_&&!V&&!E&&!Y,tagName:g,hasHref:b,hasOnClick:E,isButton:_,isLink:V,isInput:Y}},{x:m,y:h});if(f.safe?(await t.mouse.move(m,h,{steps:Math.floor(Math.random()*10)+5}),await t.waitForTimeout(Math.floor(Math.random()*200)+100),await t.mouse.click(m,h),s(`\u5B89\u5168\u70B9\u51FB\u5B8C\u6210: (${m}, ${h})`)):s(`\u8DF3\u8FC7\u4E0D\u5B89\u5168\u7684\u70B9\u51FB\u4F4D\u7F6E (${m}, ${h}): ${f.tagName}`),c<d-1){let p=Math.floor(Math.random()*(a-i+1))+i;s(`\u7B49\u5F85 ${p}ms \u540E\u8FDB\u884C\u4E0B\u4E00\u6B21\u70B9\u51FB`),await t.waitForTimeout(p)}}catch(m){s(`\u7B2C ${c+1} \u6B21\u70B9\u51FB\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u6B21: ${m.message}`)}s("\u5B89\u5168\u968F\u673A\u70B9\u51FB\u6A21\u62DF\u5B8C\u6210")}catch(d){s(`\u6A21\u62DF\u5B89\u5168\u968F\u673A\u70B9\u51FB\u65F6\u51FA\u73B0\u9519\u8BEF: ${d.message}`)}}async function ie(t,e={}){let{includeScrolling:o=!0,includeMouseMovement:r=!0,includeRandomClicks:i=!0,duration:a=3e3}=e;try{s("\u5F00\u59CB\u6A21\u62DF\u590D\u6742\u7684\u4EBA\u7C7B\u884C\u4E3A...");let n=Date.now(),d=t.viewportSize(),u=d?.width||1280,c=d?.height||720;for(;Date.now()-n<a;){let m=Math.random();if(m<.3&&o){let f=Math.random()>.5?"down":"up",p=Math.floor(Math.random()*300)+100;s(`\u6A21\u62DF\u6EDA\u52A8: ${f}, \u8DDD\u79BB: ${p}px`),await t.mouse.wheel(0,f==="down"?p:-p)}else if(m<.6&&r){let f=Math.floor(Math.random()*u),p=Math.floor(Math.random()*c);s(`\u6A21\u62DF\u9F20\u6807\u79FB\u52A8\u5230: (${f}, ${p})`),await t.mouse.move(f,p,{steps:Math.floor(Math.random()*15)+5})}else if(m<.8&&i){let f=Math.floor(Math.random()*(u*.8))+u*.1,p=Math.floor(Math.random()*(c*.8))+c*.1;s(`\u6A21\u62DF\u968F\u673A\u70B9\u51FB: (${f}, ${p})`),await t.mouse.click(f,p)}let h=Math.floor(Math.random()*800)+200;await t.waitForTimeout(h)}s("\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u6A21\u62DF\u5B8C\u6210")}catch(n){s(`\u6A21\u62DF\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u65F6\u51FA\u73B0\u9519\u8BEF: ${n.message}`)}}async function q(t,e=5e3){try{s("\u68C0\u67E5\u662F\u5426\u6709\u6B22\u8FCE\u5BF9\u8BDD\u6846\u9700\u8981\u5173\u95ED...");let o="mat-dialog-container",r='button[mat-dialog-close][aria-label="close"]';if(await t.locator(o).first().isVisible({timeout:e})){s("\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846\uFF0C\u5C1D\u8BD5\u5173\u95ED...");let a=t.locator(r).first();return await a.isVisible({timeout:2e3})?(await a.click(),s("\u5DF2\u901A\u8FC7\u5173\u95ED\u6309\u94AE\u5173\u95ED\u6B22\u8FCE\u5BF9\u8BDD\u6846"),await t.waitForTimeout(1e3),!0):(s("\u672A\u627E\u5230\u5173\u95ED\u6309\u94AE\uFF0C\u5C1D\u8BD5\u6309ESC\u952E\u5173\u95ED\u5BF9\u8BDD\u6846"),await t.keyboard.press("Escape"),await t.waitForTimeout(1e3),!0)}else return s("\u672A\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846"),!1}catch(o){return s("\u5904\u7406\u6B22\u8FCE\u5BF9\u8BDD\u6846\u65F6\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u6267\u884C:",o.message),!1}}function ce(){process.on("SIGINT",async()=>{console.log("\u6B63\u5728\u6E05\u7406\u8D44\u6E90..."),await re(),process.exit(0)}),process.on("SIGTERM",async()=>{console.log("\u6B63\u5728\u6E05\u7406\u8D44\u6E90..."),await re(),process.exit(0)})}I();var le=null;function ue(t=1e4){if(le){s("\u9875\u9762\u6C60\u76D1\u63A7\u5DF2\u5728\u8FD0\u884C\u4E2D\u3002");return}s(`\u5F00\u59CB\u76D1\u63A7\u9875\u9762\u6C60\u72B6\u6001\uFF0C\u95F4\u9694: ${t}ms`),le=setInterval(()=>{let e=A(),o=new Date().toLocaleTimeString(),r=e.total>0?(e.busy/e.total*100).toFixed(1):0;s(`[${o}] \u9875\u9762\u6C60\u72B6\u6001: \u603B\u8BA1=${e.total}, \u53EF\u7528=${e.available}, \u5FD9\u788C=${e.busy}, \u4F7F\u7528\u7387=${r}%`)},t)}function me(){let t=A(),e=new Date().toLocaleString(),o=t.total>0?(t.busy/t.total*100).toFixed(1):0;console.log(`
3
  --- \u9875\u9762\u6C60\u72B6\u6001 @ ${e} ---
4
  \u603B\u9875\u9762\u6570: ${t.total}
5
  \u53EF\u7528\u9875\u9762\u6570: ${t.available}
 
7
  \u6700\u5927\u9875\u9762\u6570: ${t.maxSize}
8
  \u4F7F\u7528\u7387: ${o}%
9
  ------------------------------------
10
+ `)}function pe(t){let e=t.node.res.getHeaders();if(e["access-control-allow-origin"]||t.node.res.setHeader("Access-Control-Allow-Origin",process.env.CORS_ORIGIN||"*"),e["access-control-allow-methods"]||t.node.res.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),e["access-control-allow-headers"]||t.node.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),e["access-control-max-age"]||t.node.res.setHeader("Access-Control-Max-Age","86400"),t.node.req.method==="OPTIONS")return t.node.res.statusCode=204,t.node.res.end()}function de(t){t.node.res.setHeader("Content-Type","text/event-stream"),t.node.res.setHeader("Cache-Control","no-cache"),t.node.res.setHeader("Connection","keep-alive"),t.node.res.setHeader("Access-Control-Allow-Origin",process.env.CORS_ORIGIN||"*"),t.node.res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization")}function he(t){let e=A(),o=e.total>0?Math.round(e.busy/e.total*100):0;return{status:"ok",timestamp:new Date().toISOString(),version:process.env.npm_package_version||"1.0.0",pagePool:{...e,utilization:`${o}%`}}}import{readBody as Ye,createError as Qe}from"h3";import{createError as Ke}from"h3";function fe(t){let{messages:e,stream:o=!1,model:r=l.api.defaultModel,temperature:i=l.api.temperature}=t;if(!e||!Array.isArray(e)||e.length===0)throw Ke({statusCode:400,statusMessage:"Invalid request: `messages` must be a non-empty array."});return{prompt:e.map(n=>!n.role||!n.content?"":`${n.role}: ${n.content}`).join(`
11
 
12
+ `),stream:o,model:r,temperature:i,messages:e}}import{createError as K}from"h3";function ge(t){if(!l.api.token){process.env.NODE_ENV==="production"&&console.warn("\u8B66\u544A: API_TOKEN \u672A\u5728\u751F\u4EA7\u73AF\u5883\u4E2D\u914D\u7F6E\uFF0CAPI \u5BF9\u5916\u5F00\u653E\uFF01");return}let e=t.node.req.headers.authorization;if(!e)throw K({statusCode:401,statusMessage:"Unauthorized: Missing Authorization header."});let[o,r]=e.split(" ");if(o!=="Bearer"||!r)throw K({statusCode:401,statusMessage:"Unauthorized: Invalid Authorization header format. Expected: Bearer <token>."});if(r!==l.api.token)throw K({statusCode:401,statusMessage:"Unauthorized: Invalid API token."})}var O=class{constructor(e,o={}){this.page=e,this.options={enableHumanSimulation:!0,...o},this.modelMapping=Object.fromEntries(Object.entries(l.models).map(([r,i])=>[r,i.displayName]))}async waitForPageLoad(){try{return await this.page.waitForSelector("body",{timeout:15e3}),await q(this.page),!0}catch(e){return console.error("\u9875\u9762\u52A0\u8F7D\u8D85\u65F6\u6216\u5931\u8D25:",e),!1}}async findInputElement(){try{await this.page.waitForSelector("footer ms-prompt-input-wrapper",{timeout:1e4}),console.log("\u8F93\u5165\u6846\u7684\u7236\u5BB9\u5668\u5DF2\u52A0\u8F7D\u3002")}catch{console.warn("\u7B49\u5F85\u8F93\u5165\u6846\u7236\u5BB9\u5668\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u67E5\u627E...")}let e=['ms-prompt-input-wrapper textarea[aria-label*="prompt"]','textarea[placeholder="Start typing a prompt"]','textarea[aria-label="Start typing a prompt"]',"footer textarea",'textarea[placeholder*="prompt"]','textarea[aria-label*="prompt"]','div[contenteditable="true"]',"textarea"];for(let o of e)try{let r=this.page.locator(o),i=await r.count();if(i>0){console.log(`\u9009\u62E9\u5668 "${o}" \u627E\u5230\u4E86 ${i} \u4E2A\u5143\u7D20\u3002\u6B63\u5728\u68C0\u67E5\u53EF\u89C1\u6027\u548C\u53EF\u7528\u6027...`);for(let a=0;a<i;a++){let n=r.nth(a);if(await n.isVisible()&&await n.isEnabled())return console.log(`\u6210\u529F\u627E\u5230\u53EF\u7528\u8F93\u5165\u6846: ${o} (\u7D22\u5F15 ${a})`),n}console.log(`\u9009\u62E9\u5668 "${o}" \u627E\u5230\u7684\u5143\u7D20\u5747\u4E0D\u53EF\u89C1\u6216\u4E0D\u53EF\u7528\u3002`)}}catch(r){console.warn(`\u4F7F\u7528\u9009\u62E9\u5668 "${o}" \u67E5\u627E\u65F6\u51FA\u9519: ${r.message}`)}if(console.error("\u5173\u952E\u9519\u8BEF: \u5C1D\u8BD5\u4E86\u6240\u6709\u9009\u62E9\u5668\u540E\uFF0C\u4ECD\u672A\u627E\u5230\u4EFB\u4F55\u53EF\u7528\u7684\u8F93\u5165\u5143\u7D20\u3002"),l.debug.saveScreenshots){let{saveScreenshot:o}=await Promise.resolve().then(()=>(D(),oe));await o(this.page,l.screenshotDir,"find-input-failed")}return null}async findSendButton(){let e=['button[aria-label="Run"]',"button.run-button",'button[aria-label*="Send"]','button[data-testid*="send"]'];for(let o of e){let r=this.page.locator(o);if(await r.count()>0){let i=r.first();if(!await i.isDisabled())return i}}return console.error("\u672A\u627E\u5230\u4EFB\u4F55\u53EF\u7528\u7684\u53D1\u9001\u6309\u94AE\u3002"),null}async fillMessage(e){let o=await this.findInputElement();if(!o)throw new Error("\u65E0\u6CD5\u627E\u5230\u8F93\u5165\u6846\u3002");try{return this.options.enableHumanSimulation&&await ne(this.page,{referenceElement:o}),await o.fill(e),await this.page.waitForTimeout(200),console.log("\u6D88\u606F\u586B\u5145\u5B8C\u6210\u3002"),!0}catch(r){return console.error("\u586B\u5145\u6D88\u606F\u5931\u8D25:",r),!1}}async waitForSendButtonEnabled(e=1e4){try{return await this.page.locator('button[aria-label="Run"]:not([disabled]), button.run-button:not([disabled])').waitFor({state:"visible",timeout:e}),console.log("\u53D1\u9001\u6309\u94AE\u5DF2\u53EF\u7528\u3002"),!0}catch{return console.warn("\u7B49\u5F85\u53D1\u9001\u6309\u94AE\u53EF\u7528\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u3002"),!1}}async sendMessage(){this.options.enableHumanSimulation&&await ie(this.page,{includeScrolling:!1,duration:1500});let e=await this.findSendButton();if(!e)throw new Error("\u65E0\u6CD5\u627E\u5230\u53EF\u7528\u7684\u53D1\u9001\u6309\u94AE\u3002");try{return await e.click(),console.log("\u6D88\u606F\u5DF2\u53D1\u9001\u3002"),!0}catch(o){console.error("\u70B9\u51FB\u53D1\u9001\u6309\u94AE\u5931\u8D25:",o);try{return console.log("\u5C1D\u8BD5\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E (Ctrl+Enter) \u53D1\u9001..."),await this.page.keyboard.press("Control+Enter"),console.log("\u5DF2\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u3002"),!0}catch(r){return console.error("\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u4E5F\u5931\u8D25:",r),!1}}}async setModel(e){try{let o=this.modelMapping[e]||e,r=this.page.locator("ms-model-selector-two-column");if(await r.count()===0)return console.log("\u672A\u627E\u5230\u6A21\u578B\u9009\u62E9\u5668\uFF0C\u8DF3\u8FC7\u6A21\u578B\u8BBE\u7F6E\u3002"),!1;if((await r.locator(".model-option-content .gmat-body-medium").textContent())?.trim()===o)return console.log("\u5F53\u524D\u5DF2\u662F\u76EE\u6807\u6A21\u578B\uFF0C\u65E0\u9700\u5207\u6362\u3002"),!0;await r.click({timeout:5e3});let a=this.page.locator(".mat-mdc-select-panel");await a.waitFor({state:"visible",timeout:5e3});let n=a.locator("mat-option.model-option",{hasText:o});return await n.count()>0?(await n.first().click({timeout:5e3}),await this.page.waitForTimeout(1e3),console.log(`\u6A21\u578B\u5DF2\u6210\u529F\u8BBE\u7F6E\u4E3A: ${o}`),!0):(console.log(`\u672A\u5728\u4E0B\u62C9\u83DC\u5355\u4E2D\u627E\u5230\u76EE\u6807\u6A21\u578B: ${o}`),await this.page.keyboard.press("Escape"),!1)}catch(o){console.error("\u8BBE\u7F6E\u6A21\u578B\u65F6\u53D1\u751F\u9519\u8BEF:",o);try{await this.page.keyboard.press("Escape")}catch{}return!1}}async setTemperature(e){try{let o=this.page.locator('[data-test-id="temperatureSliderContainer"]');if(await o.count()===0)return console.log("\u672A\u627E\u5230\u6E29\u5EA6\u8BBE\u7F6E\u5BB9\u5668\uFF0C\u8DF3\u8FC7\u3002"),!1;let r=o.locator('input[type="number"]');return await r.count()>0?(await r.fill(e.toString()),await r.dispatchEvent("change"),console.log(`\u6E29\u5EA6\u5DF2\u8BBE\u7F6E\u4E3A: ${e}`),!0):(console.log("\u672A\u627E\u5230\u6E29\u5EA6\u6570\u5B57\u8F93\u5165\u6846\uFF0C\u8DF3\u8FC7\u8BBE\u7F6E\u3002"),!1)}catch(o){return console.error("\u8BBE\u7F6E\u6E29\u5EA6\u65F6\u51FA\u9519:",o),!1}}async processMessage(e,o={}){if(console.log("\u5F00\u59CB\u5904\u7406\u6D88\u606F..."),!await this.waitForPageLoad())throw new Error("\u9875\u9762\u52A0\u8F7D\u5931\u8D25\u3002");if(o.model&&await this.setModel(o.model),o.temperature!==void 0&&await this.setTemperature(o.temperature),!await this.fillMessage(e))throw new Error("\u6D88\u606F\u586B\u5199\u5931\u8D25\u3002");if(await this.waitForSendButtonEnabled(),!await this.sendMessage())throw new Error("\u6D88\u606F\u53D1\u9001\u5931\u8D25\u3002");return console.log("\u6D88\u606F\u53D1\u9001\u6210\u529F\uFF0C\u7B49\u5F85\u7F51\u7EDC\u62E6\u622A\u83B7\u53D6\u54CD\u5E94\u3002"),!0}};I();var z=class{TARGET_URL_PATTERNS=["MakerSuiteService/GenerateContent"];constructor(e,o,r){this.page=e,this.onStreamChunk=o,this.onStreamEnd=r,this.uniqueId=`interceptor_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,this.chunkCallbackName=`__onStreamChunk_${this.uniqueId}`,this.endCallbackName=`__onStreamEnd_${this.uniqueId}`,this.isInjected=!1,this.isActive=!1}async _inject(){if(this.isInjected)return;s(`[Interceptor] \u6CE8\u5165\u6D41\u5F0F\u62E6\u622A\u811A\u672C (ID: ${this.uniqueId})...`),await this.page.exposeFunction(this.chunkCallbackName,this.onStreamChunk),await this.page.exposeFunction(this.endCallbackName,this.onStreamEnd);let e={TARGET_URL_PATTERNS:this.TARGET_URL_PATTERNS,chunkCallbackName:this.chunkCallbackName,endCallbackName:this.endCallbackName},o=this._getBrowserScript();await this.page.evaluate(o,e),this.isInjected=!0,s(`[Interceptor] \u811A\u672C\u6CE8\u5165\u548C\u56DE\u8C03\u8FDE\u63A5\u5DF2\u4E00\u6B21\u6027\u5B8C\u6210 (ID: ${this.uniqueId})`)}async activate(){this.isActive||(await this._inject(),s(`[Interceptor] \u6FC0\u6D3B\u62E6\u622A\u5668 (ID: ${this.uniqueId})...`),await this.page.evaluate(()=>{window.__streamInterceptor&&window.__streamInterceptor.activate()}),this.isActive=!0,s(`[Interceptor] \u62E6\u622A\u5668\u5DF2\u6FC0\u6D3B (ID: ${this.uniqueId})`))}async deactivate(){if(this.isActive){s(`[Interceptor] \u505C\u7528\u62E6\u622A\u5668 (ID: ${this.uniqueId})...`);try{await this.page.evaluate(()=>{window.__streamInterceptor&&window.__streamInterceptor.deactivate()}),this.isActive=!1,s(`[Interceptor] \u62E6\u622A\u5668\u5DF2\u505C\u7528 (ID: ${this.uniqueId})`)}catch(e){s(`[Interceptor] \u505C\u7528\u65F6\u53D1\u751F\u9519\u8BEF (\u53EF\u80FD\u9875\u9762\u5DF2\u5173\u95ED): ${e.message}`)}}}_getBrowserScript(){return e=>{window.__streamInterceptor&&typeof window.__streamInterceptor.deactivate=="function"&&window.__streamInterceptor.deactivate();let{TARGET_URL_PATTERNS:o,chunkCallbackName:r,endCallbackName:i}=e,a=window.XMLHttpRequest.prototype.open,n=window.XMLHttpRequest.prototype.send,d=window[r],u=window[i];console.log(`[Interceptor] \u56DE\u8C03\u5DF2\u5728\u6CE8\u5165\u65F6\u76F4\u63A5\u83B7\u53D6: ${r}, ${i}`);let c=!1;window.__streamInterceptor={activate:()=>{c||(console.log("\u{1F3AF} [Interceptor] \u6FC0\u6D3B XHR \u8865\u4E01..."),c=!0,window.XMLHttpRequest.prototype.open=function(m,h,...f){return this._url=h,a.apply(this,[m,h,...f])},window.XMLHttpRequest.prototype.send=function(...m){let h=this._url?this._url.toString():"";if(o.some(p=>h.includes(p))&&c){console.log("\u{1F3AF} [Interceptor] \u62E6\u622A\u5230\u76EE\u6807\u8BF7\u6C42:",h);let p=0,y=!1,w=()=>{if(y)return;y=!0,console.log("\u{1F3C1} [Interceptor] \u5224\u5B9A\u6D41\u5DF2\u7ED3\u675F\uFF0C\u6B63\u5728\u89E6\u53D1\u6700\u7EC8\u56DE\u8C03...");let g=this.responseText.slice(p);g&&d&&d(g),u&&u()};this.addEventListener("progress",()=>{if(y)return;let g=this.responseText.slice(p);g&&(d&&d(g),p=this.responseText.length)}),this.addEventListener("readystatechange",()=>{this.readyState===4&&!y&&(console.log(`[Interceptor] \u8BF7\u6C42\u5B8C\u6210 (readyState=4), HTTP\u72B6\u6001: ${this.status}`),w())}),this.addEventListener("error",g=>{console.error("[Interceptor] XHR \u8BF7\u6C42\u51FA\u9519:",g),y||w()}),this.addEventListener("abort",()=>{console.warn("[Interceptor] XHR \u8BF7\u6C42\u88AB\u4E2D\u6B62"),y||w()})}return n.apply(this,m)})},deactivate:()=>{c&&(console.log("\u{1F504} [Interceptor] \u505C\u7528 XHR \u8865\u4E01..."),window.XMLHttpRequest.prototype.open=a,window.XMLHttpRequest.prototype.send=n,c=!1)}}}}};function Xe(t){return t.includes("The caller does not have permission")?(console.warn("\u68C0\u6D4B\u5230\u6743\u9650\u9519\u8BEF\uFF0C\u5C06\u89E6\u53D1\u91CD\u8BD5\u673A\u5236\u3002"),{permissionError:!0,content:"\u65E0\u6743\u8BBF\u95EE AI Studio\u3002\u8BF7\u68C0\u67E5 Cookie \u6216\u767B\u5F55\u72B6\u6001\u3002"}):null}function we(t){let e=[];if(!t)return e;if(Array.isArray(t)){if(t.length>=2&&t[0]===null&&typeof t[1]=="string"&&t[1]&&t[1]!=="model"){let o=t.length>2?"thinking":"text";e.push({type:o,content:t[1].replace(/\\n/g,`
13
+ `).replace(/\\"/g,'"')})}for(let o of t)e.push(...we(o))}return e}function X(t){let e=Xe(t);if(e)return e;try{let a=t.trim().replace(/\n/g,",").replace(/,+/g,",");a.endsWith(",")&&(a=a.slice(0,-1)),a.startsWith("[")||(a="["+a),a.endsWith("]")||(a=a+"]"),a=a.replace(/,]/g,"]").replace(/\[,/g,"[");let n=JSON.parse(a),d=we(n);if(d.length>0){let u=!1;return d.map(c=>(u?c.type="text":c.type==="text"&&(u=!0),c))}}catch{}let o=/\[null,\s*"((?:\\"|[^"])*)"/g,r=[],i;for(;(i=o.exec(t))!==null;)try{let a=i[1].replace(/\\n/g,`
14
+ `).replace(/\\"/g,'"');if(a&&a!=="model"){let n=a.trim().startsWith("**")?"thinking":"text";r.push({type:n,content:a})}}catch{}if(r.length>0){let a=!1;return r.map(n=>(a?n.type="text":n.type==="text"&&(a=!0),n))}return null}function ye(t,e,o="gemini-pro"){return{id:`chatcmpl-${Date.now()}`,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:o,choices:[{index:0,delta:{content:t||"",type:e||"text"},logprobs:null,finish_reason:null}]}}function J(t,e="gemini-pro"){return{object:"error",message:t,type:"invalid_request_error",model:e}}function Se(t,e="gemini-pro"){return{id:`chatcmpl-${Date.now()}`,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}],usage:{prompt_tokens:0,completion_tokens:0,total_tokens:0}}}var U=3,be=1e3;function Ee(t){let e=t.message.toLowerCase();return["timeout","navigation failed","page crashed","target closed","element not found","is not visible","\u65E0\u6CD5\u627E\u5230","not find","cannot find"].some(r=>e.includes(r))}function Je(t){let e=t.message.toLowerCase();return["permission","unauthorized","\u65E0\u6743\u8BBF\u95EE","cookie","\u767B\u5F55"].some(r=>e.includes(r))}async function Ve(t){console.log("\u9875\u9762\u72B6\u6001\u5F02\u5E38\u6216\u9047\u5230\u6743\u9650\u95EE\u9898\uFF0C\u5F00\u59CB\u91CD\u7F6E...");try{await t.reload({waitUntil:"networkidle",timeout:2e4}),console.log("\u9875\u9762\u5237\u65B0\u6210\u529F\u3002")}catch(e){console.warn("\u9875\u9762\u5237\u65B0\u5931\u8D25\uFF0C\u5C1D\u8BD5\u91CD\u65B0\u5BFC\u822A:",e.message);try{await k(t,l.aiStudio.url,{timeout:l.aiStudio.pageTimeout}),console.log("\u91CD\u65B0\u5BFC\u822A\u6210\u529F\u3002")}catch(o){throw console.error("\u9875\u9762\u91CD\u7F6E\u5931\u8D25\uFF1A\u5237\u65B0\u548C\u91CD\u65B0\u5BFC\u822A\u5747\u544A\u5931\u8D25\u3002",o),new Error("Failed to reset page state.")}}}async function Pe(t,e,o){let r=null,i=null;try{r=await F();for(let a=1;a<=U;a++)try{console.log(`[\u5C1D\u8BD5 ${a}/${U}] \u5F00\u59CB\u5904\u7406\u8BF7\u6C42...`),(a===1||!r.url().includes("aistudio.google.com"))&&await k(r,l.aiStudio.url,{timeout:l.aiStudio.pageTimeout});let n=await o(r,t,e);return await R(r),n}catch(n){if(i=n,console.warn(`[\u5C1D\u8BD5 ${a}/${U}] \u5931\u8D25: ${n.message}`),(Je(n)||Ee(n))&&a<U)console.log(`\u68C0\u6D4B\u5230\u53EF\u91CD\u8BD5\u7684\u9519\u8BEF\uFF08\u6743\u9650\u6216\u9875\u9762\u72B6\u6001\uFF09\uFF0C\u5C06\u5728 ${be}ms \u540E\u91CD\u8BD5...`),await Ve(r),await new Promise(d=>setTimeout(d,be));else throw console.error("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\u6216\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u5C06\u629B\u51FA\u5F02\u5E38\u3002"),n}}catch(a){throw console.error("\u5904\u7406 AI Studio \u8BF7\u6C42\u6700\u7EC8\u5931\u8D25:",a),r&&(Ee(a)&&(r._needsRemoval=!0),await R(r)),i||a}}async function xe(t,e,o={}){let r=o.model||l.api.defaultModel;try{await Pe(t,o,async(i,a,n)=>new Promise(async(d,u)=>{let c=!1,m="",h=new Set,f=null,p=g=>{c||(c=!0,f&&f.deactivate().catch(console.error),g?u(g):d())},y=g=>{if(c)return;m+=g;let b=X(m);if(b?.permissionError)return p(new Error(b.content));if(Array.isArray(b)&&b.length>0)for(let E of b){let _=`${E.type}::${E.content}`;E.content?.trim()&&!h.has(_)&&(e.enqueue(`data: ${JSON.stringify(ye(E.content,E.type,r))}
15
 
16
+ `),h.add(_))}},w=()=>{c||(console.log("\u6D41\u5DF2\u7ED3\u675F\uFF0C\u53D1\u9001 [DONE] \u4FE1\u53F7\u3002"),e.enqueue(`data: [DONE]
17
 
18
+ `),e.close(),p())};try{f=new z(i,y,w),await f.activate(),await new O(i).processMessage(a,n),setTimeout(()=>{c||p(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},l.aiStudio.responseTimeout)}catch(g){p(g)}}))}catch(i){if(e.desiredSize!==null)try{e.enqueue(`data: ${JSON.stringify(J(i.message,r))}
19
 
20
  `),e.enqueue(`data: [DONE]
21
 
22
+ `),e.close()}catch(a){console.error("\u5173\u95ED\u6D41\u63A7\u5236\u5668\u65F6\u51FA\u9519:",a)}}}async function $e(t,e={}){let o=e.model||l.api.defaultModel;try{return await Pe(t,e,async(r,i,a)=>new Promise(async(n,d)=>{let u="",c=async m=>{if(m.url().includes("GenerateContent"))try{let h=await m.text(),f=X(h);if(f?.permissionError)return d(new Error(f.content));Array.isArray(f)&&(u+=f.filter(p=>p.type==="text").map(p=>p.content).join("")),r.removeListener("response",c),n(Se(u,o))}catch(h){d(h)}};r.on("response",c);try{await new O(r).processMessage(i,a),setTimeout(()=>{r.removeListener("response",c),d(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},l.aiStudio.responseTimeout)}catch(m){r.removeListener("response",c),d(m)}}))}catch(r){return J(r.message,o)}}async function ve(t){try{ge(t);let e=await Ye(t),{prompt:o,stream:r,model:i,temperature:a}=fe(e);return r?(de(t),new ReadableStream({start(d){xe(o,d,{model:i,temperature:a})}})):await $e(o,{model:i,temperature:a})}catch(e){throw console.error("\u5904\u7406\u804A\u5929\u8BF7\u6C42\u65F6\u51FA\u9519:",e),e.statusCode?e:Qe({statusCode:500,statusMessage:e.message||"An internal server error occurred."})}}import{createError as j}from"h3";async function Ie(t){try{let e=Object.values(l.models).map(o=>({id:o.id,object:o.object,created:o.created,owned_by:o.owned_by,permission:o.permission,root:o.root,parent:o.parent}));return e.sort((o,r)=>r.created-o.created),{object:"list",data:e}}catch(e){throw console.error("\u83B7\u53D6\u6A21\u578B\u5217\u8868\u65F6\u51FA\u9519:",e),j({statusCode:500,statusMessage:"Failed to retrieve models list."})}}async function Ce(t){try{let e=t.context.params?.model;if(!e)throw j({statusCode:400,statusMessage:"Model ID is required."});let o=l.models[e];if(!o)throw j({statusCode:404,statusMessage:`Model '${e}' not found.`});return{id:o.id,object:o.object,created:o.created,owned_by:o.owned_by,permission:o.permission,root:o.root,parent:o.parent}}catch(e){throw console.error(`\u83B7\u53D6\u6A21\u578B '${t.context.params?.model}' \u4FE1\u606F\u65F6\u51FA\u9519:`,e),e.statusCode?e:j({statusCode:500,statusMessage:"Failed to retrieve model information."})}}D();I();var P=new Ze,Re=process.cwd();ce();P.use("*",pe);P.get("/health",he);P.get("/v1/models",Ie);P.get("/v1/models/:model",Ce);P.post("/v1/chat/completions",ve);P.get("/screenshots/**",t=>{let e=t.path.substring(12),o=ke(Re,"screenshots",e);return _e(t,{getContents:()=>Me(o),getMeta:async()=>{let r=await Te(o).catch(()=>{});if(r?.isFile())return{size:r.size,mtime:r.mtimeMs}}})});P.get("/**",t=>{let e=t.path==="/"?"index.html":t.path,o=ke(Re,"public",e);return _e(t,{getContents:()=>Me(o),getMeta:async()=>{let r=await Te(o).catch(()=>{});if(r?.isFile())return{size:r.size,mtime:r.mtimeMs}}})});s("\u{1F527} \u521D\u59CB\u5316\u9875\u9762\u6C60...");se(5);process.env.NODE_ENV!=="production"&&(s("\u{1F4CA} \u542F\u52A8\u9875\u9762\u6C60\u76D1\u63A7..."),ue(1e4));var N=l.server.port,L=l.server.host;et(P,{port:N,host:L});s(`\u{1F680} \u670D\u52A1\u5668\u8FD0\u884C\u5728 http://${L}:${N}`);s(`\u{1F3E0} \u7BA1\u7406\u9762\u677F: http://${L}:${N}/`);s(`\u{1F4CB} \u5065\u5EB7\u68C0\u67E5: http://${L}:${N}/health`);s(`\u{1F4AC} \u804A\u5929\u7AEF\u70B9: http://${L}:${N}/v1/chat/completions`);s(`\u{1F3AF} AI Studio URL: ${l.aiStudio.url}`);s(`\u{1F30D} \u73AF\u5883: ${process.env.NODE_ENV||"development"}`);async function tt(){let t;try{s("\u{1F4F8} \u5F00\u59CB\u83B7\u53D6AI Studio\u9875\u9762\u622A\u56FE..."),t=await F(),s(`\u{1F310} \u667A\u80FD\u5BFC\u822A\u5230: ${l.aiStudio.url}`),await k(t,l.aiStudio.url,{timeout:l.aiStudio.pageTimeout}),await q(t),await t.waitForTimeout(2e3);let e=await W(t,"./screenshots","aistudio-startup");s(`\u2705 AI Studio\u622A\u56FE\u5DF2\u4FDD\u5B58: ${e}`)}catch(e){v("\u274C \u622A\u56FEAI Studio\u9875\u9762\u65F6\u51FA\u9519:",e.message)}finally{t&&(await R(t),s("\u{1F504} \u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D"))}}setTimeout(()=>{s(`
23
+ \u{1F4CA} \u521D\u59CB\u9875\u9762\u6C60\u72B6\u6001:`),me()},1e3);setTimeout(()=>{tt()},2e3);