Spaces:
Running
Running
github-actions[bot]
commited on
Commit
·
42bab47
1
Parent(s):
f89e0a1
Deploy: Update from GitHub Actions build
Browse files- dist/index.js +1 -1
dist/index.js
CHANGED
@@ -10,7 +10,7 @@ var _e=Object.defineProperty;var te=(t,e)=>()=>(t&&(e=t(t=0)),e);var Oe=(t,e)=>{
|
|
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 |
|
|
|
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=3;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 |
|