Spaces:
Running
Running
github-actions[bot]
commited on
Commit
·
f89e0a1
1
Parent(s):
85d5a1e
Deploy: Update from GitHub Actions build
Browse files- dist/index.js +8 -10
dist/index.js
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
-
var
|
2 |
-
`;try{await W.promises.appendFile(A.logFile,a)}catch(n){console.error("\u5199\u5165\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25:",n)}}function Ge(t,...e){if(!A.enableConsole)return;let o={[P.DEBUG]:console.debug,[P.INFO]:console.log,[P.WARN]:console.warn,[P.ERROR]:console.error}[t]||console.log,a=new Date().toLocaleTimeString();o(`[${a}] [${t}]`,...e)}function q(t,...e){let o=He(...e);Ge(t,...e),Ue(t,o)}var P,A,r,$,g,S=te(()=>{P={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},A={logFile:"./logs/app.log",logDir:"./logs",enableConsole:!0,enableFile:!0,logLevel:process.env.LOG_LEVEL||P.INFO};r=(...t)=>q(P.INFO,...t),$=(...t)=>q(P.WARN,...t),g=(...t)=>q(P.ERROR,...t)});var ae={};Ne(ae,{checkCookieAvailability:()=>Be,ensureDirectoryExists:()=>re,getHumanReadableTimestamp:()=>oe,loadCookies:()=>K,saveScreenshot:()=>J,waitForUserInput:()=>Ve});import _ from"node:fs";import ze from"node:path";import je from"node:readline";function oe(){return new Date().toISOString().replace(/T/,"_").replace(/:/g,"-").replace(/\..+/,"")}function re(t){_.existsSync(t)||(_.mkdirSync(t,{recursive:!0}),r(`\u5DF2\u521B\u5EFA\u76EE\u5F55: ${t}`))}function Be(t,e){if(e)try{return JSON.parse(e),r("\u53D1\u73B0\u5E76\u9A8C\u8BC1\u4E86\u73AF\u5883\u53D8\u91CF\u4E2D\u7684 COOKIES\u3002"),!0}catch(o){g("\u73AF\u5883\u53D8\u91CF COOKIES \u683C\u5F0F\u65E0\u6548 (\u5FC5\u987B\u662F JSON \u6570\u7EC4\u5B57\u7B26\u4E32):",o.message)}return _.existsSync(t)?(r(`\u53D1\u73B0 Cookie \u6587\u4EF6: ${t}`),!0):(g(`Cookie \u6587\u4EF6\u4E0D\u5B58\u5728: ${t}\uFF0C\u4E14\u672A\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002`),r("\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 r("\u4ECE\u73AF\u5883\u53D8\u91CF COOKIES \u52A0\u8F7D Cookie..."),JSON.parse(e);if(_.existsSync(t))return r(`\u4ECE\u6587\u4EF6\u52A0\u8F7D Cookie: ${t}`),JSON.parse(_.readFileSync(t,"utf8"))}catch(o){throw g("\u52A0\u8F7D Cookie \u5931\u8D25:",o),new Error("\u65E0\u6CD5\u52A0\u8F7D\u6216\u89E3\u6790 Cookie\u3002")}return[]}async function J(t,e,o="screenshot",a=!0){if(re(e),a){let s=oe();o=`${o}_${s}`}let n=ze.join(e,`${o}.png`);return await t.screenshot({path:n,fullPage:!0}),r(`\u622A\u56FE\u5DF2\u4FDD\u5B58: ${n}`),n}function Ve(){let t=je.createInterface({input:process.stdin,output:process.stdout});return new Promise(e=>{t.question("",()=>{t.close(),e()})})}var L=te(()=>{S()});import{H3 as rt,serve as at,serveStatic as Me}from"h3";import{stat as Re,readFile as Ae}from"node:fs/promises";import{join as _e}from"node:path";import{chromium as We}from"playwright";import{newInjectedContext as qe}from"fingerprint-injector";import{FingerprintGenerator as Ke}from"fingerprint-generator";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"]},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=Fe;L();S();var v=null,M=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),r(`\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++,r(`\u521B\u5EFA\u65B0\u9875\u9762\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}\uFF0C\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),o}return r("\u9875\u9762\u6C60\u5DF2\u6EE1\uFF0C\u7B49\u5F85\u9875\u9762\u91CA\u653E..."),new Promise(e=>{let o=()=>{if(this.availablePages.length>0){let a=this.availablePages.pop();this.busyPages.add(a),r(`\u7B49\u5F85\u540E\u83B7\u53D6\u5230\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),e(a)}else setTimeout(o,100)};o()})}async releasePage(e){if(!this.busyPages.has(e)){r("\u5C1D\u8BD5\u91CA\u653E\u4E0D\u5728\u5FD9\u788C\u5217\u8868\u4E2D\u7684\u9875\u9762");return}try{await this.cleanupPage(e),this.busyPages.delete(e),this.availablePages.push(e),r(`\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){r(`\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(a=>{(a.startsWith("__handleStreamChunk")||a.startsWith("__onStreamChunk")||a.startsWith("__onStreamEnd"))&&delete window[a]}),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){r(`\u6E05\u7406\u9875\u9762\u72B6\u6001\u65F6\u51FA\u73B0evaluate\u9519\u8BEF: ${o.message}`)}r("\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--,r(`\u9875\u9762\u5DF2\u4ECE\u6C60\u4E2D\u79FB\u9664\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}`)}catch(o){r(`\u5173\u95ED\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}}async cleanup(){r("\u5F00\u59CB\u6E05\u7406\u9875\u9762\u6C60...");for(let e of this.busyPages)try{await e.close()}catch(o){r(`\u5173\u95ED\u5FD9\u788C\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}for(let e of this.availablePages)try{await e.close()}catch(o){r(`\u5173\u95ED\u53EF\u7528\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}this.busyPages.clear(),this.availablePages=[],this.totalPages=0,r("\u9875\u9762\u6C60\u6E05\u7406\u5B8C\u6210")}getStatus(){return{total:this.totalPages,available:this.availablePages.length,busy:this.busyPages.size,maxSize:this.maxSize}}},w=null;async function Je(){if(!v){v=await We.launch({headless:l.browser.headless,timeout:l.browser.timeout,args:l.browser.args,executablePath:l.browser.executablePath});let t=new Ke().getFingerprint({devices:["desktop"],operatingSystems:["windows"],browsers:[{name:"chrome"}]});M=await qe(v,{fingerprint:t,newContextOptions:{locale:"zh-CN",serviceWorkers:"allow",javaScriptEnabled:!0,bypassCSP:!1}});let e=K(l.cookieFile,l.cookiesFromEnv);await M.addCookies(e)}return{browser:v,context:M}}function ne(t=5){return w||(w=new H(t),r(`\u9875\u9762\u6C60\u5DF2\u521D\u59CB\u5316\uFF0C\u6700\u5927\u9875\u9762\u6570: ${t}`)),w}function ie(){return w||(w=new H,r("\u9875\u9762\u6C60\u5DF2\u81EA\u52A8\u521D\u59CB\u5316\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E")),w}async function U(){let e=await ie().getPage();return await e.bringToFront(),e}async function k(t){await ie().releasePage(t)}function O(){return w?w.getStatus():{total:0,available:0,busy:0,maxSize:0}}async function G(t,e,o={}){let a=t.url();r("\u5F53\u524D\u9875\u9762URL:",a),r("\u76EE\u6807URL:",e);try{return a!==e?(r("\u9875\u9762URL\u4E0D\u5339\u914D\uFF0C\u9700\u8981\u5BFC\u822A..."),await t.goto(e,{waitUntil:"load",timeout:3e4,...o}),r("\u9875\u9762\u5BFC\u822A\u5B8C\u6210"),!0):(r("\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}),r("\u9875\u9762\u5237\u65B0\u5B8C\u6210"),!0)}catch{}return!1}async function ce(t,e={}){let{minClicks:o=1,maxClicks:a=3,minDelay:n=300,maxDelay:s=500,referenceElement:i=null}=e;try{r("\u5F00\u59CB\u6A21\u62DF\u4EBA\u7C7B\u968F\u673A\u70B9\u51FB\u884C\u4E3A...");let m=Math.floor(Math.random()*(a-o+1))+o;r(`\u5C06\u8FDB\u884C ${m} \u6B21\u968F\u673A\u70B9\u51FB`);let u=null;if(i)try{let c=await i.boundingBox();c&&(u={x:c.x-50,y:Math.max(0,c.y-200),width:c.width+50,height:300},r(`\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){r(`\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(),p=c?.width||1280,f=c?.height||720;u={x:p*.3,y:f*.3,width:p*.4,height:f*.2},r(`\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<m;c++)try{let p=Math.floor(Math.random()*u.width)+u.x,f=Math.floor(Math.random()*u.height)+u.y;r(`\u7B2C ${c+1} \u6B21\u5B89\u5168\u70B9\u51FB: (${p}, ${f})`);let d=await t.locator("*").first().evaluate((h,T)=>{let x=document.elementFromPoint(T.x,T.y);if(!x)return{safe:!0};let I=x.tagName.toLowerCase(),y=x.hasAttribute("href"),E=x.hasAttribute("onclick")||x.onclick,b=I==="button"||x.type==="button",R=I==="a"||y,ee=["input","textarea","select"].includes(I);return{safe:!b&&!R&&!E&&!ee,tagName:I,hasHref:y,hasOnClick:E,isButton:b,isLink:R,isInput:ee}},{x:p,y:f});if(d.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),r(`\u5B89\u5168\u70B9\u51FB\u5B8C\u6210: (${p}, ${f})`)):r(`\u8DF3\u8FC7\u4E0D\u5B89\u5168\u7684\u70B9\u51FB\u4F4D\u7F6E (${p}, ${f}): ${d.tagName}`),c<m-1){let h=Math.floor(Math.random()*(s-n+1))+n;r(`\u7B49\u5F85 ${h}ms \u540E\u8FDB\u884C\u4E0B\u4E00\u6B21\u70B9\u51FB`),await t.waitForTimeout(h)}}catch(p){r(`\u7B2C ${c+1} \u6B21\u70B9\u51FB\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u6B21: ${p.message}`)}r("\u5B89\u5168\u968F\u673A\u70B9\u51FB\u6A21\u62DF\u5B8C\u6210")}catch(m){r(`\u6A21\u62DF\u5B89\u5168\u968F\u673A\u70B9\u51FB\u65F6\u51FA\u73B0\u9519\u8BEF: ${m.message}`)}}async function le(t,e={}){let{includeScrolling:o=!0,includeMouseMovement:a=!0,includeRandomClicks:n=!0,duration:s=3e3}=e;try{r("\u5F00\u59CB\u6A21\u62DF\u590D\u6742\u7684\u4EBA\u7C7B\u884C\u4E3A...");let i=Date.now(),m=t.viewportSize(),u=m?.width||1280,c=m?.height||720;for(;Date.now()-i<s;){let p=Math.random();if(p<.3&&o){let d=Math.random()>.5?"down":"up",h=Math.floor(Math.random()*300)+100;r(`\u6A21\u62DF\u6EDA\u52A8: ${d}, \u8DDD\u79BB: ${h}px`),await t.mouse.wheel(0,d==="down"?h:-h)}else if(p<.6&&a){let d=Math.floor(Math.random()*u),h=Math.floor(Math.random()*c);r(`\u6A21\u62DF\u9F20\u6807\u79FB\u52A8\u5230: (${d}, ${h})`),await t.mouse.move(d,h,{steps:Math.floor(Math.random()*15)+5})}else if(p<.8&&n){let d=Math.floor(Math.random()*(u*.8))+u*.1,h=Math.floor(Math.random()*(c*.8))+c*.1;r(`\u6A21\u62DF\u968F\u673A\u70B9\u51FB: (${d}, ${h})`),await t.mouse.click(d,h)}let f=Math.floor(Math.random()*800)+200;await t.waitForTimeout(f)}r("\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u6A21\u62DF\u5B8C\u6210")}catch(i){r(`\u6A21\u62DF\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u65F6\u51FA\u73B0\u9519\u8BEF: ${i.message}`)}}async function z(t,e=5e3){try{r("\u68C0\u67E5\u662F\u5426\u6709\u6B22\u8FCE\u5BF9\u8BDD\u6846\u9700\u8981\u5173\u95ED...");let o="mat-dialog-container",a='button[mat-dialog-close][aria-label="close"]';if(await t.locator(o).first().isVisible({timeout:e})){r("\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846\uFF0C\u5C1D\u8BD5\u5173\u95ED...");let s=t.locator(a).first();return await s.isVisible({timeout:2e3})?(await s.click(),r("\u5DF2\u901A\u8FC7\u5173\u95ED\u6309\u94AE\u5173\u95ED\u6B22\u8FCE\u5BF9\u8BDD\u6846"),await t.waitForTimeout(1e3),!0):(r("\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 r("\u672A\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846"),!1}catch(o){return r("\u5904\u7406\u6B22\u8FCE\u5BF9\u8BDD\u6846\u65F6\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u6267\u884C:",o.message),!1}}var se=!1;async function Ye(){if(!v){r("\u6D4F\u89C8\u5668\u5B9E\u4F8B\u4E0D\u5B58\u5728\uFF0C\u65E0\u9700\u6E05\u7406\u3002");return}r("\u{1F9F9} \u5F00\u59CB\u6E05\u7406\u6D4F\u89C8\u5668\u8D44\u6E90..."),w&&(await w.cleanup(),w=null,r("\u2705 \u9875\u9762\u6C60\u5DF2\u6E05\u7406\u3002")),M&&(await M.close(),M=null,r("\u2705 \u6D4F\u89C8\u5668\u4E0A\u4E0B\u6587\u5DF2\u5173\u95ED\u3002")),v&&(await v.close(),v=null,r("\u2705 \u6D4F\u89C8\u5668\u5B9E\u4F8B\u5DF2\u5173\u95ED\u3002")),r("\u2728 \u6240\u6709\u8D44\u6E90\u5747\u5DF2\u6210\u529F\u91CA\u653E\u3002")}async function Y(t){if(se){r("\u6E05\u7406\u5DF2\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7A0D\u5019...");return}se=!0,r(`
|
3 |
-
\u{1F6A8} \u6536\u5230\u4FE1\u53F7 ${t}\u3002\u5F00\u59CB\u4F18\u96C5\u505C\u673A...`);try{await
|
4 |
--- \u9875\u9762\u6C60\u72B6\u6001 @ ${e} ---
|
5 |
\u603B\u9875\u9762\u6570: ${t.total}
|
6 |
\u53EF\u7528\u9875\u9762\u6570: ${t.available}
|
@@ -8,17 +8,15 @@ var Oe=Object.defineProperty;var te=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ne=(t,e)=>{
|
|
8 |
\u6700\u5927\u9875\u9762\u6570: ${t.maxSize}
|
9 |
\u4F7F\u7528\u7387: ${o}%
|
10 |
------------------------------------
|
11 |
-
`)}function he(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 fe(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=
|
12 |
|
13 |
-
`),stream:o,model:a,temperature:n,messages:e}}import{createError as X}from"h3";function ye(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 X({statusCode:401,statusMessage:"Unauthorized: Missing Authorization header."});let[o,a]=e.split(" ");if(o!=="Bearer"||!a)throw X({statusCode:401,statusMessage:"Unauthorized: Invalid Authorization header format. Expected: Bearer <token>."});if(a!==l.api.token)throw X({statusCode:401,statusMessage:"Unauthorized: Invalid API token."})}S();var N=class{constructor(e,o={}){this.page=e,this.options={enableHumanSimulation:!1,...o},this.modelMapping=Object.fromEntries(Object.entries(l.models).map(([a,n])=>[a,n.displayName]))}async waitForPageLoad(){try{return await this.page.waitForSelector("body",{timeout:15e3}),await z(this.page),!0}catch(e){return e("\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}),r("\u8F93\u5165\u6846\u7684\u7236\u5BB9\u5668\u5DF2\u52A0\u8F7D\u3002")}catch{$("\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 a=this.page.locator(o),n=await a.count();if(n>0){r(`\u9009\u62E9\u5668 "${o}" \u627E\u5230\u4E86 ${n} \u4E2A\u5143\u7D20\u3002\u6B63\u5728\u68C0\u67E5\u53EF\u89C1\u6027\u548C\u53EF\u7528\u6027...`);for(let s=0;s<n;s++){let i=a.nth(s);if(await i.isVisible()&&await i.isEnabled())return r(`\u6210\u529F\u627E\u5230\u53EF\u7528\u8F93\u5165\u6846: ${o} (\u7D22\u5F15 ${s})`),i}r(`\u9009\u62E9\u5668 "${o}" \u627E\u5230\u7684\u5143\u7D20\u5747\u4E0D\u53EF\u89C1\u6216\u4E0D\u53EF\u7528\u3002`)}}catch(a){$(`\u4F7F\u7528\u9009\u62E9\u5668 "${o}" \u67E5\u627E\u65F6\u51FA\u9519: ${a.message}`)}if(g("\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(()=>(L(),ae));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 a=this.page.locator(o);if(await a.count()>0){let n=a.first();if(!await n.isDisabled())return n}}return g("\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 ce(this.page,{referenceElement:o}),await o.fill(e),await this.page.waitForTimeout(200),r("\u6D88\u606F\u586B\u5145\u5B8C\u6210\u3002"),!0}catch(a){return a("\u586B\u5145\u6D88\u606F\u5931\u8D25:",a),!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}),r("\u53D1\u9001\u6309\u94AE\u5DF2\u53EF\u7528\u3002"),!0}catch{return $("\u7B49\u5F85\u53D1\u9001\u6309\u94AE\u53EF\u7528\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u3002"),!1}}async sendMessage(){this.options.enableHumanSimulation&&await le(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(),r("\u6D88\u606F\u5DF2\u53D1\u9001\u3002"),!0}catch(o){o("\u70B9\u51FB\u53D1\u9001\u6309\u94AE\u5931\u8D25:",o);try{return r("\u5C1D\u8BD5\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E (Ctrl+Enter) \u53D1\u9001..."),await this.page.keyboard.press("Control+Enter"),r("\u5DF2\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u3002"),!0}catch(a){return o("\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u4E5F\u5931\u8D25:",a),!1}}}async setModel(e){try{let o=this.modelMapping[e]||e,a=this.page.locator("ms-model-selector-two-column");if(await a.count()===0)return r("\u672A\u627E\u5230\u6A21\u578B\u9009\u62E9\u5668\uFF0C\u8DF3\u8FC7\u6A21\u578B\u8BBE\u7F6E\u3002"),!1;if((await a.locator(".model-option-content .gmat-body-medium").textContent())?.trim()===o)return r("\u5F53\u524D\u5DF2\u662F\u76EE\u6807\u6A21\u578B\uFF0C\u65E0\u9700\u5207\u6362\u3002"),!0;await a.click({timeout:5e3});let s=this.page.locator(".mat-mdc-select-panel");await s.waitFor({state:"visible",timeout:5e3});let i=s.locator("mat-option.model-option",{hasText:o});return await i.count()>0?(await i.first().click({timeout:5e3}),await this.page.waitForTimeout(1e3),r(`\u6A21\u578B\u5DF2\u6210\u529F\u8BBE\u7F6E\u4E3A: ${o}`),!0):(r(`\u672A\u5728\u4E0B\u62C9\u83DC\u5355\u4E2D\u627E\u5230\u76EE\u6807\u6A21\u578B: ${o}`),await this.page.keyboard.press("Escape"),!1)}catch(o){o("\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 r("\u672A\u627E\u5230\u6E29\u5EA6\u8BBE\u7F6E\u5BB9\u5668\uFF0C\u8DF3\u8FC7\u3002"),!1;let a=o.locator('input[type="number"]');return await a.count()>0?(await a.fill(e.toString()),await a.dispatchEvent("change"),r(`\u6E29\u5EA6\u5DF2\u8BBE\u7F6E\u4E3A: ${e}`),!0):(r("\u672A\u627E\u5230\u6E29\u5EA6\u6570\u5B57\u8F93\u5165\u6846\uFF0C\u8DF3\u8FC7\u8BBE\u7F6E\u3002"),!1)}catch(o){return o("\u8BBE\u7F6E\u6E29\u5EA6\u65F6\u51FA\u9519:",o),!1}}async processMessage(e,o={}){if(r("\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 r("\u6D88\u606F\u53D1\u9001\u6210\u529F\uFF0C\u7B49\u5F85\u7F51\u7EDC\u62E6\u622A\u83B7\u53D6\u54CD\u5E94\u3002"),!0}};S();var j=class{TARGET_URL_PATTERN=new RegExp("MakerSuiteService/GenerateContent");constructor(e,o,a){this.page=e,this.onStreamChunk=o,this.onStreamEnd=a,this.isActive=!1,this.routeHandler=this._handleRoute.bind(this)}async activate(){this.isActive||(r("[InterceptorV2] \u6FC0\u6D3B\u7F51\u7EDC\u8DEF\u7531\u62E6\u622A..."),await this.page.route(this.TARGET_URL_PATTERN,this.routeHandler),this.isActive=!0,r(`[InterceptorV2] \u62E6\u622A\u5668\u5DF2\u6FC0\u6D3B\uFF0C\u76D1\u542C URL pattern: ${this.TARGET_URL_PATTERN}`))}async deactivate(){if(this.isActive){r("[InterceptorV2] \u505C\u7528\u7F51\u7EDC\u8DEF\u7531\u62E6\u622A...");try{await this.page.unroute(this.TARGET_URL_PATTERN,this.routeHandler),this.isActive=!1,r("[InterceptorV2] \u62E6\u622A\u5668\u5DF2\u505C\u7528\u3002")}catch(e){g(`[InterceptorV2] \u505C\u7528\u62E6\u622A\u5668\u65F6\u51FA\u9519: ${e.message}`)}}}async _handleRoute(e,o){r(`[InterceptorV2] \u62E6\u622A\u5230\u76EE\u6807\u8BF7\u6C42: ${o.method()} ${o.url()}`);try{await e.fulfill({status:200,contentType:"application/json",body:JSON.stringify({message:"Request handled by backend interceptor."})}),r("[InterceptorV2] \u5DF2\u5411\u6D4F\u89C8\u5668\u53D1\u9001\u4F2A\u9020\u7684\u6210\u529F\u54CD\u5E94\u3002")}catch(a){g(`[InterceptorV2] Fulfill \u539F\u59CB\u8BF7\u6C42\u5931\u8D25: ${a.message}`),e.isFulfillable()&&await e.abort().catch(n=>g(`[InterceptorV2] Abort \u8BF7\u6C42\u4E5F\u5931\u8D25: ${n.message}`));return}try{r("[InterceptorV2] \u6B63\u5728\u4F7F\u7528 Node.js fetch \u91CD\u65B0\u53D1\u9001\u8BF7\u6C42...");let a=await o.headers();delete a["x-playwright-api-request"],delete a["content-length"];let n=await fetch(o.url(),{method:o.method(),headers:a,body:o.postDataBuffer()});if(!n.ok){let m=await n.text();this.onStreamChunk(m);return}if(!n.body)throw new Error("\u540E\u7AEF fetch \u54CD\u5E94\u4E2D\u6CA1\u6709 body\u3002");r("[InterceptorV2] \u5F00\u59CB\u4ECE\u540E\u7AEF fetch \u63A5\u6536\u6D41\u5F0F\u6570\u636E...");let s=n.body.getReader(),i=new TextDecoder;for(;;){let{done:m,value:u}=await s.read();if(m)break;let c=i.decode(u,{stream:!0});this.onStreamChunk(c)}r("[InterceptorV2] \u6D41\u63A5\u6536\u5B8C\u6BD5\u3002"),this.onStreamEnd()}catch(a){g("[InterceptorV2] \u540E\u7AEF\u5904\u7406\u8BF7\u6C42\u65F6\u53D1\u751F\u4E25\u91CD\u9519\u8BEF:",a),this.onStreamEnd()}}};S();function Qe(t){return t.includes("The caller does not have permission")?($("\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 be(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,`
|
14 |
-
`).replace(/\\"/g,'"')})}for(let o of t)e.push(...be(o))}return e}function Q(t){let e=Qe(t);if(e)return e;try{let s=t.trim().replace(/\n/g,",").replace(/,+/g,",");s.endsWith(",")&&(s=s.slice(0,-1)),s.startsWith("[")||(s="["+s),s.endsWith("]")||(s=s+"]"),s=s.replace(/,]/g,"]").replace(/\[,/g,"[");let i=JSON.parse(s),m=be(i);if(m.length>0){let u=!1;return m.map(c=>(u?c.type="text":c.type==="text"&&(u=!0),c))}}catch{}let o=/\[null,\s*"((?:\\"|[^"])*)"/g,a=[],n;for(;(n=o.exec(t))!==null;)try{let s=n[1].replace(/\\n/g,`
|
15 |
-
`).replace(/\\"/g,'"');if(s&&s!=="model"){let i=s.trim().startsWith("**")?"thinking":"text";a.push({type:i,content:s})}}catch{}if(a.length>0){let s=!1;return a.map(i=>(s?i.type="text":i.type==="text"&&(s=!0),i))}return null}function Se(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 Z(t,e="gemini-pro"){return{object:"error",message:t,type:"invalid_request_error",model:e}}function xe(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}}}S();var B=3,Ee=100;function Ze(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(a=>e.includes(a))}function et(t){let e=t.message.toLowerCase();return["permission","unauthorized","\u65E0\u6743\u8BBF\u95EE","cookie","\u767B\u5F55"].some(a=>e.includes(a))}async function Pe(t,e,o){let a=null,n=null;try{a=await U();for(let s=1;s<=B;s++)try{r(`\u{1F310} [\u5C1D\u8BD5 ${s}/${B}] \u5F00\u59CB\u5904\u7406\u8BF7\u6C42...`),await G(a,l.aiStudio.url,{timeout:l.aiStudio.pageTimeout});let i=await o(a,t,e);return await k(a),i}catch(i){if(n=i,$(`\u274C [\u5C1D\u8BD5 ${s}/${B}] \u5931\u8D25: ${i.message}`),(et(i)||Ze(i))&&s<B)r(`\u68C0\u6D4B\u5230\u53EF\u91CD\u8BD5\u7684\u9519\u8BEF\uFF08\u6743\u9650\u6216\u9875\u9762\u72B6\u6001\uFF09\uFF0C\u5C06\u5728 ${Ee}ms \u540E\u91CD\u8BD5...`),await new Promise(m=>setTimeout(m,Ee));else throw i("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\u6216\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u5C06\u629B\u51FA\u5F02\u5E38\u3002"),i}}catch(s){throw s("\u5904\u7406 AI Studio \u8BF7\u6C42\u6700\u7EC8\u5931\u8D25:",s),a&&await k(a),n||s}}async function $e(t,e,o={}){let a=o.model||l.api.defaultModel;try{await Pe(t,o,async(n,s,i)=>new Promise(async(m,u)=>{let c=!1,p="",f=new Set,d=null,h=!1,T=y=>{c||(c=!0,d&&d.deactivate().catch(g),y?u(y):m())},x=y=>{if(c)return;p+=y;let E=Q(p);if(E?.permissionError)return T(new Error(E.content));if(Array.isArray(E)&&E.length>0)for(let b of E){let R=`${b.type}::${b.content}`;b.content?.trim()&&!f.has(R)&&(b.type==="text"&&(h=!0),!h||b.type==="text"?(e.enqueue(`data: ${JSON.stringify(Se(b.content,b.type,a))}
|
16 |
|
17 |
-
`)
|
18 |
|
19 |
-
`),e.close(),
|
20 |
|
21 |
`),e.enqueue(`data: [DONE]
|
22 |
|
23 |
-
`),e.close()}catch(
|
24 |
\u{1F4CA} \u521D\u59CB\u9875\u9762\u6C60\u72B6\u6001:`),de()},1e3);setTimeout(()=>{st()},2e3);
|
|
|
1 |
+
var _e=Object.defineProperty;var te=(t,e)=>()=>(t&&(e=t(t=0)),e);var Oe=(t,e)=>{for(var o in e)_e(t,o,{get:e[o],enumerable:!0})};import j from"node:fs";function De(){j.existsSync(C.logDir)||j.mkdirSync(C.logDir,{recursive:!0})}function Fe(...t){return t.map(e=>typeof e=="object"&&e!==null?JSON.stringify(e,null,2):String(e)).join(" ")}async function Le(t,e){if(!C.enableFile)return;De();let a=`[${new Date().toISOString()}] [${t}] ${e}
|
2 |
+
`;try{await j.promises.appendFile(C.logFile,a)}catch(s){console.error("\u5199\u5165\u65E5\u5FD7\u6587\u4EF6\u5931\u8D25:",s)}}function He(t,...e){if(!C.enableConsole)return;let o={[x.DEBUG]:console.debug,[x.INFO]:console.log,[x.WARN]:console.warn,[x.ERROR]:console.error}[t]||console.log,a=new Date().toLocaleTimeString();o(`[${a}] [${t}]`,...e)}function V(t,...e){let o=Fe(...e);He(t,...e),Le(t,o)}var x,C,r,E,g,P=te(()=>{x={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},C={logFile:"./logs/app.log",logDir:"./logs",enableConsole:!0,enableFile:!0,logLevel:process.env.LOG_LEVEL||x.INFO};r=(...t)=>V(x.INFO,...t),E=(...t)=>V(x.WARN,...t),g=(...t)=>V(x.ERROR,...t)});var ae={};Oe(ae,{checkCookieAvailability:()=>Ge,ensureDirectoryExists:()=>re,getHumanReadableTimestamp:()=>oe,loadCookies:()=>q,saveScreenshot:()=>W,waitForUserInput:()=>ze});import A from"node:fs";import Ue from"node:path";import Be from"node:readline";function oe(){return new Date().toISOString().replace(/T/,"_").replace(/:/g,"-").replace(/\..+/,"")}function re(t){A.existsSync(t)||(A.mkdirSync(t,{recursive:!0}),r(`\u5DF2\u521B\u5EFA\u76EE\u5F55: ${t}`))}function Ge(t,e){if(e)try{return JSON.parse(e),r("\u53D1\u73B0\u5E76\u9A8C\u8BC1\u4E86\u73AF\u5883\u53D8\u91CF\u4E2D\u7684 COOKIES\u3002"),!0}catch(o){g("\u73AF\u5883\u53D8\u91CF COOKIES \u683C\u5F0F\u65E0\u6548 (\u5FC5\u987B\u662F JSON \u6570\u7EC4\u5B57\u7B26\u4E32):",o.message)}return A.existsSync(t)?(r(`\u53D1\u73B0 Cookie \u6587\u4EF6: ${t}`),!0):(g(`Cookie \u6587\u4EF6\u4E0D\u5B58\u5728: ${t}\uFF0C\u4E14\u672A\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002`),r("\u8BF7\u5148\u8FD0\u884C `npm run login` \u6216\u8BBE\u7F6E COOKIES \u73AF\u5883\u53D8\u91CF\u3002"),!1)}function q(t,e){try{if(e)return r("\u4ECE\u73AF\u5883\u53D8\u91CF COOKIES \u52A0\u8F7D Cookie..."),JSON.parse(e);if(A.existsSync(t))return r(`\u4ECE\u6587\u4EF6\u52A0\u8F7D Cookie: ${t}`),JSON.parse(A.readFileSync(t,"utf8"))}catch(o){throw g("\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",a=!0){if(re(e),a){let n=oe();o=`${o}_${n}`}let s=Ue.join(e,`${o}.png`);return await t.screenshot({path:s,fullPage:!0}),r(`\u622A\u56FE\u5DF2\u4FDD\u5B58: ${s}`),s}function ze(){let t=Be.createInterface({input:process.stdin,output:process.stdout});return new Promise(e=>{t.question("",()=>{t.close(),e()})})}var D=te(()=>{P()});import{H3 as rt,serve as at,serveStatic as Te}from"h3";import{stat as Ce,readFile as Ae}from"node:fs/promises";import{join as Me}from"node:path";import{chromium as je}from"playwright";import{newInjectedContext as Ve}from"fingerprint-injector";import{FingerprintGenerator as qe}from"fingerprint-generator";import ke from"dotenv";ke.config();var Ne={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"]},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"}},u=Ne;D();P();var $=null,T=null,F=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),r(`\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++,r(`\u521B\u5EFA\u65B0\u9875\u9762\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}\uFF0C\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),o}return r("\u9875\u9762\u6C60\u5DF2\u6EE1\uFF0C\u7B49\u5F85\u9875\u9762\u91CA\u653E..."),new Promise(e=>{let o=()=>{if(this.availablePages.length>0){let a=this.availablePages.pop();this.busyPages.add(a),r(`\u7B49\u5F85\u540E\u83B7\u53D6\u5230\u9875\u9762\uFF0C\u5F53\u524D\u5FD9\u788C\u9875\u9762\u6570: ${this.busyPages.size}`),e(a)}else setTimeout(o,100)};o()})}async releasePage(e){if(!this.busyPages.has(e)){r("\u5C1D\u8BD5\u91CA\u653E\u4E0D\u5728\u5FD9\u788C\u5217\u8868\u4E2D\u7684\u9875\u9762");return}try{await this.cleanupPage(e),this.busyPages.delete(e),this.availablePages.push(e),r(`\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){r(`\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(a=>{(a.startsWith("__handleStreamChunk")||a.startsWith("__onStreamChunk")||a.startsWith("__onStreamEnd"))&&delete window[a]}),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){r(`\u6E05\u7406\u9875\u9762\u72B6\u6001\u65F6\u51FA\u73B0evaluate\u9519\u8BEF: ${o.message}`)}r("\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--,r(`\u9875\u9762\u5DF2\u4ECE\u6C60\u4E2D\u79FB\u9664\uFF0C\u603B\u9875\u9762\u6570: ${this.totalPages}`)}catch(o){r(`\u5173\u95ED\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}}async cleanup(){r("\u5F00\u59CB\u6E05\u7406\u9875\u9762\u6C60...");for(let e of this.busyPages)try{await e.close()}catch(o){r(`\u5173\u95ED\u5FD9\u788C\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}for(let e of this.availablePages)try{await e.close()}catch(o){r(`\u5173\u95ED\u53EF\u7528\u9875\u9762\u65F6\u51FA\u9519: ${o.message}`)}this.busyPages.clear(),this.availablePages=[],this.totalPages=0,r("\u9875\u9762\u6C60\u6E05\u7406\u5B8C\u6210")}getStatus(){return{total:this.totalPages,available:this.availablePages.length,busy:this.busyPages.size,maxSize:this.maxSize}}},y=null;async function We(){if(!$){$=await je.launch({headless:u.browser.headless,timeout:u.browser.timeout,args:u.browser.args,executablePath:u.browser.executablePath});let t=new qe().getFingerprint({devices:["desktop"],operatingSystems:["windows"],browsers:[{name:"chrome"}]});T=await Ve($,{fingerprint:t,newContextOptions:{locale:"zh-CN",serviceWorkers:"allow",javaScriptEnabled:!0,bypassCSP:!1}});let e=q(u.cookieFile,u.cookiesFromEnv);await T.addCookies(e)}return{browser:$,context:T}}function ne(t=5){return y||(y=new F(t),r(`\u9875\u9762\u6C60\u5DF2\u521D\u59CB\u5316\uFF0C\u6700\u5927\u9875\u9762\u6570: ${t}`)),y}function ie(){return y||(y=new F,r("\u9875\u9762\u6C60\u5DF2\u81EA\u52A8\u521D\u59CB\u5316\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E")),y}async function L(){let e=await ie().getPage();return await e.bringToFront(),e}async function M(t){await ie().releasePage(t)}function R(){return y?y.getStatus():{total:0,available:0,busy:0,maxSize:0}}async function H(t,e,o={}){let a=t.url();r("\u5F53\u524D\u9875\u9762URL:",a),r("\u76EE\u6807URL:",e);try{return a!==e?(r("\u9875\u9762URL\u4E0D\u5339\u914D\uFF0C\u9700\u8981\u5BFC\u822A..."),await t.goto(e,{waitUntil:"load",timeout:3e4,...o}),r("\u9875\u9762\u5BFC\u822A\u5B8C\u6210"),!0):(r("\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}),r("\u9875\u9762\u5237\u65B0\u5B8C\u6210"),!0)}catch{}return!1}async function ce(t,e={}){let{minClicks:o=1,maxClicks:a=3,minDelay:s=300,maxDelay:n=500,referenceElement:i=null}=e;try{r("\u5F00\u59CB\u6A21\u62DF\u4EBA\u7C7B\u968F\u673A\u70B9\u51FB\u884C\u4E3A...");let p=Math.floor(Math.random()*(a-o+1))+o;r(`\u5C06\u8FDB\u884C ${p} \u6B21\u968F\u673A\u70B9\u51FB`);let m=null;if(i)try{let c=await i.boundingBox();c&&(m={x:c.x-50,y:Math.max(0,c.y-200),width:c.width+50,height:300},r(`\u4F7F\u7528\u8F93\u5165\u6846\u9644\u8FD1\u7684\u5B89\u5168\u533A\u57DF: x=${m.x}, y=${m.y}, w=${m.width}, h=${m.height}`))}catch(c){r(`\u83B7\u53D6\u53C2\u8003\u5143\u7D20\u4F4D\u7F6E\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: ${c.message}`)}if(!m){let c=t.viewportSize(),l=c?.width||1280,h=c?.height||720;m={x:l*.3,y:h*.3,width:l*.4,height:h*.2},r(`\u4F7F\u7528\u9ED8\u8BA4\u5B89\u5168\u533A\u57DF: x=${m.x}, y=${m.y}, w=${m.width}, h=${m.height}`)}for(let c=0;c<p;c++)try{let l=Math.floor(Math.random()*m.width)+m.x,h=Math.floor(Math.random()*m.height)+m.y;r(`\u7B2C ${c+1} \u6B21\u5B89\u5168\u70B9\u51FB: (${l}, ${h})`);let d=await t.locator("*").first().evaluate((f,b)=>{let w=document.elementFromPoint(b.x,b.y);if(!w)return{safe:!0};let I=w.tagName.toLowerCase(),N=w.hasAttribute("href"),S=w.hasAttribute("onclick")||w.onclick,Q=I==="button"||w.type==="button",Z=I==="a"||N,ee=["input","textarea","select"].includes(I);return{safe:!Q&&!Z&&!S&&!ee,tagName:I,hasHref:N,hasOnClick:S,isButton:Q,isLink:Z,isInput:ee}},{x:l,y:h});if(d.safe?(await t.mouse.move(l,h,{steps:Math.floor(Math.random()*10)+5}),await t.waitForTimeout(Math.floor(Math.random()*200)+100),await t.mouse.click(l,h),r(`\u5B89\u5168\u70B9\u51FB\u5B8C\u6210: (${l}, ${h})`)):r(`\u8DF3\u8FC7\u4E0D\u5B89\u5168\u7684\u70B9\u51FB\u4F4D\u7F6E (${l}, ${h}): ${d.tagName}`),c<p-1){let f=Math.floor(Math.random()*(n-s+1))+s;r(`\u7B49\u5F85 ${f}ms \u540E\u8FDB\u884C\u4E0B\u4E00\u6B21\u70B9\u51FB`),await t.waitForTimeout(f)}}catch(l){r(`\u7B2C ${c+1} \u6B21\u70B9\u51FB\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u6B21: ${l.message}`)}r("\u5B89\u5168\u968F\u673A\u70B9\u51FB\u6A21\u62DF\u5B8C\u6210")}catch(p){r(`\u6A21\u62DF\u5B89\u5168\u968F\u673A\u70B9\u51FB\u65F6\u51FA\u73B0\u9519\u8BEF: ${p.message}`)}}async function le(t,e={}){let{includeScrolling:o=!0,includeMouseMovement:a=!0,includeRandomClicks:s=!0,duration:n=3e3}=e;try{r("\u5F00\u59CB\u6A21\u62DF\u590D\u6742\u7684\u4EBA\u7C7B\u884C\u4E3A...");let i=Date.now(),p=t.viewportSize(),m=p?.width||1280,c=p?.height||720;for(;Date.now()-i<n;){let l=Math.random();if(l<.3&&o){let d=Math.random()>.5?"down":"up",f=Math.floor(Math.random()*300)+100;r(`\u6A21\u62DF\u6EDA\u52A8: ${d}, \u8DDD\u79BB: ${f}px`),await t.mouse.wheel(0,d==="down"?f:-f)}else if(l<.6&&a){let d=Math.floor(Math.random()*m),f=Math.floor(Math.random()*c);r(`\u6A21\u62DF\u9F20\u6807\u79FB\u52A8\u5230: (${d}, ${f})`),await t.mouse.move(d,f,{steps:Math.floor(Math.random()*15)+5})}else if(l<.8&&s){let d=Math.floor(Math.random()*(m*.8))+m*.1,f=Math.floor(Math.random()*(c*.8))+c*.1;r(`\u6A21\u62DF\u968F\u673A\u70B9\u51FB: (${d}, ${f})`),await t.mouse.click(d,f)}let h=Math.floor(Math.random()*800)+200;await t.waitForTimeout(h)}r("\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u6A21\u62DF\u5B8C\u6210")}catch(i){r(`\u6A21\u62DF\u590D\u6742\u4EBA\u7C7B\u884C\u4E3A\u65F6\u51FA\u73B0\u9519\u8BEF: ${i.message}`)}}async function U(t,e=5e3){try{r("\u68C0\u67E5\u662F\u5426\u6709\u6B22\u8FCE\u5BF9\u8BDD\u6846\u9700\u8981\u5173\u95ED...");let o="mat-dialog-container",a='button[mat-dialog-close][aria-label="close"]';if(await t.locator(o).first().isVisible({timeout:e})){r("\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846\uFF0C\u5C1D\u8BD5\u5173\u95ED...");let n=t.locator(a).first();return await n.isVisible({timeout:2e3})?(await n.click(),r("\u5DF2\u901A\u8FC7\u5173\u95ED\u6309\u94AE\u5173\u95ED\u6B22\u8FCE\u5BF9\u8BDD\u6846"),await t.waitForTimeout(1e3),!0):(r("\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 r("\u672A\u53D1\u73B0\u6B22\u8FCE\u5BF9\u8BDD\u6846"),!1}catch(o){return r("\u5904\u7406\u6B22\u8FCE\u5BF9\u8BDD\u6846\u65F6\u51FA\u73B0\u9519\u8BEF\uFF0C\u7EE7\u7EED\u6267\u884C:",o.message),!1}}var se=!1;async function Ke(){if(!$){r("\u6D4F\u89C8\u5668\u5B9E\u4F8B\u4E0D\u5B58\u5728\uFF0C\u65E0\u9700\u6E05\u7406\u3002");return}r("\u{1F9F9} \u5F00\u59CB\u6E05\u7406\u6D4F\u89C8\u5668\u8D44\u6E90..."),y&&(await y.cleanup(),y=null,r("\u2705 \u9875\u9762\u6C60\u5DF2\u6E05\u7406\u3002")),T&&(await T.close(),T=null,r("\u2705 \u6D4F\u89C8\u5668\u4E0A\u4E0B\u6587\u5DF2\u5173\u95ED\u3002")),$&&(await $.close(),$=null,r("\u2705 \u6D4F\u89C8\u5668\u5B9E\u4F8B\u5DF2\u5173\u95ED\u3002")),r("\u2728 \u6240\u6709\u8D44\u6E90\u5747\u5DF2\u6210\u529F\u91CA\u653E\u3002")}async function K(t){if(se){r("\u6E05\u7406\u5DF2\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u7A0D\u5019...");return}se=!0,r(`
|
3 |
+
\u{1F6A8} \u6536\u5230\u4FE1\u53F7 ${t}\u3002\u5F00\u59CB\u4F18\u96C5\u505C\u673A...`);try{await Ke(),process.exit(0)}catch(e){g("\u274C \u5728\u4F18\u96C5\u505C\u673A\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:",e),process.exit(1)}}function ue(){process.once("SIGUSR2",()=>K("SIGUSR2")),process.on("SIGINT",()=>K("SIGINT")),process.on("SIGTERM",()=>K("SIGTERM"))}P();var me=null;function pe(t=1e4){if(me){r("\u9875\u9762\u6C60\u76D1\u63A7\u5DF2\u5728\u8FD0\u884C\u4E2D\u3002");return}r(`\u5F00\u59CB\u76D1\u63A7\u9875\u9762\u6C60\u72B6\u6001\uFF0C\u95F4\u9694: ${t}ms`),me=setInterval(()=>{let e=R(),o=new Date().toLocaleTimeString(),a=e.total>0?(e.busy/e.total*100).toFixed(1):0;r(`[${o}] \u9875\u9762\u6C60\u72B6\u6001: \u603B\u8BA1=${e.total}, \u53EF\u7528=${e.available}, \u5FD9\u788C=${e.busy}, \u4F7F\u7528\u7387=${a}%`)},t)}function de(){let t=R(),e=new Date().toLocaleString(),o=t.total>0?(t.busy/t.total*100).toFixed(1):0;r(`
|
4 |
--- \u9875\u9762\u6C60\u72B6\u6001 @ ${e} ---
|
5 |
\u603B\u9875\u9762\u6570: ${t.total}
|
6 |
\u53EF\u7528\u9875\u9762\u6570: ${t.available}
|
|
|
8 |
\u6700\u5927\u9875\u9762\u6570: ${t.maxSize}
|
9 |
\u4F7F\u7528\u7387: ${o}%
|
10 |
------------------------------------
|
11 |
+
`)}function he(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 fe(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=R(),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 tt,createError as ot}from"h3";import{createError as Je}from"h3";function we(t){let{messages:e,stream:o=!1,model:a=u.api.defaultModel,temperature:s=u.api.temperature}=t;if(!e||!Array.isArray(e)||e.length===0)throw Je({statusCode:400,statusMessage:"Invalid request: `messages` must be a non-empty array."});return{prompt:e.map(i=>!i.role||!i.content?"":`${i.role}: ${i.content}`).join(`
|
12 |
|
13 |
+
`),stream:o,model:a,temperature:s,messages:e}}import{createError as J}from"h3";function ye(t){if(!u.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,a]=e.split(" ");if(o!=="Bearer"||!a)throw J({statusCode:401,statusMessage:"Unauthorized: Invalid Authorization header format. Expected: Bearer <token>."});if(a!==u.api.token)throw J({statusCode:401,statusMessage:"Unauthorized: Invalid API token."})}P();var _=class{constructor(e,o={}){this.page=e,this.options={enableHumanSimulation:!1,...o},this.modelMapping=Object.fromEntries(Object.entries(u.models).map(([a,s])=>[a,s.displayName]))}async waitForPageLoad(){try{return await this.page.waitForSelector("body",{timeout:15e3}),await U(this.page),!0}catch(e){return e("\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}),r("\u8F93\u5165\u6846\u7684\u7236\u5BB9\u5668\u5DF2\u52A0\u8F7D\u3002")}catch{E("\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 a=this.page.locator(o),s=await a.count();if(s>0){r(`\u9009\u62E9\u5668 "${o}" \u627E\u5230\u4E86 ${s} \u4E2A\u5143\u7D20\u3002\u6B63\u5728\u68C0\u67E5\u53EF\u89C1\u6027\u548C\u53EF\u7528\u6027...`);for(let n=0;n<s;n++){let i=a.nth(n);if(await i.isVisible()&&await i.isEnabled())return r(`\u6210\u529F\u627E\u5230\u53EF\u7528\u8F93\u5165\u6846: ${o} (\u7D22\u5F15 ${n})`),i}r(`\u9009\u62E9\u5668 "${o}" \u627E\u5230\u7684\u5143\u7D20\u5747\u4E0D\u53EF\u89C1\u6216\u4E0D\u53EF\u7528\u3002`)}}catch(a){E(`\u4F7F\u7528\u9009\u62E9\u5668 "${o}" \u67E5\u627E\u65F6\u51FA\u9519: ${a.message}`)}if(g("\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"),u.debug.saveScreenshots){let{saveScreenshot:o}=await Promise.resolve().then(()=>(D(),ae));await o(this.page,u.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 a=this.page.locator(o);if(await a.count()>0){let s=a.first();if(!await s.isDisabled())return s}}return g("\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 ce(this.page,{referenceElement:o}),await o.fill(e),await this.page.waitForTimeout(200),r("\u6D88\u606F\u586B\u5145\u5B8C\u6210\u3002"),!0}catch(a){return a("\u586B\u5145\u6D88\u606F\u5931\u8D25:",a),!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}),r("\u53D1\u9001\u6309\u94AE\u5DF2\u53EF\u7528\u3002"),!0}catch{return E("\u7B49\u5F85\u53D1\u9001\u6309\u94AE\u53EF\u7528\u8D85\u65F6\uFF0C\u5C06\u7EE7\u7EED\u5C1D\u8BD5\u3002"),!1}}async sendMessage(){this.options.enableHumanSimulation&&await le(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(),r("\u6D88\u606F\u5DF2\u53D1\u9001\u3002"),!0}catch(o){o("\u70B9\u51FB\u53D1\u9001\u6309\u94AE\u5931\u8D25:",o);try{return r("\u5C1D\u8BD5\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E (Ctrl+Enter) \u53D1\u9001..."),await this.page.keyboard.press("Control+Enter"),r("\u5DF2\u4F7F\u7528\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u3002"),!0}catch(a){return o("\u952E\u76D8\u5FEB\u6377\u952E\u53D1\u9001\u4E5F\u5931\u8D25:",a),!1}}}async setModel(e){try{let o=this.modelMapping[e]||e,a=this.page.locator("ms-model-selector-two-column");if(await a.count()===0)return r("\u672A\u627E\u5230\u6A21\u578B\u9009\u62E9\u5668\uFF0C\u8DF3\u8FC7\u6A21\u578B\u8BBE\u7F6E\u3002"),!1;if((await a.locator(".model-option-content .gmat-body-medium").textContent())?.trim()===o)return r("\u5F53\u524D\u5DF2\u662F\u76EE\u6807\u6A21\u578B\uFF0C\u65E0\u9700\u5207\u6362\u3002"),!0;await a.click({timeout:5e3});let n=this.page.locator(".mat-mdc-select-panel");await n.waitFor({state:"visible",timeout:5e3});let i=n.locator("mat-option.model-option",{hasText:o});return await i.count()>0?(await i.first().click({timeout:5e3}),await this.page.waitForTimeout(1e3),r(`\u6A21\u578B\u5DF2\u6210\u529F\u8BBE\u7F6E\u4E3A: ${o}`),!0):(r(`\u672A\u5728\u4E0B\u62C9\u83DC\u5355\u4E2D\u627E\u5230\u76EE\u6807\u6A21\u578B: ${o}`),await this.page.keyboard.press("Escape"),!1)}catch(o){o("\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 r("\u672A\u627E\u5230\u6E29\u5EA6\u8BBE\u7F6E\u5BB9\u5668\uFF0C\u8DF3\u8FC7\u3002"),!1;let a=o.locator('input[type="number"]');return await a.count()>0?(await a.fill(e.toString()),await a.dispatchEvent("change"),r(`\u6E29\u5EA6\u5DF2\u8BBE\u7F6E\u4E3A: ${e}`),!0):(r("\u672A\u627E\u5230\u6E29\u5EA6\u6570\u5B57\u8F93\u5165\u6846\uFF0C\u8DF3\u8FC7\u8BBE\u7F6E\u3002"),!1)}catch(o){return o("\u8BBE\u7F6E\u6E29\u5EA6\u65F6\u51FA\u9519:",o),!1}}async processMessage(e,o={}){if(r("\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 r("\u6D88\u606F\u53D1\u9001\u6210\u529F\uFF0C\u7B49\u5F85\u7F51\u7EDC\u62E6\u622A\u83B7\u53D6\u54CD\u5E94\u3002"),!0}};P();var B=class{TARGET_URL_PATTERN=new RegExp("MakerSuiteService/GenerateContent");constructor(e,o,a){this.page=e,this.onStreamChunk=o,this.onStreamEnd=a,this.isActive=!1,this.routeHandler=this._handleRoute.bind(this)}async activate(){this.isActive||(r("[InterceptorV2] \u6FC0\u6D3B\u7F51\u7EDC\u8DEF\u7531\u62E6\u622A..."),await this.page.route(this.TARGET_URL_PATTERN,this.routeHandler),this.isActive=!0,r(`[InterceptorV2] \u62E6\u622A\u5668\u5DF2\u6FC0\u6D3B\uFF0C\u76D1\u542C URL pattern: ${this.TARGET_URL_PATTERN}`))}async deactivate(){if(this.isActive){r("[InterceptorV2] \u505C\u7528\u7F51\u7EDC\u8DEF\u7531\u62E6\u622A...");try{await this.page.unroute(this.TARGET_URL_PATTERN,this.routeHandler),this.isActive=!1,r("[InterceptorV2] \u62E6\u622A\u5668\u5DF2\u505C\u7528\u3002")}catch(e){g(`[InterceptorV2] \u505C\u7528\u62E6\u622A\u5668\u65F6\u51FA\u9519: ${e.message}`)}}}async _handleRoute(e,o){r(`[InterceptorV2] \u62E6\u622A\u5230\u76EE\u6807\u8BF7\u6C42: ${o.method()} ${o.url()}`);try{await e.fulfill({status:200,contentType:"application/json",body:JSON.stringify({message:"Request handled by backend interceptor."})}),r("[InterceptorV2] \u5DF2\u5411\u6D4F\u89C8\u5668\u53D1\u9001\u4F2A\u9020\u7684\u6210\u529F\u54CD\u5E94\u3002")}catch(a){g(`[InterceptorV2] Fulfill \u539F\u59CB\u8BF7\u6C42\u5931\u8D25: ${a.message}`),e.isFulfillable()&&await e.abort().catch(s=>g(`[InterceptorV2] Abort \u8BF7\u6C42\u4E5F\u5931\u8D25: ${s.message}`));return}try{r("[InterceptorV2] \u6B63\u5728\u4F7F\u7528 Node.js fetch \u91CD\u65B0\u53D1\u9001\u8BF7\u6C42...");let a=await o.headers();delete a["x-playwright-api-request"],delete a["content-length"];let s=await fetch(o.url(),{method:o.method(),headers:a,body:o.postDataBuffer()});if(!s.ok){let p=await s.text();this.onStreamChunk(p);return}if(!s.body)throw new Error("\u540E\u7AEF fetch \u54CD\u5E94\u4E2D\u6CA1\u6709 body\u3002");r("[InterceptorV2] \u5F00\u59CB\u4ECE\u540E\u7AEF fetch \u63A5\u6536\u6D41\u5F0F\u6570\u636E...");let n=s.body.getReader(),i=new TextDecoder;for(;;){let{done:p,value:m}=await n.read();if(p)break;let c=i.decode(m,{stream:!0});this.onStreamChunk(c)}r("[InterceptorV2] \u6D41\u63A5\u6536\u5B8C\u6BD5\u3002"),this.onStreamEnd()}catch(a){g("[InterceptorV2] \u540E\u7AEF\u5904\u7406\u8BF7\u6C42\u65F6\u53D1\u751F\u4E25\u91CD\u9519\u8BEF:",a),this.onStreamEnd()}}};P();function Ye(t){return t.includes("The caller does not have permission")?(E("\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 Xe(t){if(!Array.isArray(t))return null;let e=t[0];for(;Array.isArray(e)&&Array.isArray(e[0]);)e=e[0];return Array.isArray(e)&&e.length>=2&&e[0]===null&&typeof e[1]=="string"?e:null}function Qe(t){if(t.length===4&&t[0]===null&&t[1]===null&&t[2]===null)return{type:"done",content:"Stream finished"};if(t.length===3){let e=Xe(t);if(e){let o=e[1];return{type:e.length===2?"text":"thinking",content:o}}}return null}function Y(t){let e=Ye(t);if(e)return{parsedItems:[e],remainingBuffer:""};let o=[],a=/(\d+\s*\]\s*\]\s*),(\s*\[)/g,s="__ELEMENT_SEPARATOR__",i=t.replace(a,`$1,${s}$2`).split(s);if(i.length===1)return{parsedItems:[],remainingBuffer:t};let p=i.pop()||"",m=i;for(let c of m){let l=c.trim();l.endsWith(",")&&(l=l.slice(0,-1));let h=null,d=0,f=10;for(;d<f;)try{h=JSON.parse(l);break}catch(b){l=l.substring(1),d++,E(`\u89E3\u6790\u5143\u7D20\u5931\u8D25\uFF0C\u8DF3\u8FC7\u8BE5\u5757\u3002\u9519\u8BEF: ${b.message}, \u5143\u7D20\u5185\u5BB9: "${l}"`)}if(h){let b=Qe(h);b&&o.push(b)}}return{parsedItems:o,remainingBuffer:p}}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 X(t,e="gemini-pro"){return{object:"error",message:t,type:"invalid_request_error",model:e}}P();var G=3,Se=1e3;function Ze(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(a=>e.includes(a))}function et(t){let e=t.message.toLowerCase();return["permission","unauthorized","\u65E0\u6743\u8BBF\u95EE","cookie","\u767B\u5F55"].some(a=>e.includes(a))}async function Ee(t,e,o){let a=null,s=null;try{a=await L();for(let n=1;n<=G;n++)try{r(`\u{1F310} [\u5C1D\u8BD5 ${n}/${G}] \u5F00\u59CB\u5904\u7406\u8BF7\u6C42...`),await H(a,u.aiStudio.url,{timeout:u.aiStudio.pageTimeout});let i=await o(a,t,e);return await M(a),i}catch(i){if(s=i,E(`\u274C [\u5C1D\u8BD5 ${n}/${G}] \u5931\u8D25: ${i.message}`),(et(i)||Ze(i))&&n<G)r(`\u68C0\u6D4B\u5230\u53EF\u91CD\u8BD5\u7684\u9519\u8BEF\uFF08\u6743\u9650\u6216\u9875\u9762\u72B6\u6001\uFF09\uFF0C\u5C06\u5728 ${Se}ms \u540E\u91CD\u8BD5...`),await new Promise(p=>setTimeout(p,Se));else throw i("\u9519\u8BEF\u4E0D\u53EF\u91CD\u8BD5\u6216\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u5C06\u629B\u51FA\u5F02\u5E38\u3002"),i}}catch(n){throw n("\u5904\u7406 AI Studio \u8BF7\u6C42\u6700\u7EC8\u5931\u8D25:",n),a&&await M(a),s||n}}async function Pe(t,e,o={}){let a=o.model||u.api.defaultModel;try{await Ee(t,o,async(s,n,i)=>new Promise(async(p,m)=>{let c=!1,l=null,h="",d=w=>{c||(c=!0,l&&l.deactivate().catch(g),w?m(w):p())},f=w=>{if(c)return;h+=w;let{parsedItems:I,remainingBuffer:N}=Y(h);if(h=N,I.length>0)for(let S of I){if(S.permissionError)return d(new Error(S.content));if(S.type==="done"){b();return}S.content?.trim()&&e.enqueue(`data: ${JSON.stringify(be(S.content,S.type,a))}
|
|
|
|
|
14 |
|
15 |
+
`)}},b=()=>{c||(r("\u6D41\u5DF2\u7ED3\u675F\uFF0C\u53D1\u9001 [DONE] \u4FE1\u53F7\u3002"),e.enqueue(`data: [DONE]
|
16 |
|
17 |
+
`),e.close(),d())};try{l=new B(s,f,b),await l.activate(),await new _(s).processMessage(n,i),setTimeout(()=>{c||d(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},u.aiStudio.responseTimeout)}catch(w){d(w)}}))}catch(s){if(e.desiredSize!==null)try{e.enqueue(`data: ${JSON.stringify(X(s.message,a))}
|
18 |
|
19 |
`),e.enqueue(`data: [DONE]
|
20 |
|
21 |
+
`),e.close()}catch(n){s("\u5173\u95ED\u6D41\u63A7\u5236\u5668\u65F6\u51FA\u9519:",n)}}}async function xe(t,e={}){let o=e.model||u.api.defaultModel;try{return await Ee(t,e,async(a,s,n)=>new Promise(async(i,p)=>{let m="",c=async l=>{if(l.url().includes("GenerateContent"))try{let h=await l.text(),d=Y(h);if(d?.permissionError)return p(new Error(d.content));Array.isArray(d)&&(m+=d.filter(f=>f.type==="text").map(f=>f.content).join("")),a.removeListener("response",c),i(createNonStreamResponse(m,o))}catch(h){p(h)}};a.on("response",c);try{await new _(a).processMessage(s,n),setTimeout(()=>{a.removeListener("response",c),p(new Error("AI Studio \u54CD\u5E94\u8D85\u65F6\u3002"))},u.aiStudio.responseTimeout)}catch(l){a.removeListener("response",c),p(l)}}))}catch(a){return X(a.message,o)}}async function $e(t){try{ye(t);let e=await tt(t),{prompt:o,stream:a,model:s,temperature:n}=we(e);return a?(fe(t),new ReadableStream({start(p){Pe(o,p,{model:s,temperature:n})}})):await xe(o,{model:s,temperature:n})}catch(e){throw console.error("\u5904\u7406\u804A\u5929\u8BF7\u6C42\u65F6\u51FA\u9519:",e),e.statusCode?e:ot({statusCode:500,statusMessage:e.message||"An internal server error occurred."})}}import{createError as z}from"h3";async function ve(t){try{let e=Object.values(u.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,a)=>a.created-o.created),{object:"list",data:e}}catch(e){throw console.error("\u83B7\u53D6\u6A21\u578B\u5217\u8868\u65F6\u51FA\u9519:",e),z({statusCode:500,statusMessage:"Failed to retrieve models list."})}}async function Ie(t){try{let e=t.context.params?.model;if(!e)throw z({statusCode:400,statusMessage:"Model ID is required."});let o=u.models[e];if(!o)throw z({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:z({statusCode:500,statusMessage:"Failed to retrieve model information."})}}D();P();var v=new rt,Re=process.cwd();ue();v.use("*",he);v.get("/health",ge);v.get("/v1/models",ve);v.get("/v1/models/:model",Ie);v.post("/v1/chat/completions",$e);v.get("/screenshots/**",t=>{let e=t.path.substring(12),o=Me(Re,"screenshots",e);return Te(t,{getContents:()=>Ae(o),getMeta:async()=>{let a=await Ce(o).catch(()=>{});if(a?.isFile())return{size:a.size,mtime:a.mtimeMs}}})});v.get("/**",t=>{let e=t.path==="/"?"index.html":t.path,o=Me(Re,"public",e);return Te(t,{getContents:()=>Ae(o),getMeta:async()=>{let a=await Ce(o).catch(()=>{});if(a?.isFile())return{size:a.size,mtime:a.mtimeMs}}})});r("\u{1F527} \u521D\u59CB\u5316\u9875\u9762\u6C60...");ne(5);process.env.NODE_ENV!=="production"&&(r("\u{1F4CA} \u542F\u52A8\u9875\u9762\u6C60\u76D1\u63A7..."),pe(1e4));var O=u.server.port,k=u.server.host;at(v,{port:O,host:k});r(`\u{1F680} \u670D\u52A1\u5668\u8FD0\u884C\u5728 http://${k}:${O}`);r(`\u{1F3E0} \u7BA1\u7406\u9762\u677F: http://${k}:${O}/`);r(`\u{1F4CB} \u5065\u5EB7\u68C0\u67E5: http://${k}:${O}/health`);r(`\u{1F4AC} \u804A\u5929\u7AEF\u70B9: http://${k}:${O}/v1/chat/completions`);r(`\u{1F3AF} AI Studio URL: ${u.aiStudio.url}`);r(`\u{1F30D} \u73AF\u5883: ${process.env.NODE_ENV||"development"}`);async function st(){let t;try{r("\u{1F4F8} \u5F00\u59CB\u83B7\u53D6AI Studio\u9875\u9762\u622A\u56FE..."),t=await L(),r(`\u667A\u80FD\u5BFC\u822A\u5230: ${u.aiStudio.url}`),await H(t,u.aiStudio.url,{timeout:u.aiStudio.pageTimeout}),await U(t),await t.waitForTimeout(2e3);let e=await W(t,"./screenshots","aistudio-startup",!1);r(`\u2705 AI Studio\u622A\u56FE\u5DF2\u4FDD\u5B58: ${e}`)}catch(e){g("\u274C \u622A\u56FEAI Studio\u9875\u9762\u65F6\u51FA\u9519:",e.message)}finally{t&&(await M(t),r("\u{1F504} \u9875\u9762\u5DF2\u91CA\u653E\u56DE\u6C60\u4E2D"))}}setTimeout(()=>{r(`
|
22 |
\u{1F4CA} \u521D\u59CB\u9875\u9762\u6C60\u72B6\u6001:`),de()},1e3);setTimeout(()=>{st()},2e3);
|