@doubao-dev/cli 0.0.25 → 0.0.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/2168.js +60 -0
- package/dist/275.js +25 -0
- package/dist/{4091.js → 2861.js} +14 -14
- package/dist/2932.js +1 -1
- package/dist/318.js +1 -1
- package/dist/3768.js +1 -0
- package/dist/3974.js +10 -10
- package/dist/4931.js +2 -2
- package/dist/6780.js +7 -0
- package/dist/{react.js → 6831.js} +1 -1
- package/dist/7410.js +1 -1
- package/dist/@byted-doubao-apps/create.js +1 -1
- package/dist/@byted-doubao-apps/login.js +1 -1
- package/dist/@byted-doubao-apps/login~1.js +1 -1
- package/dist/@byted-doubao-apps/template-empty/package.json +3 -3
- package/dist/@byted-doubao-apps/template-starter/package.json +3 -3
- package/dist/@byted-hdt/cli.js +1 -1
- package/dist/@inquirer/select.js +1 -1
- package/dist/app.js +1 -1
- package/dist/assets/web-sdk-debugger/index.html +1 -1
- package/dist/assets/web-sdk-debugger/static/css/index.cc3b255797.css +1 -0
- package/dist/assets/web-sdk-debugger/static/js/index.b85cbec3be.js +26 -0
- package/dist/assets/web-sdk-debugger/wsd/doubao-apps-api.template.js +0 -0
- package/dist/assets/web-sdk-debugger/wsd/doubao-apps-framework.template.js +0 -0
- package/dist/browser.js +1 -1
- package/dist/dbx-demo.js +1 -1
- package/dist/dbx.js +2 -2
- package/dist/demo-server.js +2 -2
- package/dist/dev-config.js +2 -2
- package/dist/dev-service-client.js +1 -25
- package/dist/dev-shell.js +1 -1
- package/dist/dev.js +10 -10
- package/dist/eval.js +1 -1
- package/dist/gen-explore.js +1 -1
- package/dist/gen-trajectory.js +1 -1
- package/dist/get.js +1 -1
- package/dist/init.js +4 -4
- package/dist/ink.js +3 -3
- package/dist/json-file.js +1 -1
- package/dist/login.js +1 -1
- package/dist/main.js +1 -1
- package/dist/manifest-mcp-config.js +1 -1
- package/dist/ora.js +1 -1
- package/dist/portal.js +1 -1
- package/dist/project-layout.js +1 -1
- package/dist/prompt.js +7 -7
- package/dist/prompts.js +1 -1
- package/dist/report.js +1 -1
- package/dist/run-registry.js +1 -1
- package/dist/run.js +121 -121
- package/dist/sandbox.js +1 -1
- package/dist/scan.js +1 -1
- package/dist/sdk.js +20 -20
- package/dist/sdk~1.js +20 -20
- package/dist/server.js +4 -4
- package/dist/simulator-client.js +1 -1
- package/dist/skill.js +1 -1
- package/dist/skills.js +1 -1
- package/dist/skills~2.js +1 -1
- package/dist/status.js +2 -2
- package/dist/status~1.js +1 -1
- package/dist/stop.js +1 -1
- package/dist/update.js +1 -1
- package/dist/upgrade.js +1 -1
- package/dist/upload.js +6 -6
- package/dist/validate.js +1 -1
- package/dist/workspace.js +1 -1
- package/dist/yaml.js +1 -1
- package/package.json +2 -2
- package/dist/1664.js +0 -66
- package/dist/assets/web-sdk-debugger/static/css/index.3fba1d83fd.css +0 -1
- package/dist/assets/web-sdk-debugger/static/js/index.c19e6628b4.js +0 -26
- /package/dist/{dev-service-client.js.LICENSE.txt → 275.js.LICENSE.txt} +0 -0
- /package/dist/{4091.js.LICENSE.txt → 2861.js.LICENSE.txt} +0 -0
- /package/dist/{react.js.LICENSE.txt → 6831.js.LICENSE.txt} +0 -0
package/dist/3974.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var e;let t,r;import"node:module";import{__webpack_require__ as n}from"./rslib-runtime.js";import{authorizedFetch as o,http_getApiBaseUrl as a,isRecord as i}from"./
|
|
2
|
-
`,"utf8")}catch(e){if(!M){M=!0;let t=e.code||"unknown";console.error(`[logger] 日志写入失败(${t});后续同类错误将静默处理。`)}}}function
|
|
3
|
-
`,"utf8");try{o=(0,U.spawn)(process.execPath,(t=function(){let e=process.argv[1];if(!e)throw Error("Unable to resolve the DBX CLI entry point.");return(0,x.resolve)(e)}(),r=p,[t,"eval","run","--internal-dev-runtime",r]),{cwd:d,detached:"win32"!==process.platform,env:{...process.env,DBX_CLI_NO_UPDATE_NOTIFIER:"1"},stdio:["ignore","inherit","inherit","ipc"]})}catch(e){throw u.cleanup(),e}let m=!1,f=!1,g=new Promise((e,t)=>{i=e,s=t}),_=new Promise((e,t)=>{l=t});_.catch(()=>void 0),o.on("message",e=>{if(e&&"object"==typeof e){if("log"===e.type){let t=`[eval-dev-runtime] ${e.message}`;"warn"===e.level?L.warn(t):L.log(t);return}if("failure"===e.type){a=e.message,m||s?.(Error(e.message));return}"ready"===e.type&&(m=!0,i?.(e.webDebuggerUrl))}}),o.once("error",e=>{m?l?.(e):s?.(e)});let h=new Promise(e=>{o.once("exit",(t,r)=>{let n={code:t,signal:r};if(e(n),W(o),u.cleanup(),f)return;let i=new q({...n,detail:a});m?l?.(i):s?.(i)})});try{c=await (n=g,new Promise((e,t)=>{let r=setTimeout(()=>t(Error(`eval dev runtime startup timed out after ${9e4}ms`)),9e4);n.then(t=>{clearTimeout(r),e(t)},e=>{clearTimeout(r),t(e)})}))}catch(e){throw f=!0,await G(o,h),u.cleanup(),e}return{webDebuggerUrl:c,unexpectedExit:_,stop:async()=>{f||(f=!0,o.connected&&o.send({type:"stop"}),await G(o,h,15e3),u.cleanup())}}}function z(e){return new Promise(t=>setTimeout(t,e))}async function G(e,t,r=0){!(r>0&&await Promise.race([t.then(()=>!0),z(r).then(()=>!1)]))&&(e.kill("SIGTERM"),W(e),await Promise.race([t.then(()=>!0),z(3e3).then(()=>!1)])||(e.kill("SIGKILL"),W(e,"SIGKILL"),await Promise.race([t,z(1e3)])))}function W(e,t="SIGTERM"){if("win32"!==process.platform&&e.pid)try{process.kill(-e.pid,t)}catch{}}function X(e,t,r){if(t?.toLowerCase().includes("text/event-stream")){let t=function(e){let t=[],r=[],n=()=>{if(0===r.length)return;let e=r.join("\n").trim();e&&"[DONE]"!==e&&t.push(JSON.parse(e)),r=[]};for(let t of e.split(/\r?\n/)){if(""===t){n();continue}t.startsWith("data:")&&r.push(t.slice(5).trimStart())}return n(),t}(e),n=t.find(e=>{var t,n;return t=e,null!==(n=r)&&Z(t)&&t.id===n})??t.find(Z);if(!n)throw Error("MCP SSE response has no JSON-RPC response");return n}return JSON.parse(e)}function Z(e){return!!(e&&"object"==typeof e&&"id"in e&&("result"in e||"error"in e))}let Y="2025-11-25",Q=["application/json","text/event-stream"];async function ee(e,t,r){let n=await et(e,t,r);try{return{tools:n.tools,manifest:n.manifest,skills:n.skills}}finally{n.close()}}async function et(e,t,r){return new URL(e).pathname.replace(/\/+$/,"").toLowerCase().endsWith("/sse")?en(e,t,r):er(e,t,r)}async function er(e,t,r){let n,o=(("/"===(n=new URL(e)).pathname||""===n.pathname)&&(n.pathname="/mcp"),n.toString());try{let e=await em(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:Y,capabilities:{},clientInfo:{name:"dbx-simulator-eval",version:"0.1.0"}}},{headers:r}),n=e.body.result?.protocolVersion??Y,a=e.headers.get("mcp-session-id")??void 0;await em(o,{jsonrpc:"2.0",method:"notifications/initialized",params:{}},{sessionID:a,protocolVersion:n,allowEmpty:!0,headers:r});let i=await em(o,{jsonrpc:"2.0",id:2,method:"tools/list",params:{}},{sessionID:a,protocolVersion:n,headers:r});return eo({kind:"streamable",url:o,sessionID:a,protocolVersion:n,headers:r},{tools:{server_id:e_(o),name:e_(o),description:"Standard MCP Streamable HTTP server",app_key:t,protocol:"streamable_http",tools:(i.body.result?.tools??[]).map(e=>({name:e.name,description:e.description??"",input_schema_json:JSON.stringify(e.inputSchema??e.input_schema??{}),output_schema_json:JSON.stringify(e.outputSchema??e.output_schema??{})}))}})}catch(e){throw Error(`MCP Streamable HTTP 初始化失败(${eg(e)})`)}}async function en(e,t,r){let n=new URL(e).toString(),o={kind:"sse",url:n,pending:new Map,headers:r};try{await es(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"dbx-simulator-eval",version:"0.1.0"}}},!1),await es(o,{jsonrpc:"2.0",method:"notifications/initialized",params:{}},!0);let e=await es(o,{jsonrpc:"2.0",id:2,method:"tools/list",params:{}},!1);return eo(o,{tools:{server_id:e_(n),name:e_(n),description:"Standard MCP SSE server",app_key:t,protocol:"sse",tools:(e.result?.tools??[]).map(e=>({name:e.name,description:e.description??"",input_schema_json:JSON.stringify(e.inputSchema??e.input_schema??{}),output_schema_json:JSON.stringify(e.outputSchema??e.output_schema??{})}))}})}catch(e){throw ep(o),Error(`MCP SSE 初始化失败(${eg(e)})`)}}function eo(e,t){let r=!1;return{...t,async callTool(t){if(r)throw Error("MCP client is closed");return function(e){var t;let r=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;let{_response_meta:t,...r}=e;return r}(e);if(!r||"object"!=typeof r){let e=String(r??"");return{content:e,raw_result_text:e,raw_mcp_result_json:e}}if("string"==typeof r.content||"raw_mcp_result_json"in r||"raw_result_text"in r||"structured"in r){let e="string"==typeof r.content?r.content:JSON.stringify(r.content??""),t=r.raw_mcp_result_json||r.raw_result_text||e;return{...r,content:e,raw_result_text:r.raw_result_text||t,raw_mcp_result_json:r.raw_mcp_result_json||t,structured:r.structured??r.structuredContent,is_error:r.is_error??r.isError}}let n=JSON.stringify(r);return{content:n,structured:r.structuredContent,raw_result_text:n,raw_mcp_result_json:n,is_error:!0===r.isError,miniapp:(t=r,Array.isArray(t?.content)&&t?.structuredContent&&"object"==typeof t.structuredContent)?{is_mini_app:!0,mcp_channel:"flow_miniapp"}:void 0}}("sse"===e.kind?await ei(e,t):await ea(e,t))},close(){r||(r=!0,"sse"===e.kind&&ep(e))}}}async function ea(e,t){let r=ew(t.tool_name);if(!r)throw Error("MCP tool name is empty");return(await em(e.url,{jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:r,arguments:e$(t.arguments)??ev(ew(t.arguments_json))??{}}},{sessionID:e.sessionID,protocolVersion:e.protocolVersion,headers:e.headers})).body.result}async function ei(e,t){let r=ew(t.tool_name);if(!r)throw Error("MCP tool name is empty");return(await es(e,{jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:r,arguments:e$(t.arguments)??ev(ew(t.arguments_json))??{}}},!1)).result}async function es(e,t,r){let n;if(await el(e),!e.endpointURL)throw Error("MCP SSE did not provide endpoint event");let o=eh(t),a=ey(t)||"unknown",i=eb(t),s=i?`${a}:${i}`:a,l=null!==o,c=l?new Promise((t,r)=>{let n=setTimeout(()=>{e.pending.delete(o),r(Error(`MCP SSE request timed out: ${s}`))},1e4);e.pending.set(o,{resolve:t,reject:r,timeout:n})}):void 0;try{var u;let r;n=await ef(e.endpointURL,{method:"POST",headers:(u=e.headers,(r=new Headers(u)).set("Content-Type","application/json"),r),body:JSON.stringify(t)},1e4,`MCP SSE POST ${s}`)}catch(t){throw l&&ed(e,o),t}if(!n.ok)throw l&&ed(e,o),await n.body?.cancel(),Error(`MCP SSE 请求失败(HTTP ${n.status})`);if(await n.text(),!l)return{};let d=await c;if(!d&&!r)throw Error("MCP SSE returned empty response");if(d?.error)throw Error(`MCP SSE 请求失败(错误码 ${d.error.code})`);return d}async function el(e){if(e.ready)return e.ready;let t=new AbortController;return e.abortController=t,e.ready=new Promise((r,n)=>{let o=!1,a=setTimeout(()=>{t.abort(),i(Error("MCP SSE endpoint event timed out"))},1e4),i=e=>{o||(o=!0,clearTimeout(a),n(e))};ec(e,t,t=>{e.endpointURL=new URL(t,e.url).toString(),o||(o=!0,clearTimeout(a),r())},i)}).catch(t=>{throw ep(e,t),t}),e.ready}async function ec(e,t,r,n){try{var o;let a,i=await fetch(e.url,{method:"GET",headers:(o=e.headers,(a=new Headers(o)).set("Accept","text/event-stream"),a),signal:t.signal});if(!i.ok||!i.body){await i.body?.cancel(),n(Error(`MCP SSE 连接失败(HTTP ${i.status})`));return}if(!String(i.headers.get("content-type")??"").toLowerCase().includes("text/event-stream"))return void n(Error(`MCP SSE GET content-type=${i.headers.get("content-type")??"-"}`));await eu(e,i.body,r),t.signal.aborted||ep(e,Error("MCP SSE stream closed"))}catch(r){if(!t.signal.aborted){let t=r instanceof Error?r:Error(String(r));n(t),ep(e,t)}}}async function eu(e,t,r){let n=t.getReader(),o=new TextDecoder,a="",i="message",s=[],l=()=>{if(0===s.length){i="message";return}(function(e,t,r,n){let o;if("endpoint"===t)return n(r.trim());if(!r.trim())return;try{o=JSON.parse(r)}catch{return}let a=o.id;if(null==a)return;let i=e.pending.get(a);i&&(clearTimeout(i.timeout),e.pending.delete(a),i.resolve(o))})(e,i,s.join("\n"),r),i="message",s=[]};for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=(a+=o.decode(t,{stream:!0})).search(/\r?\n/);for(;r>=0;){let e=a.slice(0,r).replace(/\r$/,"");a=a.slice(r+("\r"===a[r]&&"\n"===a[r+1]?2:1)),""===e?l():e.startsWith("event:")?i=e.slice(6).trim():e.startsWith("data:")&&s.push(e.slice(5).trimStart()),r=a.search(/\r?\n/)}}a&&s.push(a),l()}function ed(e,t){if(null===t)return;let r=e.pending.get(t);r&&(clearTimeout(r.timeout),e.pending.delete(t))}function ep(e,t=Error("MCP SSE session closed")){for(let[r,n]of(e.abortController?.abort(),e.abortController=void 0,e.endpointURL=void 0,e.ready=void 0,e.pending.entries()))clearTimeout(n.timeout),n.reject(t),e.pending.delete(r)}async function em(e,t,r){var n,o;let a,i,s,l=ey(t)||"unknown",c=eb(t),u=c?`${l}:${c}`:l,d=await ef(e,{method:"POST",headers:(n=t,(a=new Headers((o=r).headers)).set("Content-Type","application/json"),a.set("Accept",Q.join(", ")),(i=ey(n))&&a.set("Mcp-Method",i),(s=eb(n))&&a.set("Mcp-Name",s),o.protocolVersion&&a.set("MCP-Protocol-Version",o.protocolVersion),o.sessionID&&a.set("Mcp-Session-Id",o.sessionID),a),body:JSON.stringify(t)},1e4,`MCP Streamable HTTP ${u}`);if(!d.ok)throw await d.body?.cancel(),Error(`MCP Streamable HTTP 请求失败(HTTP ${d.status})`);let p=await d.text();if(!p&&r.allowEmpty)return{body:{},headers:d.headers};if(!p)throw Error("MCP Streamable HTTP returned empty response");let m=X(p,d.headers.get("content-type"),eh(t));if(m.error)throw Error(`MCP Streamable HTTP 请求失败(错误码 ${m.error.code})`);return{body:m,headers:d.headers}}async function ef(e,t,r,n){let o=new AbortController,a=setTimeout(()=>o.abort(),r),i=Date.now(),s=function(e){let t=e.match(/\btools\/call:([^\s]+)/);if(t){let e=t[1];return{start:`正在调用 MCP 工具:${e}`,done:`MCP 工具调用完成:${e}`,failed:`MCP 工具调用失败:${e}`}}return e.includes("tools/list")?{start:"正在获取 MCP 工具列表",done:"MCP 工具列表获取完成",failed:"MCP 工具列表获取失败"}:e.includes("notifications/initialized")?{start:"正在完成 MCP 初始化",done:"MCP 初始化通知完成",failed:"MCP 初始化通知失败"}:{start:"正在连接 MCP 服务",done:"MCP 请求完成",failed:"MCP 请求失败"}}(n);L.log(`[mcp-http] ${s.start}`);try{let r=await fetch(e,{...t,signal:o.signal});return L.log(`[mcp-http] ${s.done}(HTTP ${r.status},耗时 ${J(Date.now()-i)})`),r}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw L.warn(`[mcp-http] ${s.failed}(超时 ${J(r)})`),Error(`MCP 请求超时(${J(r)})`);throw L.warn(`[mcp-http] ${s.failed}(${eg(e)},耗时 ${J(Date.now()-i)})`),Error(`MCP 请求失败(${eg(e)})`)}finally{clearTimeout(a)}}function eg(e){let t=e instanceof Error&&e.name?e.name:"MCPRequestError",r=e instanceof Error?e.message:String(e),n=r.match(/\bHTTP\s+(\d{3})\b/i)?.[1],o=r.match(/错误码\s+(-?\d+)/)?.[1];return n?`${t},HTTP ${n}`:o?`${t},错误码 ${o}`:t}function e_(e){let t=new URL(e);return`${t.hostname}_${t.port||t.protocol.replace(":","")}${t.pathname.replace(/[^A-Za-z0-9_-]/g,"_")}`}function eh(e){return e&&"object"==typeof e&&"id"in e?e.id??null:null}function ey(e){if(e&&"object"==typeof e&&"method"in e)return e.method}function eb(e){if(!e||"object"!=typeof e)return;let t=e.params;return t&&"object"==typeof t?"string"==typeof t.name?t.name:"string"==typeof t.uri?t.uri:void 0:void 0}function ew(e){return"string"==typeof e?e:""}function e$(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function ev(e){if(e)try{return JSON.parse(e)}catch{return}}let eS=n("node:crypto"),eE="dbx-eval",ej=Symbol("dbx.eval.llm-request-diagnostic"),ek="app_quota_exhausted";function ex(e){let t=e.baseUrl?.trim(),r=e.apiKey?.trim();return t&&r?{url:`${t.replace(/\/+$/,"")}/chat/completions`,fetch:globalThis.fetch,authHeader:`Bearer ${r}`,backend:"openai",transport:"json"}:{url:`${a().replace(/\/+$/,"")}/app_developer/api/v1/chat/completions`,fetch:o,backend:"gateway",transport:"sse"}}function eP(e){return e.model||eE}class eC extends Error{backend;transport;url;httpStatus;responseMessage;responseCode;logId;retryable;attempts;partialContentReceived;streamEvent;constructor(e){super(e.message),void 0!==e.cause&&(this.cause=e.cause),this.name="LLMResponseError",this.backend=e.backend,this.transport=e.transport,this.url=e.url,this.httpStatus=e.httpStatus,this.responseMessage=e.responseMessage,this.responseCode=e.responseCode,this.logId=e.logId,this.retryable=e.retryable,this.attempts=e.attempts,this.partialContentReceived=e.partialContentReceived??!1,this.streamEvent=e.streamEvent}}class eI extends Error{timeoutMs;url;constructor(e,t){super(`LLM request timed out after ${e}ms`),this.timeoutMs=e,this.url=t,this.name="LLMRequestTimeoutError"}}function eA(e){if(e&&("object"==typeof e||"function"==typeof e))return e[ej]}function eT(e){return e instanceof eC?"gateway"===e.backend&&(401===e.httpStatus||403===e.httpStatus):eF(e)}function eM(e){return e instanceof eC&&429===e.httpStatus&&e.responseCode===ek}class eO{config;defaultSignal;constructor(e,t){this.config=e,this.defaultSignal=t}async chatCompletion(e,t){let r=t?.response_format?.type==="json_object"?eq(e):e,n=ex(this.config),o=t?.response_format?.type==="json_object",a=eP(this.config),i=eL(t?.request_context);L.log(`[llm] ▶ 正在${i} backend=${n.backend} model=${a} msgs=${r.length} json=${o}`);let s=Date.now(),l=t?.timeout_ms,c=new AbortController,u=!1,d=l&&l>0?setTimeout(()=>{u=!0,c.abort()},l):void 0,p=()=>c.abort(this.defaultSignal?.reason);this.defaultSignal?.aborted?p():this.defaultSignal?.addEventListener("abort",p,{once:!0});let m={...t,signal:c.signal};try{let e=await this.openaiCall(n,r,m);return L.log(`[llm] ✔ ${i}完成 backend=${n.backend} model=${a} in=${J(Date.now()-s)} chars=${e.length}`),e}catch(o){let e=u?new eI(l??0,n.url):o;throw u&&eR(e,{...eA(o)??this.describeRequest(r,t),error_type:e.name}),L.error(`[llm] ✘ ${i}失败 backend=${n.backend} model=${a} after=${J(Date.now()-s)} ${eJ(e)}`),e}finally{d&&clearTimeout(d),this.defaultSignal?.removeEventListener("abort",p)}}describeRequest(e,t){let r=t?.response_format?.type==="json_object"?eq(e):e,n=ex(this.config),o=this.buildRequestBody(n,r,t);return eN(n,eP(this.config),o,t)}async openaiCall(e,t,r){let n,o=Math.max(1,r?.max_http_attempts??3),a=this.buildRequestBody(e,t,r),i=eN(e,eP(this.config),a,r);if("gateway"===e.backend){let t=this.config.appKey?.trim();if(!t){let t=new eC({backend:e.backend,transport:e.transport,message:"LLM gateway request is missing app_key; set app_key in manifest.yaml (or --app-id) so the eval pipeline can attribute the request.",url:e.url,retryable:!1,attempts:1});throw eR(t,{...i,attempts:1,retry_count:0,retryable:!1,error_type:t.name}),t}a.app_key=t}let s=JSON.stringify(a),l=eL(r?.request_context);for(let t=0;t<o;t++){let a=Date.now();L.log(`[llm-http] ▶ 正在${l} attempt=${t+1}/${o} transport=${e.transport}`);try{let n,i={"Content-Type":"application/json"};e.authHeader&&(i.Authorization=e.authHeader);try{n=await e.fetch(e.url,{method:"POST",headers:i,body:s,signal:r?.signal})}catch(r){if("gateway"===e.backend&&eF(r)){var c,u,d;throw c=e,u=r,d=t+1,new eC({backend:c.backend,transport:c.transport,message:"LLM Gateway authentication failed",url:c.url,httpStatus:401,responseMessage:"authentication failed",retryable:!1,attempts:d,cause:u})}throw r}let p=J(Date.now()-a);if(!n.ok){let a=await this.errorFromResponse(e,n,t+1,!1);if(L.warn(`[llm-http] ✘ ${l}失败 HTTP=${n.status} in=${p} attempt=${t+1}/${o} ${eJ(a)}`),a.retryable&&(429===n.status||n.status>=500)&&t<o-1&&!r?.signal?.aborted){await eH(2**t*1e3,r?.signal);continue}throw a}L.log(`[llm-http] ✔ ${l}请求完成 HTTP=${n.status} in=${p} attempt=${t+1}/${o}`);let m="sse"===e.transport?await this.parseSSEStream(n,e,t+1):await this.parseJsonResponse(n,e,t+1);return L.log(`[llm-http] ${l}响应解析完成 in=${J(Date.now()-a)} attempt=${t+1}/${o}`),m}catch(s){if(eR(n=s,{...i,attempts:s instanceof eC?s.attempts:t+1,retry_count:Math.max(0,(s instanceof eC?s.attempts:t+1)-1),retryable:!(s instanceof eC)||s.retryable,http_status:s instanceof eC?s.httpStatus:void 0,response_code:s instanceof eC?s.responseCode:void 0,log_id:s instanceof eC?s.logId:void 0,error_type:s instanceof Error?s.name:typeof s}),L.warn(`[llm-http] ✘ ${l}失败 attempt=${t+1}/${o} after=${J(Date.now()-a)} ${eJ(n)}`),r?.signal?.aborted)throw r.signal.reason instanceof Error?r.signal.reason:n;let e=!(s instanceof eC)||s.retryable;if(t<o-1&&e){await eH(2**t*1e3,r?.signal);continue}throw n}}throw n??Error("LLM request failed after retries")}buildRequestBody(e,t,r){let n={messages:t,temperature:r?.temperature??this.config.temperature??.7,...r?.response_format?{response_format:r.response_format}:{}};return"openai"===e.backend&&(n.max_tokens=r?.max_tokens??this.config.maxTokens??4096),"gateway"===e.backend&&this.config.appKey?.trim()&&(n.app_key=this.config.appKey.trim()),this.config.model&&(n.model=this.config.model),n.stream="sse"===e.transport,n}async parseJsonResponse(e,t,r){let n;try{n=await e.json()}catch(n){throw new eC({backend:t.backend,transport:t.transport,message:"LLM returned invalid JSON",url:t.url,logId:eU(e),retryable:!0,attempts:r,cause:n})}let o=n.choices?.[0]?.message?.content;if(!o)throw new eC({backend:t.backend,transport:t.transport,message:"LLM returned an empty response payload",url:t.url,logId:eU(e),retryable:!1,attempts:r});return o}async parseSSEStream(e,t,r){if(!e.body)throw new eC({backend:t.backend,transport:t.transport,message:"SSE response body is null",url:t.url,logId:eU(e),retryable:!0,attempts:r});let n=e.body.getReader(),o=new TextDecoder,a="",i="",s=!1,l="",c=!1,u=!1;for(;!u;){let d;try{let e=await n.read();u=e.done,d=e.value}catch(n){throw i&&(c=!0),new eC({backend:t.backend,transport:t.transport,message:"SSE stream disconnected",url:t.url,logId:eU(e),retryable:!0,attempts:r,partialContentReceived:c,streamEvent:l,cause:n})}if(!d)continue;let p=(a+=o.decode(d,{stream:!u})).split(/\r?\n/);a=p.pop()??"";let m=l;for(let n of p){let o,a=n.trim();if(""===a){m="";continue}if(a.startsWith(":"))continue;if(a.startsWith("event:")){l=m=a.slice(6).trim();continue}if(!a.startsWith("data:"))continue;let u=a.slice(5).trim();if(""===u)continue;if("[DONE]"===u){s=!0;continue}try{o=JSON.parse(u)}catch(n){throw new eC({backend:t.backend,transport:t.transport,message:"SSE data is not valid JSON",url:t.url,logId:eU(e),retryable:!0,attempts:r,streamEvent:m,cause:n})}if("error"===m||o.error){let n=o.error;throw new eC({backend:t.backend,transport:t.transport,message:"LLM stream returned an error event",url:t.url,httpStatus:e.status,responseMessage:n?.message,logId:o.log_id??o.logId??eU(e),retryable:!1,attempts:r,streamEvent:m||"error"})}let d=o.choices,p=d?.[0]?.delta?.content;p&&(i+=p,c=!0)}}if(!s)throw new eC({backend:t.backend,transport:t.transport,message:"SSE stream ended without a [DONE] marker",url:t.url,logId:eU(e),retryable:!0,attempts:r,partialContentReceived:c,streamEvent:l});if(!i)throw new eC({backend:t.backend,transport:t.transport,message:"LLM returned empty stream response",url:t.url,logId:eU(e),retryable:!1,attempts:r,streamEvent:l});return i}async errorFromResponse(e,t,r,n){let o,a,i=eU(t),s="";try{s=await t.text()}catch{s=""}try{let e=JSON.parse(s);o=e.error?.message??e.message,a=e.error?.code??e.code}catch{o=s.length>2e3?`${s.slice(0,2e3)}...`:s}let l=(429!==t.status||a!==ek)&&(429===t.status||t.status>=500);return new eC({backend:e.backend,transport:e.transport,message:`LLM API error: HTTP ${t.status}`,url:e.url,httpStatus:t.status,responseMessage:o,responseCode:a,logId:i,retryable:l,attempts:r,partialContentReceived:n})}}function eN(e,t,r,n){var o,a;let i=eD(n?.request_context);return{stage:i.stage,label:i.label,prompt_source:i.promptSource,backend:e.backend,transport:e.transport,model:t,request_body:(o=r,a=i.promptSource,Object.fromEntries(Object.entries(o).map(([e,t])=>"messages"===e&&Array.isArray(t)?[e,t.map(e=>{var t,r;return t=e,r=a,{role:t.role,content:`<已脱敏:${r}>`,content_length:t.content.length,content_sha256:(0,eS.createHash)("sha256").update(t.content).digest("hex")}})]:/^(?:app_key|api_key|authorization|token|headers?)$/i.test(e)?[e,"<已脱敏>"]:[e,t]))),max_http_attempts:Math.max(1,n?.max_http_attempts??3)}}function eD(e){return{stage:v(e?.stage||"llm:completion"),label:v(e?.label||"生成 LLM 响应"),promptSource:v(e?.promptSource||"未标注的 Prompt 来源")}}function eL(e){return eD(e).label.replace(/^正在/,"")}function eR(e,t){if(e&&("object"==typeof e||"function"==typeof e))try{Object.defineProperty(e,ej,{configurable:!0,value:t})}catch{}}function eJ(e){let t=[`error=${e instanceof Error?e.name:typeof e}`];return e instanceof eC&&(void 0!==e.httpStatus&&t.push(`http=${e.httpStatus}`),e.responseCode&&t.push(`code=${v(e.responseCode)}`),t.push(`retryable=${e.retryable}`),t.push(`attempts=${e.attempts}`),e.logId&&t.push(`logid=${v(e.logId)}`)),t.join(" ")}function eU(e){return e.headers.get("x-tt-logid")??void 0}function eF(e){if(!e||"object"!=typeof e)return!1;let t=String(e.name??e.constructor?.name??""),r=String(e.code??""),n=String(e.message??"").toLowerCase();return"NotLoggedInError"===t||"TokenExpiredError"===t||"NOT_LOGGED_IN"===r||"TOKEN_EXPIRED"===r||n.includes("login token has expired")||"not logged in"===n}function eH(e,t){return t?.aborted?Promise.reject(t.reason):new Promise((r,n)=>{let o=setTimeout(function(){t?.removeEventListener("abort",a),r()},e);function a(){clearTimeout(o),n(t?.reason)}t?.addEventListener("abort",a,{once:!0})})}function eq(e){return e.some(e=>/\bjson\b/.test(e.content))?e:e.map((t,r)=>r===e.length-1?{...t,content:`${t.content}
|
|
1
|
+
var e;let t,r;import"node:module";import{__webpack_require__ as n}from"./rslib-runtime.js";import"./3768.js";import"./yaml.js";import{authorizedFetch as o,http_getApiBaseUrl as a,isRecord as i}from"./2168.js";import{atomicWriteJson as s}from"./json-file.js";import{SimulatorHTTPError as l,SimulatorStreamError as c,runSimulatorStream as u}from"./simulator-client.js";import{resolveDevSimulatorPaths as d,validateDevManifest as p,resolveDevMcpEndpoint as m}from"./dev-config.js";import{readManifestAppKey as f,resolveAppKey as g}from"./workspace.js";import{readDbxConfig as _}from"./dbx.js";import{requireRuntimeSkillEntries as h,runtime_skill_layout_resolveRuntimeSkillLayout as y}from"./project-layout.js";let b="<已隐藏>",w=/^(?:api[_-]?key|authorization|bearer|token|headers?|prompt|messages?|body|arguments?|arguments_json|result|raw_result_text|raw_mcp_result_json|content)$/i;function $(e){return e instanceof Error?`${e.name}: ${v(e.message)}`:"string"==typeof e?v(e):Array.isArray(e)?e.map(e=>$(e)):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,w.test(e)?b:$(t)])):e}function v(e){return e.replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,"Bearer <已隐藏>").replace(/("?(?:api[_-]?key|authorization|token|secret|cookie)"?\s*[=:]\s*)("?)[^\s,;}]+/gi,"$1$2<已隐藏>").replace(/(\b(?:body|prompt|messages?|arguments?|result|content)"?\s*[=:]\s*).*$/gi,"$1<已隐藏>").replace(/https?:\/\/[^\s\])}"']+/gi,"<接口地址已隐藏>").replace(/(?:\/[A-Za-z0-9._-]+){3,}(?:\.[A-Za-z0-9._-]+)?/g,"<本地路径已隐藏>").replace(/[A-Za-z]:\\(?:[^\s\\]+\\){2,}[^\s,;]*/g,"<本地路径已隐藏>")}function S(e,t){return/意图|用户输入|入参|结果|目录|路径|prompt|message|body|argument/i.test(e)?[e,b]:[e,$(t)]}function E(e){let t=e instanceof Error&&e.name?e.name:"Error",r=e instanceof Error?e.message:String(e),n=r.match(/\bHTTP[=: ]+(\d{3})\b/i)?.[1],o=r.match(/(?:错误码|code)[=: ]+(-?[A-Za-z0-9_]+)/i)?.[1];return[t,n?`HTTP ${n}`:void 0,o?`错误码 ${o}`:void 0].filter(Boolean).join(",")}function j(e){return{...e,reason:v(e.reason),hint:e.hint?v(e.hint):void 0}}let k=n("node:fs"),x=n("node:path");function P(){let e=new Date,t=(e,t=2)=>String(e).padStart(t,"0");return`${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}.${t(e.getMilliseconds(),3)}`}let C=!1;function I(e){C=e}let A={};function T(){return A.runId?`[${P()}] [runId=${A.runId}]`:`[${P()}]`}let M=!1;function N(e){if(A.logFile)try{(0,k.appendFileSync)(A.logFile,`${e}
|
|
2
|
+
`,"utf8")}catch(e){if(!M){M=!0;let t=e.code||"unknown";console.error(`[logger] 日志写入失败(${t});后续同类错误将静默处理。`)}}}function O(e){return D(e).map(e=>"string"==typeof e?e:JSON.stringify(e)).join(" ")}function D(e){return e.map(e=>$(e))}let L={setContext(e){if((A={...e}).logFile)try{(0,k.mkdirSync)((0,x.dirname)(A.logFile),{recursive:!0})}catch{}},getContext:()=>A,log(...e){let t=T();C||console.log(t,...D(e)),N(`${t} ${O(e)}`)},debug(...e){let t=T();N(`${t} DEBUG ${O(e)}`)},warn(...e){let t=T();C||console.warn(t,...D(e)),N(`${t} WARN ${O(e)}`)},error(...e){let t=T();C||console.error(t,...D(e)),N(`${t} ERROR ${O(e)}`)}};async function R(e,t){let r=Date.now();L.log(`[timing] ▶ ${e}`);try{let n=await t(),o=Date.now()-r;return L.log(`[timing] ✔ ${e} in ${J(o)}`),{result:n,durationMs:o}}catch(n){let t=Date.now()-r;throw L.log(`[timing] ✘ ${e} FAILED after ${J(t)}: ${E(n)}`),n}}function J(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(2)}s`;let t=Math.floor(e/6e4),r=(e%6e4/1e3).toFixed(1);return`${t}m${r}s`}let U=n("node:child_process"),F=n("node:os"),H=new Set(["node_modules",".doubao-apps",".dbx","dist",".git"]);class K extends Error{code;signal;constructor(e){let t="SIGSEGV"===e.signal?"渲染运行时发生原生崩溃(SIGSEGV / Segmentation fault: 11)":e.signal?`渲染运行时被信号 ${e.signal} 终止`:`渲染运行时异常退出(exit code ${e.code??"unknown"})`;super(e.detail?`${t}:${e.detail}`:t),this.name="EvalDevRuntimeProcessError",this.code=e.code,this.signal=e.signal}}function q(e){let t=(0,x.resolve)(e);if(!(0,k.existsSync)(t)||!(0,k.statSync)(t).isDirectory())throw Error(`miniapp directory does not exist: ${t}`);let r=(0,x.join)(t,"node_modules");if(!(0,k.existsSync)(r))throw Error(`miniapp node_modules not found at ${r}. Run 'pnpm install' (or your package manager) in the miniapp before running eval.`)}function B(e,t){let r=(0,x.relative)((0,x.resolve)(t),(0,x.resolve)(e));return""===r||!r.startsWith(`..${x.sep}`)&&".."!==r&&!(0,x.isAbsolute)(r)}async function V(e){var t,r,n;let o,a,i,s,l,c,u=function(e,t=[]){q(e);let r=(0,k.mkdtempSync)((0,x.join)((0,F.tmpdir)(),"dbx-eval-")),n=!1,o=()=>{if(!n){n=!0;try{(0,k.rmSync)(r,{recursive:!0,force:!0})}catch(e){L.warn(`[eval-dev-runtime] 隔离环境清理失败(${E(e)})`)}}};try{return{directory:function(e,t,r=[]){let n=(0,x.resolve)(e);q(n);let o=(0,x.join)(n,"node_modules"),a=(0,x.resolve)(t);var i=n,s=a;if(B(s,i))throw Error(`isolated miniapp target must not be inside source: ${s}`);if(B(i,s))throw Error(`isolated miniapp target must not contain source: ${s}`);let l=r.map(e=>(0,x.resolve)(e));(0,k.existsSync)(a)&&(0,k.rmSync)(a,{recursive:!0,force:!0}),(0,k.mkdirSync)(a,{recursive:!0});try{return(0,k.cpSync)(n,a,{recursive:!0,dereference:!1,filter:e=>{let t=(0,x.resolve)(e);return t===n||!l.some(e=>B(t,e))&&!H.has((0,x.basename)(e))}}),(0,k.symlinkSync)(o,(0,x.join)(a,"node_modules"),"win32"===process.platform?"junction":"dir"),a}catch(e){try{(0,k.rmSync)(a,{recursive:!0,force:!0})}catch(e){L.warn(`[eval-dev-runtime] 隔离环境回滚失败(${E(e)})`)}throw e}}(e,(0,x.join)(r,"miniapp"),t),cleanup:o}}catch(e){throw o(),e}}(e.miniappDir,e.excludePaths),d=u.directory;L.log("[eval-dev-runtime] 已创建隔离渲染环境");let p=(0,x.join)(d,"..","runtime.json");(0,k.writeFileSync)(p,`${JSON.stringify({...e,miniappDir:d,excludePaths:void 0})}
|
|
3
|
+
`,"utf8");try{o=(0,U.spawn)(process.execPath,(t=function(){let e=process.argv[1];if(!e)throw Error("Unable to resolve the DBX CLI entry point.");return(0,x.resolve)(e)}(),r=p,[t,"eval","run","--internal-dev-runtime",r]),{cwd:d,detached:"win32"!==process.platform,env:{...process.env,DBX_CLI_NO_UPDATE_NOTIFIER:"1"},stdio:["ignore","inherit","inherit","ipc"]})}catch(e){throw u.cleanup(),e}let m=!1,f=!1,g=new Promise((e,t)=>{i=e,s=t}),_=new Promise((e,t)=>{l=t});_.catch(()=>void 0),o.on("message",e=>{if(e&&"object"==typeof e){if("log"===e.type){let t=`[eval-dev-runtime] ${e.message}`;"warn"===e.level?L.warn(t):L.log(t);return}if("failure"===e.type){a=e.message,m||s?.(Error(e.message));return}"ready"===e.type&&(m=!0,i?.(e.webDebuggerUrl))}}),o.once("error",e=>{m?l?.(e):s?.(e)});let h=new Promise(e=>{o.once("exit",(t,r)=>{let n={code:t,signal:r};if(e(n),W(o),u.cleanup(),f)return;let i=new K({...n,detail:a});m?l?.(i):s?.(i)})});try{c=await (n=g,new Promise((e,t)=>{let r=setTimeout(()=>t(Error(`eval dev runtime startup timed out after ${9e4}ms`)),9e4);n.then(t=>{clearTimeout(r),e(t)},e=>{clearTimeout(r),t(e)})}))}catch(e){throw f=!0,await G(o,h),u.cleanup(),e}return{webDebuggerUrl:c,unexpectedExit:_,stop:async()=>{f||(f=!0,o.connected&&o.send({type:"stop"}),await G(o,h,15e3),u.cleanup())}}}function z(e){return new Promise(t=>setTimeout(t,e))}async function G(e,t,r=0){!(r>0&&await Promise.race([t.then(()=>!0),z(r).then(()=>!1)]))&&(e.kill("SIGTERM"),W(e),await Promise.race([t.then(()=>!0),z(3e3).then(()=>!1)])||(e.kill("SIGKILL"),W(e,"SIGKILL"),await Promise.race([t,z(1e3)])))}function W(e,t="SIGTERM"){if("win32"!==process.platform&&e.pid)try{process.kill(-e.pid,t)}catch{}}function X(e,t,r){if(t?.toLowerCase().includes("text/event-stream")){let t=function(e){let t=[],r=[],n=()=>{if(0===r.length)return;let e=r.join("\n").trim();e&&"[DONE]"!==e&&t.push(JSON.parse(e)),r=[]};for(let t of e.split(/\r?\n/)){if(""===t){n();continue}t.startsWith("data:")&&r.push(t.slice(5).trimStart())}return n(),t}(e),n=t.find(e=>{var t,n;return t=e,null!==(n=r)&&Z(t)&&t.id===n})??t.find(Z);if(!n)throw Error("MCP SSE response has no JSON-RPC response");return n}return JSON.parse(e)}function Z(e){return!!(e&&"object"==typeof e&&"id"in e&&("result"in e||"error"in e))}let Y="2025-11-25",Q=["application/json","text/event-stream"];async function ee(e,t,r){let n=await et(e,t,r);try{return{tools:n.tools,manifest:n.manifest,skills:n.skills}}finally{n.close()}}async function et(e,t,r){return new URL(e).pathname.replace(/\/+$/,"").toLowerCase().endsWith("/sse")?en(e,t,r):er(e,t,r)}async function er(e,t,r){let n,o=(("/"===(n=new URL(e)).pathname||""===n.pathname)&&(n.pathname="/mcp"),n.toString());try{let e=await em(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:Y,capabilities:{},clientInfo:{name:"dbx-simulator-eval",version:"0.1.0"}}},{headers:r}),n=e.body.result?.protocolVersion??Y,a=e.headers.get("mcp-session-id")??void 0;await em(o,{jsonrpc:"2.0",method:"notifications/initialized",params:{}},{sessionID:a,protocolVersion:n,allowEmpty:!0,headers:r});let i=await em(o,{jsonrpc:"2.0",id:2,method:"tools/list",params:{}},{sessionID:a,protocolVersion:n,headers:r});return eo({kind:"streamable",url:o,sessionID:a,protocolVersion:n,headers:r},{tools:{server_id:e_(o),name:e_(o),description:"Standard MCP Streamable HTTP server",app_key:t,protocol:"streamable_http",tools:(i.body.result?.tools??[]).map(e=>({name:e.name,description:e.description??"",input_schema_json:JSON.stringify(e.inputSchema??e.input_schema??{}),output_schema_json:JSON.stringify(e.outputSchema??e.output_schema??{})}))}})}catch(e){throw Error(`MCP Streamable HTTP 初始化失败(${eg(e)})`)}}async function en(e,t,r){let n=new URL(e).toString(),o={kind:"sse",url:n,pending:new Map,headers:r};try{await es(o,{jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"dbx-simulator-eval",version:"0.1.0"}}},!1),await es(o,{jsonrpc:"2.0",method:"notifications/initialized",params:{}},!0);let e=await es(o,{jsonrpc:"2.0",id:2,method:"tools/list",params:{}},!1);return eo(o,{tools:{server_id:e_(n),name:e_(n),description:"Standard MCP SSE server",app_key:t,protocol:"sse",tools:(e.result?.tools??[]).map(e=>({name:e.name,description:e.description??"",input_schema_json:JSON.stringify(e.inputSchema??e.input_schema??{}),output_schema_json:JSON.stringify(e.outputSchema??e.output_schema??{})}))}})}catch(e){throw ep(o),Error(`MCP SSE 初始化失败(${eg(e)})`)}}function eo(e,t){let r=!1;return{...t,async callTool(t){if(r)throw Error("MCP client is closed");return function(e){var t;let r=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;let{_response_meta:t,...r}=e;return r}(e);if(!r||"object"!=typeof r){let e=String(r??"");return{content:e,raw_result_text:e,raw_mcp_result_json:e}}if("string"==typeof r.content||"raw_mcp_result_json"in r||"raw_result_text"in r||"structured"in r){let e="string"==typeof r.content?r.content:JSON.stringify(r.content??""),t=r.raw_mcp_result_json||r.raw_result_text||e;return{...r,content:e,raw_result_text:r.raw_result_text||t,raw_mcp_result_json:r.raw_mcp_result_json||t,structured:r.structured??r.structuredContent,is_error:r.is_error??r.isError}}let n=JSON.stringify(r);return{content:n,structured:r.structuredContent,raw_result_text:n,raw_mcp_result_json:n,is_error:!0===r.isError,miniapp:(t=r,Array.isArray(t?.content)&&t?.structuredContent&&"object"==typeof t.structuredContent)?{is_mini_app:!0,mcp_channel:"flow_miniapp"}:void 0}}("sse"===e.kind?await ei(e,t):await ea(e,t))},close(){r||(r=!0,"sse"===e.kind&&ep(e))}}}async function ea(e,t){let r=ew(t.tool_name);if(!r)throw Error("MCP tool name is empty");return(await em(e.url,{jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:r,arguments:e$(t.arguments)??ev(ew(t.arguments_json))??{}}},{sessionID:e.sessionID,protocolVersion:e.protocolVersion,headers:e.headers})).body.result}async function ei(e,t){let r=ew(t.tool_name);if(!r)throw Error("MCP tool name is empty");return(await es(e,{jsonrpc:"2.0",id:Date.now(),method:"tools/call",params:{name:r,arguments:e$(t.arguments)??ev(ew(t.arguments_json))??{}}},!1)).result}async function es(e,t,r){let n;if(await el(e),!e.endpointURL)throw Error("MCP SSE did not provide endpoint event");let o=eh(t),a=ey(t)||"unknown",i=eb(t),s=i?`${a}:${i}`:a,l=null!==o,c=l?new Promise((t,r)=>{let n=setTimeout(()=>{e.pending.delete(o),r(Error(`MCP SSE request timed out: ${s}`))},1e4);e.pending.set(o,{resolve:t,reject:r,timeout:n})}):void 0;try{var u;let r;n=await ef(e.endpointURL,{method:"POST",headers:(u=e.headers,(r=new Headers(u)).set("Content-Type","application/json"),r),body:JSON.stringify(t)},1e4,`MCP SSE POST ${s}`)}catch(t){throw l&&ed(e,o),t}if(!n.ok)throw l&&ed(e,o),await n.body?.cancel(),Error(`MCP SSE 请求失败(HTTP ${n.status})`);if(await n.text(),!l)return{};let d=await c;if(!d&&!r)throw Error("MCP SSE returned empty response");if(d?.error)throw Error(`MCP SSE 请求失败(错误码 ${d.error.code})`);return d}async function el(e){if(e.ready)return e.ready;let t=new AbortController;return e.abortController=t,e.ready=new Promise((r,n)=>{let o=!1,a=setTimeout(()=>{t.abort(),i(Error("MCP SSE endpoint event timed out"))},1e4),i=e=>{o||(o=!0,clearTimeout(a),n(e))};ec(e,t,t=>{e.endpointURL=new URL(t,e.url).toString(),o||(o=!0,clearTimeout(a),r())},i)}).catch(t=>{throw ep(e,t),t}),e.ready}async function ec(e,t,r,n){try{var o;let a,i=await fetch(e.url,{method:"GET",headers:(o=e.headers,(a=new Headers(o)).set("Accept","text/event-stream"),a),signal:t.signal});if(!i.ok||!i.body){await i.body?.cancel(),n(Error(`MCP SSE 连接失败(HTTP ${i.status})`));return}if(!String(i.headers.get("content-type")??"").toLowerCase().includes("text/event-stream"))return void n(Error(`MCP SSE GET content-type=${i.headers.get("content-type")??"-"}`));await eu(e,i.body,r),t.signal.aborted||ep(e,Error("MCP SSE stream closed"))}catch(r){if(!t.signal.aborted){let t=r instanceof Error?r:Error(String(r));n(t),ep(e,t)}}}async function eu(e,t,r){let n=t.getReader(),o=new TextDecoder,a="",i="message",s=[],l=()=>{if(0===s.length){i="message";return}(function(e,t,r,n){let o;if("endpoint"===t)return n(r.trim());if(!r.trim())return;try{o=JSON.parse(r)}catch{return}let a=o.id;if(null==a)return;let i=e.pending.get(a);i&&(clearTimeout(i.timeout),e.pending.delete(a),i.resolve(o))})(e,i,s.join("\n"),r),i="message",s=[]};for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=(a+=o.decode(t,{stream:!0})).search(/\r?\n/);for(;r>=0;){let e=a.slice(0,r).replace(/\r$/,"");a=a.slice(r+("\r"===a[r]&&"\n"===a[r+1]?2:1)),""===e?l():e.startsWith("event:")?i=e.slice(6).trim():e.startsWith("data:")&&s.push(e.slice(5).trimStart()),r=a.search(/\r?\n/)}}a&&s.push(a),l()}function ed(e,t){if(null===t)return;let r=e.pending.get(t);r&&(clearTimeout(r.timeout),e.pending.delete(t))}function ep(e,t=Error("MCP SSE session closed")){for(let[r,n]of(e.abortController?.abort(),e.abortController=void 0,e.endpointURL=void 0,e.ready=void 0,e.pending.entries()))clearTimeout(n.timeout),n.reject(t),e.pending.delete(r)}async function em(e,t,r){var n,o;let a,i,s,l=ey(t)||"unknown",c=eb(t),u=c?`${l}:${c}`:l,d=await ef(e,{method:"POST",headers:(n=t,(a=new Headers((o=r).headers)).set("Content-Type","application/json"),a.set("Accept",Q.join(", ")),(i=ey(n))&&a.set("Mcp-Method",i),(s=eb(n))&&a.set("Mcp-Name",s),o.protocolVersion&&a.set("MCP-Protocol-Version",o.protocolVersion),o.sessionID&&a.set("Mcp-Session-Id",o.sessionID),a),body:JSON.stringify(t)},1e4,`MCP Streamable HTTP ${u}`);if(!d.ok)throw await d.body?.cancel(),Error(`MCP Streamable HTTP 请求失败(HTTP ${d.status})`);let p=await d.text();if(!p&&r.allowEmpty)return{body:{},headers:d.headers};if(!p)throw Error("MCP Streamable HTTP returned empty response");let m=X(p,d.headers.get("content-type"),eh(t));if(m.error)throw Error(`MCP Streamable HTTP 请求失败(错误码 ${m.error.code})`);return{body:m,headers:d.headers}}async function ef(e,t,r,n){let o=new AbortController,a=setTimeout(()=>o.abort(),r),i=Date.now(),s=function(e){let t=e.match(/\btools\/call:([^\s]+)/);if(t){let e=t[1];return{start:`正在调用 MCP 工具:${e}`,done:`MCP 工具调用完成:${e}`,failed:`MCP 工具调用失败:${e}`}}return e.includes("tools/list")?{start:"正在获取 MCP 工具列表",done:"MCP 工具列表获取完成",failed:"MCP 工具列表获取失败"}:e.includes("notifications/initialized")?{start:"正在完成 MCP 初始化",done:"MCP 初始化通知完成",failed:"MCP 初始化通知失败"}:{start:"正在连接 MCP 服务",done:"MCP 请求完成",failed:"MCP 请求失败"}}(n);L.log(`[mcp-http] ${s.start}`);try{let r=await fetch(e,{...t,signal:o.signal});return L.log(`[mcp-http] ${s.done}(HTTP ${r.status},耗时 ${J(Date.now()-i)})`),r}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw L.warn(`[mcp-http] ${s.failed}(超时 ${J(r)})`),Error(`MCP 请求超时(${J(r)})`);throw L.warn(`[mcp-http] ${s.failed}(${eg(e)},耗时 ${J(Date.now()-i)})`),Error(`MCP 请求失败(${eg(e)})`)}finally{clearTimeout(a)}}function eg(e){let t=e instanceof Error&&e.name?e.name:"MCPRequestError",r=e instanceof Error?e.message:String(e),n=r.match(/\bHTTP\s+(\d{3})\b/i)?.[1],o=r.match(/错误码\s+(-?\d+)/)?.[1];return n?`${t},HTTP ${n}`:o?`${t},错误码 ${o}`:t}function e_(e){let t=new URL(e);return`${t.hostname}_${t.port||t.protocol.replace(":","")}${t.pathname.replace(/[^A-Za-z0-9_-]/g,"_")}`}function eh(e){return e&&"object"==typeof e&&"id"in e?e.id??null:null}function ey(e){if(e&&"object"==typeof e&&"method"in e)return e.method}function eb(e){if(!e||"object"!=typeof e)return;let t=e.params;return t&&"object"==typeof t?"string"==typeof t.name?t.name:"string"==typeof t.uri?t.uri:void 0:void 0}function ew(e){return"string"==typeof e?e:""}function e$(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function ev(e){if(e)try{return JSON.parse(e)}catch{return}}let eS=n("node:crypto"),eE="dbx-eval",ej=Symbol("dbx.eval.llm-request-diagnostic"),ek="app_quota_exhausted";function ex(e){let t=e.baseUrl?.trim(),r=e.apiKey?.trim();return t&&r?{url:`${t.replace(/\/+$/,"")}/chat/completions`,fetch:globalThis.fetch,authHeader:`Bearer ${r}`,backend:"openai",transport:"json"}:{url:`${a().replace(/\/+$/,"")}/app_developer/api/v1/chat/completions`,fetch:o,backend:"gateway",transport:"sse"}}function eP(e){return e.model||eE}class eC extends Error{backend;transport;url;httpStatus;responseMessage;responseCode;logId;retryable;attempts;partialContentReceived;streamEvent;constructor(e){super(e.message),void 0!==e.cause&&(this.cause=e.cause),this.name="LLMResponseError",this.backend=e.backend,this.transport=e.transport,this.url=e.url,this.httpStatus=e.httpStatus,this.responseMessage=e.responseMessage,this.responseCode=e.responseCode,this.logId=e.logId,this.retryable=e.retryable,this.attempts=e.attempts,this.partialContentReceived=e.partialContentReceived??!1,this.streamEvent=e.streamEvent}}class eI extends Error{timeoutMs;url;constructor(e,t){super(`LLM request timed out after ${e}ms`),this.timeoutMs=e,this.url=t,this.name="LLMRequestTimeoutError"}}function eA(e){if(e&&("object"==typeof e||"function"==typeof e))return e[ej]}function eT(e){return e instanceof eC?"gateway"===e.backend&&(401===e.httpStatus||403===e.httpStatus):eF(e)}function eM(e){return e instanceof eC&&429===e.httpStatus&&e.responseCode===ek}class eN{config;defaultSignal;constructor(e,t){this.config=e,this.defaultSignal=t}async chatCompletion(e,t){let r=t?.response_format?.type==="json_object"?eK(e):e,n=ex(this.config),o=t?.response_format?.type==="json_object",a=eP(this.config),i=eL(t?.request_context);L.log(`[llm] ▶ 正在${i} backend=${n.backend} model=${a} msgs=${r.length} json=${o}`);let s=Date.now(),l=t?.timeout_ms,c=new AbortController,u=!1,d=l&&l>0?setTimeout(()=>{u=!0,c.abort()},l):void 0,p=()=>c.abort(this.defaultSignal?.reason);this.defaultSignal?.aborted?p():this.defaultSignal?.addEventListener("abort",p,{once:!0});let m={...t,signal:c.signal};try{let e=await this.openaiCall(n,r,m);return L.log(`[llm] ✔ ${i}完成 backend=${n.backend} model=${a} in=${J(Date.now()-s)} chars=${e.length}`),e}catch(o){let e=u?new eI(l??0,n.url):o;throw u&&eR(e,{...eA(o)??this.describeRequest(r,t),error_type:e.name}),L.error(`[llm] ✘ ${i}失败 backend=${n.backend} model=${a} after=${J(Date.now()-s)} ${eJ(e)}`),e}finally{d&&clearTimeout(d),this.defaultSignal?.removeEventListener("abort",p)}}describeRequest(e,t){let r=t?.response_format?.type==="json_object"?eK(e):e,n=ex(this.config),o=this.buildRequestBody(n,r,t);return eO(n,eP(this.config),o,t)}async openaiCall(e,t,r){let n,o=Math.max(1,r?.max_http_attempts??3),a=this.buildRequestBody(e,t,r),i=eO(e,eP(this.config),a,r);if("gateway"===e.backend){let t=this.config.appKey?.trim();if(!t){let t=new eC({backend:e.backend,transport:e.transport,message:"LLM gateway request is missing app_key; set app_key in manifest.yaml (or --app-id) so the eval pipeline can attribute the request.",url:e.url,retryable:!1,attempts:1});throw eR(t,{...i,attempts:1,retry_count:0,retryable:!1,error_type:t.name}),t}a.app_key=t}let s=JSON.stringify(a),l=eL(r?.request_context);for(let t=0;t<o;t++){let a=Date.now();L.log(`[llm-http] ▶ 正在${l} attempt=${t+1}/${o} transport=${e.transport}`);try{let n,i={"Content-Type":"application/json"};e.authHeader&&(i.Authorization=e.authHeader);try{n=await e.fetch(e.url,{method:"POST",headers:i,body:s,signal:r?.signal})}catch(r){if("gateway"===e.backend&&eF(r)){var c,u,d;throw c=e,u=r,d=t+1,new eC({backend:c.backend,transport:c.transport,message:"LLM Gateway authentication failed",url:c.url,httpStatus:401,responseMessage:"authentication failed",retryable:!1,attempts:d,cause:u})}throw r}let p=J(Date.now()-a);if(!n.ok){let a=await this.errorFromResponse(e,n,t+1,!1);if(L.warn(`[llm-http] ✘ ${l}失败 HTTP=${n.status} in=${p} attempt=${t+1}/${o} ${eJ(a)}`),a.retryable&&(429===n.status||n.status>=500)&&t<o-1&&!r?.signal?.aborted){await eH(2**t*1e3,r?.signal);continue}throw a}L.log(`[llm-http] ✔ ${l}请求完成 HTTP=${n.status} in=${p} attempt=${t+1}/${o}`);let m="sse"===e.transport?await this.parseSSEStream(n,e,t+1):await this.parseJsonResponse(n,e,t+1);return L.log(`[llm-http] ${l}响应解析完成 in=${J(Date.now()-a)} attempt=${t+1}/${o}`),m}catch(s){if(eR(n=s,{...i,attempts:s instanceof eC?s.attempts:t+1,retry_count:Math.max(0,(s instanceof eC?s.attempts:t+1)-1),retryable:!(s instanceof eC)||s.retryable,http_status:s instanceof eC?s.httpStatus:void 0,response_code:s instanceof eC?s.responseCode:void 0,log_id:s instanceof eC?s.logId:void 0,error_type:s instanceof Error?s.name:typeof s}),L.warn(`[llm-http] ✘ ${l}失败 attempt=${t+1}/${o} after=${J(Date.now()-a)} ${eJ(n)}`),r?.signal?.aborted)throw r.signal.reason instanceof Error?r.signal.reason:n;let e=!(s instanceof eC)||s.retryable;if(t<o-1&&e){await eH(2**t*1e3,r?.signal);continue}throw n}}throw n??Error("LLM request failed after retries")}buildRequestBody(e,t,r){let n={messages:t,temperature:r?.temperature??this.config.temperature??.7,...r?.response_format?{response_format:r.response_format}:{}};return"openai"===e.backend&&(n.max_tokens=r?.max_tokens??this.config.maxTokens??4096),"gateway"===e.backend&&this.config.appKey?.trim()&&(n.app_key=this.config.appKey.trim()),this.config.model&&(n.model=this.config.model),n.stream="sse"===e.transport,n}async parseJsonResponse(e,t,r){let n;try{n=await e.json()}catch(n){throw new eC({backend:t.backend,transport:t.transport,message:"LLM returned invalid JSON",url:t.url,logId:eU(e),retryable:!0,attempts:r,cause:n})}let o=n.choices?.[0]?.message?.content;if(!o)throw new eC({backend:t.backend,transport:t.transport,message:"LLM returned an empty response payload",url:t.url,logId:eU(e),retryable:!1,attempts:r});return o}async parseSSEStream(e,t,r){if(!e.body)throw new eC({backend:t.backend,transport:t.transport,message:"SSE response body is null",url:t.url,logId:eU(e),retryable:!0,attempts:r});let n=e.body.getReader(),o=new TextDecoder,a="",i="",s=!1,l="",c=!1,u=!1;for(;!u;){let d;try{let e=await n.read();u=e.done,d=e.value}catch(n){throw i&&(c=!0),new eC({backend:t.backend,transport:t.transport,message:"SSE stream disconnected",url:t.url,logId:eU(e),retryable:!0,attempts:r,partialContentReceived:c,streamEvent:l,cause:n})}if(!d)continue;let p=(a+=o.decode(d,{stream:!u})).split(/\r?\n/);a=p.pop()??"";let m=l;for(let n of p){let o,a=n.trim();if(""===a){m="";continue}if(a.startsWith(":"))continue;if(a.startsWith("event:")){l=m=a.slice(6).trim();continue}if(!a.startsWith("data:"))continue;let u=a.slice(5).trim();if(""===u)continue;if("[DONE]"===u){s=!0;continue}try{o=JSON.parse(u)}catch(n){throw new eC({backend:t.backend,transport:t.transport,message:"SSE data is not valid JSON",url:t.url,logId:eU(e),retryable:!0,attempts:r,streamEvent:m,cause:n})}if("error"===m||o.error){let n=o.error;throw new eC({backend:t.backend,transport:t.transport,message:"LLM stream returned an error event",url:t.url,httpStatus:e.status,responseMessage:n?.message,logId:o.log_id??o.logId??eU(e),retryable:!1,attempts:r,streamEvent:m||"error"})}let d=o.choices,p=d?.[0]?.delta?.content;p&&(i+=p,c=!0)}}if(!s)throw new eC({backend:t.backend,transport:t.transport,message:"SSE stream ended without a [DONE] marker",url:t.url,logId:eU(e),retryable:!0,attempts:r,partialContentReceived:c,streamEvent:l});if(!i)throw new eC({backend:t.backend,transport:t.transport,message:"LLM returned empty stream response",url:t.url,logId:eU(e),retryable:!1,attempts:r,streamEvent:l});return i}async errorFromResponse(e,t,r,n){let o,a,i=eU(t),s="";try{s=await t.text()}catch{s=""}try{let e=JSON.parse(s);o=e.error?.message??e.message,a=e.error?.code??e.code}catch{o=s.length>2e3?`${s.slice(0,2e3)}...`:s}let l=(429!==t.status||a!==ek)&&(429===t.status||t.status>=500);return new eC({backend:e.backend,transport:e.transport,message:`LLM API error: HTTP ${t.status}`,url:e.url,httpStatus:t.status,responseMessage:o,responseCode:a,logId:i,retryable:l,attempts:r,partialContentReceived:n})}}function eO(e,t,r,n){var o,a;let i=eD(n?.request_context);return{stage:i.stage,label:i.label,prompt_source:i.promptSource,backend:e.backend,transport:e.transport,model:t,request_body:(o=r,a=i.promptSource,Object.fromEntries(Object.entries(o).map(([e,t])=>"messages"===e&&Array.isArray(t)?[e,t.map(e=>{var t,r;return t=e,r=a,{role:t.role,content:`<已脱敏:${r}>`,content_length:t.content.length,content_sha256:(0,eS.createHash)("sha256").update(t.content).digest("hex")}})]:/^(?:app_key|api_key|authorization|token|headers?)$/i.test(e)?[e,"<已脱敏>"]:[e,t]))),max_http_attempts:Math.max(1,n?.max_http_attempts??3)}}function eD(e){return{stage:v(e?.stage||"llm:completion"),label:v(e?.label||"生成 LLM 响应"),promptSource:v(e?.promptSource||"未标注的 Prompt 来源")}}function eL(e){return eD(e).label.replace(/^正在/,"")}function eR(e,t){if(e&&("object"==typeof e||"function"==typeof e))try{Object.defineProperty(e,ej,{configurable:!0,value:t})}catch{}}function eJ(e){let t=[`error=${e instanceof Error?e.name:typeof e}`];return e instanceof eC&&(void 0!==e.httpStatus&&t.push(`http=${e.httpStatus}`),e.responseCode&&t.push(`code=${v(e.responseCode)}`),t.push(`retryable=${e.retryable}`),t.push(`attempts=${e.attempts}`),e.logId&&t.push(`logid=${v(e.logId)}`)),t.join(" ")}function eU(e){return e.headers.get("x-tt-logid")??void 0}function eF(e){if(!e||"object"!=typeof e)return!1;let t=String(e.name??e.constructor?.name??""),r=String(e.code??""),n=String(e.message??"").toLowerCase();return"NotLoggedInError"===t||"TokenExpiredError"===t||"NOT_LOGGED_IN"===r||"TOKEN_EXPIRED"===r||n.includes("login token has expired")||"not logged in"===n}function eH(e,t){return t?.aborted?Promise.reject(t.reason):new Promise((r,n)=>{let o=setTimeout(function(){t?.removeEventListener("abort",a),r()},e);function a(){clearTimeout(o),n(t?.reason)}t?.addEventListener("abort",a,{once:!0})})}function eK(e){return e.some(e=>/\bjson\b/.test(e.content))?e:e.map((t,r)=>r===e.length-1?{...t,content:`${t.content}
|
|
4
4
|
|
|
5
|
-
(Respond in json.)`}:t)}let
|
|
5
|
+
(Respond in json.)`}:t)}let eq=0,eB=new WeakMap;class eV extends Error{stage;failures;requestContext;requestDiagnostic;diagnosticPath;constructor(e,t,r=eZ(e),n){super(`Invalid structured LLM output for ${e} after ${t.length} response(s): ${t.at(-1)?.error??"unknown parse error"}`),this.stage=e,this.failures=t,this.requestContext=r,this.requestDiagnostic=n,this.name="StructuredOutputError"}attachDiagnostic(e){this.diagnosticPath=e,this.message=`${this.message}. Diagnostic: ${e}`}}async function ez(e){let t=eZ(e.stage,e.requestContext),r=Math.max(0,e.maxRepairAttempts??2),n=[],o=e.messages,a=eY(e.completionOptions,t),i=eQ(e.llmClient,o,a),s=await e0(e.llmClient,o,a);for(let c=0;c<=r;c++)try{return e.parse(s)}catch(p){var l;let u=p.message;if(n.push({response:s,error:u}),c===r){let r=new eV(e.stage,n,t,i);throw function(e,t){let r=eB.get(e);if(r)try{t.attachDiagnostic(eX(r,t))}catch(e){L.warn(`[structured-output] ${t.stage} 诊断保存失败(${E(e)})`)}}(e.llmClient,r),r}let d=c+1;L.warn(`[structured-output] ${t.label}输出无效,正在修复 ${d}/${r}(${p instanceof SyntaxError?"JSONSyntaxError":"SchemaValidationError"})`),o=[...e.messages,{role:"assistant",content:s},{role:"user",content:e.buildRepairPrompt?.({error:u,repairAttempt:d})??(l=u,`上一条响应不符合最初要求的 JSON 契约。
|
|
6
6
|
|
|
7
7
|
错误:${l}
|
|
8
8
|
|
|
9
9
|
请保留原响应的业务语义和字段,只修复 JSON 语法或结构错误。
|
|
10
|
-
只输出完整、严格合法的 JSON 对象,不要输出解释或 Markdown 代码围栏。`)}],a=eY({...e.completionOptions,temperature:.2,response_format:{type:"json_object"}},t),i=eQ(e.llmClient,o,a),s=await e0(e.llmClient,o,a)}throw new eV(e.stage,n)}function eG(e,t){eB.set(e,(0,x.resolve)(t))}function eW(e){var t;let r,n,o=JSON.parse((n=(r=e.trim()).match(/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/i),(n?.[1]??r).trim()));if(!((t=o)&&"object"==typeof t&&!Array.isArray(t)))throw Error("response JSON must be an object");return o}function eX(e,t){let r=new Date().toISOString(),n=eK++,o=`${e2(t.stage)}-${Date.now()}-${n}.json`,a=(0,x.join)((0,x.resolve)(e),"llm-errors",o);return s(a,{stage:t.stage,label:t.requestContext.label,prompt_source:t.requestContext.promptSource,timestamp:r,...e1(t.requestDiagnostic),response_count:t.failures.length,failures:t.failures.map((e,t)=>({attempt:t+1,error:e.error,raw_response:e.response}))}),a}function eZ(e,t={}){let r=function(e){let t=e.split(":"),r=t.find(e=>/^case[_-]/i.test(e)),n=r?`(Case ${r})`:"";if("genChecklist"===t[0]){let r=t[1],o=e.endsWith(":correction")?"buildRubricCorrectionPrompt":({behavior:"buildBehaviorPrompt",skillRubric:"buildSkillRubricPrompt",flowRubric:"buildFlowRubricPrompt",rubric:"buildRubricPrompt",rubricSupplement:"buildRubricSupplementPrompt",rubricValidate:"buildRubricReviewPrompt"})[r]||"Checklist Prompt 构建器";return{label:`生成 Checklist${n}`,promptSource:`gen-checklist.ts / ${o}`}}if("genIntent"===t[0]){let e=t[1],r="flowBatch"===e&&t[2]?`(批次 ${t[2]})`:"";return{label:`生成测试用例${r}`,promptSource:`gen-intent.ts / ${({autoCount:"auto-count inline prompt",flowBatch:"buildFlowCaseBatchPrompt",enrichFlowSeeds:"buildFlowSeedEnrichmentPrompt",planSeeds:"seed-plan inline prompt",generateSeed:"generateCaseForSeedAttempt",validate:"validateCases"})[e]||"Intent Prompt 构建器"}`}}if("scorer"===t[0]){let n=e.match(/:batch(\d+)$/),o=[r?`Case ${r}`:void 0,n?`Rubric 批次 ${n[1]}`:void 0].filter(Boolean);return{label:`生成评分${o.length?`(${o.join(",")})`:""}`,promptSource:"rubric"===t[1]?"scorer.ts / buildRubricJudgePrompt":"scorer.ts / evaluability prompt"}}if("apiDeps"===t[0]){let e="shard"===t[1]&&t[2]?`(分片 ${t[2]})`:"";return{label:`生成 API 依赖关系${e}`,promptSource:"shard"===t[1]?"gen-api-deps.ts / buildAPIDepsShardPrompt":"gen-api-deps.ts / buildAPIDepsPrompt"}}if("entityPool"===t[0]){let e=t[1];return{label:`生成实体池${"expand"===e&&t[2]?`(${t[2]})`:""}`,promptSource:`entity-pool.ts / ${({summarize:"buildEntityAggregatePrompt",expand:"buildEntityExpandPrompt",intentSeeds:"buildIntentSeedPrompt"})[e]||"Entity Pool Prompt 构建器"}`}}if("attribution"===t[0]){let e="v3"===t[1]?t[2]:t[1];return{label:`生成失败归因${e?`(Case ${e})`:""}`,promptSource:"attribution-v3.ts / buildAttributionV3Prompt"}}if("userExperience"===t[0])return{label:`生成用户体验评分${t[1]?`(Case ${t[1]})`:""}`,promptSource:"user-experience.ts / buildUserExperiencePrompt"};if("trajectory"===t[0]&&"ua"===t[1]){let t=e.match(/:round(\d+)$/),n=[r?`Case ${r}`:void 0,t?`第 ${t[1]} 轮`:void 0].filter(Boolean);return{label:`生成用户模拟输入${n.length?`(${n.join(",")})`:""}`,promptSource:"prompts.ts / buildUASystemPrompt + buildUATurnPrompt"}}let o={"explore:action":{label:"生成工具探索动作",promptSource:"prompts.ts / buildExploreSystemPrompt + buildExploreStepPrompt"},skillReview:{label:"生成 Skill 审查",promptSource:"skill-review.ts / buildSkillReviewPrompt"},developerSummary:{label:"生成开发者总结",promptSource:"developer-summary.ts / buildDeveloperSummaryPrompt"},flowMap:{label:"生成业务流程图",promptSource:"gen-flow-map.ts / buildFlowMapPrompt"},flowTopology:{label:"生成业务流程拓扑",promptSource:"gen-flow-topology.ts / buildFlowTopologyPrompt"},"entityPool:summarize":{label:"生成实体池",promptSource:"entity-pool.ts / buildEntityAggregatePrompt"}}[e];return o||{label:`生成评测内容(${v(e)})`,promptSource:`${t[0]||"unknown"}.ts / 未标注的 Prompt 构建器`}}(e);return{stage:v(t.stage||e),label:v(t.label||r.label),promptSource:v(t.promptSource||r.promptSource)}}function eY(e,t){return{...e,request_context:t}}function eQ(e,t,r){try{return e.describeRequest?.(t,r)}catch{return}}async function e0(e,t,r){try{return await e.chatCompletion(t,r)}catch(n){throw function(e,t,r){let n=eB.get(e);if(!n)return;let o=eA(t)??r;if(o)try{var a,i,l,c;let e,r,u,d;a=n,i=t,l=o,e=new Date().toISOString(),r=eK++,u=`${e2(l.stage)}-request-${Date.now()}-${r}.json`,d=(0,x.join)((0,x.resolve)(a),"llm-errors",u),s(d,{stage:l.stage,label:l.label,prompt_source:l.prompt_source,timestamp:e,...e1(l),error_summary:(c=i)instanceof eC?`LLM 请求失败(HTTP ${c.httpStatus??"未知"})`:c instanceof Error?`${c.name}: ${v(c.message)}`:v(String(c))})}catch(e){L.warn(`[structured-output] LLM 请求诊断保存失败(${E(e)})`)}}(e,n,eQ(e,t,r)),n}}function e1(e){return e?{backend:e.backend,transport:e.transport,model:e.model,http_status:e.http_status,response_code:e.response_code,attempts:e.attempts,retry_count:e.retry_count,max_http_attempts:e.max_http_attempts,retryable:e.retryable,log_id:e.log_id,error_type:e.error_type,request_body:e.request_body}:{}}function e2(e){return e.replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"unknown-stage"}let e3=/(^|[_.-])(add|book|cancel|confirm|create|delete|edit|modify|pay|purchase|refund|remove|reserve|save|send|set|submit|update|upsert|write)([_.-]|$)/i,e4=/^(?:\[[^\]]+\]\s*)?(创建|新增|更新|修改|删除|移除|取消|提交|支付|写入|设置|保存|发送|预订|预约|退款)/;function e5(e){return!e3.test(e.name)&&!e4.test(e.description?.trim()??"")}let e9="DBX_EVAL_SIMULATOR_CHAT_QPS",e6=(e={runSimulatorStream:u,waitForStart:function(e){if(!Number.isFinite(e.minIntervalMs)||e.minIntervalMs<0)throw Error("minIntervalMs must be a non-negative finite number");let t=e.now??Date.now,r=e.sleep??tn,n=0,o=Promise.resolve();return a=>{let i=o.then(async()=>{a?.throwIfAborted();let o=Math.max(0,n-t());o>0&&await r(o,a),a?.throwIfAborted(),n=t()+e.minIntervalMs});return o=i.catch(()=>void 0),i}}({minIntervalMs:function(e=process.env[e9]){let t=e?.trim(),r=void 0===t||""===t?.5:Number(t);if(!Number.isFinite(r)||r<=0)throw Error(`${e9} must be a positive finite number`);return 1e3/r}()}),sleep:tn,random:Math.random,now:Date.now},async(t,r={})=>{let n=[];for(let i=1;i<=5;i++){r.signal?.throwIfAborted(),await e.waitForStart(r.signal);let s=e.now();try{let o=await e.runSimulatorStream(t),a=e.now(),l=function(e){for(let t of e){if(tl(t)&&"tool_call_or_report_failed"===t.code)continue;let e=(function e(t,r=0){if(r>4)return[];if("string"==typeof t)return[t];if(Array.isArray(t))return t.flatMap(t=>e(t,r+1));if(!tl(t))return[];let n=[];for(let e of["code","message"]){let r=t[e];"string"==typeof r&&n.push(r)}for(let o of["error","details"])n.push(...e(t[o],r+1));return n})(t).find(e=>(function(e){let t=e.trim().toLowerCase();return"rate_limit_exceeded"===t||t.includes("ratelimit triggered")||t.includes("rate limit exceeded")})(e));if(e)return e}}(o.streamErrors),c=l?void 0:function(e){let t=e.map(e=>(function e(t){if("string"==typeof t)return t;if(!tl(t))return ta(t);let r=ts(t,"code"),n=ts(t,"message")||ts(t,"msg")||ts(t,"error_message"),o=ts(t,"reason"),a=ts(t,"detail")||ts(t,"details"),i=e(t.error),s=[r&&n?`${r}: ${n}`:n??r,o,a,i,"string"==typeof t.details?void 0:e(t.details)].filter(e=>!!e);return s.length>0?s.join(" | "):ta(t)})(e)).filter(e=>!!e);if(0!==t.length){var r;return(r=t.join(" | ")).length>1e3?`${r.slice(0,997)}...`:r}}(o.streamErrors),u={attempt:i,started_at_ms:s,ended_at_ms:a,duration_ms:a-s,status:200,log_id:o.logID,outcome:l?"rate_limited":c?"failed":"success",error:l??c};n.push(u);let d=c&&0===o.toolCalls.length&&to(c)?c:void 0;if(!l&&!d)return c?L.warn(`[simulator-chat] failed attempt=${i}/5 logid=${o.logID||"-"} error=${tr(c)}`):i>1&&L.log(`[simulator-chat] success attempt=${i}/5 logid=${o.logID||"-"}`),{state:o,attempts:n};if(l&&o.toolCalls.length>0)throw L.warn(`[simulator-chat] retry blocked reason=tool_call_observed attempts=${i} logids=${ti(n)}`),new e7(`simulator chat rate limited after tool call: ${l}`,o,n,{retryBlockedReason:"tool_call_observed"});let p=!!l,m=p?"rate limited":"connection error",f=l??d;if(5===i)throw L.error(`[simulator-chat] retry exhausted attempts=${i} logids=${ti(n)}`),function(e,t,r,n,o={}){return e?new e7(t,r,n,o):new e8(t,r,n,o)}(p,`simulator chat ${m} retry exhausted after ${i} attempts: ${f}`,o,n,{retryExhausted:!0});await tt(i,u,e,r.signal,m)}catch(p){var o,a;if(r.signal?.aborted)throw r.signal.reason;if(p instanceof e8)throw p;let t=e.now(),u=te(p);if(p instanceof l&&429===u){let o={attempt:i,started_at_ms:s,ended_at_ms:t,duration_ms:t-s,status:u,log_id:p.logId,outcome:"rate_limited",error:p.message};n.push(o);let a={requestID:"",logID:p.logId,answer:"",toolCalls:[],cards:[],traceEvents:[],streamErrors:[]};if(5===i)throw L.error(`[simulator-chat] retry exhausted attempts=${i} logids=${ti(n)}`),new e7(`simulator chat HTTP 429 retry exhausted after ${i} attempts`,a,n,{retryExhausted:!0,cause:p});await tt(i,o,e,r.signal,"rate limited");continue}let d={attempt:i,started_at_ms:s,ended_at_ms:t,duration_ms:t-s,status:te(p),log_id:ts(o=p,"logId")||ts(o,"log_id")||ts(o,"logID"),outcome:"failed",error:(a=p)instanceof Error?a.message:String(a)};if(n.push(d),p instanceof c){let t=to(p.message),o=p.state.toolCalls.length>0;if(t&&!o&&i<5){await tt(i,d,e,r.signal,"connection error");continue}throw t&&o?L.warn(`[simulator-chat] retry blocked reason=tool_call_observed attempts=${i} logids=${ti(n)}`):t&&L.error(`[simulator-chat] retry exhausted attempts=${i} logids=${ti(n)}`),new e8(p.message,p.state,n,{cause:p,retryExhausted:t&&!o,retryBlockedReason:t&&o?"tool_call_observed":void 0})}throw p}}throw Error("simulator chat retry loop ended unexpectedly")});class e8 extends c{attempts;retryExhausted;retryBlockedReason;constructor(e,t,r,n={}){super(e,t,t.logID),this.attempts=r,this.name="EvalSimulatorStreamError",this.retryExhausted=n.retryExhausted??!1,this.retryBlockedReason=n.retryBlockedReason,this.cause=n.cause}}class e7 extends e8{constructor(e,t,r,n={}){super(e,t,r,n),this.name="EvalSimulatorRateLimitError"}}function te(e){if(!(e instanceof l))return;let t=e.status;if("number"==typeof t&&Number.isInteger(t))return t;let r=e.message.match(/\bHTTP\s+(\d{3})\b/i);return r?Number(r[1]):void 0}async function tt(e,t,r,n,o="rate limited"){let a=function(e,t=Math.random){if(!Number.isInteger(e)||e<1||e>=5)throw Error("retryNumber must be between 1 and 4");return Math.round(1e3*2**(e-1)*(.8+.4*Math.min(1,Math.max(0,t()))))}(e,r.random);t.retry_delay_ms=a,L.warn(`[simulator-chat] ${o} attempt=${t.attempt}/5 logid=${t.log_id||"-"} retry_in=${a}ms error=${t.error?tr(t.error):"-"}`),await r.sleep(a,n)}function tr(e){let t=e.match(/(?:^|\|\s)([A-Z][A-Z0-9_]{2,})(?=[:\s|]|$)/)?.[1];return t||(to(e)?"SIMULATOR_CONNECTION_ERROR":E(Error(e)))}function tn(e,t){return t?.aborted?Promise.reject(t.reason):new Promise((r,n)=>{let o=setTimeout(function(){t?.removeEventListener("abort",a),r()},e);function a(){clearTimeout(o),n(t?.reason)}t?.addEventListener("abort",a,{once:!0})})}function to(e){let t=e.trim().toLowerCase();return!!t&&("terminated"===t||t.includes("code = 14")||t.includes("code=14")||t.includes("connection termination")||t.includes("connection terminated")||t.includes("connection reset")||t.includes("connection closed")||t.includes("connection refused")||t.includes("connection error")||t.includes("premature close")||t.includes("other side closed")||t.includes("econnreset")||t.includes("econnrefused")||t.includes("epipe")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("stream disconnected")||t.includes("network error")||t.includes("unavailable")||t.includes("timeout")||t.includes("timed out"))}function ta(e){if(void 0!==e)try{return JSON.stringify(e)}catch{return String(e)}}function ti(e){return e.map(e=>e.log_id||"-").join(",")}function ts(e,t){if(!tl(e))return;let r=e[t];return"string"==typeof r&&r?r:void 0}function tl(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let tc=new Set(["posthook_tool_input","posthook_tool_output","posthook_tool_report"]);function tu(e){return"simulator_response"===e.origin&&tc.has(e.family)}function td(e,t){var r,n;let o,a=e.rounds.flatMap(e=>e.simulator_failures||[]),i=a.filter(tu);return 0===i.length?"terminated"===e.metadata.stop_reason?"terminated_infrastructure":"scoreable_clean":(r=e,n=t,o=r.rounds.flatMap(e=>e.tool_calls.filter(e=>!e.is_error)),n.length>0?o.length>0:r.rounds.some(e=>"terminated"!==e.status&&e.assistant_answer.trim().length>0&&0===(e.simulator_failures||[]).length))?"scoreable_with_posthook":i.length===a.length?"blocked_posthook":"scoreable_with_posthook"}function tp(e,t,r,n){let o=tf(r);if(!o)return;let a=tf(o.details),i=tf(o.error);if("cli_tool_callback"===o.origin)return;let s=tg(o,"code")||tg(a,"code")||tg(i,"code"),l=tg(o,"stage")||tg(a,"stage")||tg(i,"stage"),c=function(e,t,r){let n,o=e?.trim().toLowerCase(),a=t?.trim().toLowerCase();if("tool_call_arguments_invalid"===o||"tool_call_validation"===a)return"posthook_tool_input";if("miniapp_mcp_result_invalid"===o||"context_post_hook"===a||"tool_result_validation"===a)return"posthook_tool_output";if("tool_report_validation"===a||"tool_call_or_report_failed"===o&&((n=t_(r).toLowerCase()).includes("schema validation")||n.includes("protocol validation")||n.includes("entity validation")||n.includes("mcp tool invalid response")))return"posthook_tool_report";let i=t_(r).toLowerCase();return"rate_limit_exceeded"===o||i.includes("ratelimit triggered")||i.includes("rate limit exceeded")||i.includes("code = 14")||i.includes("timed out")||i.includes("timeout")||i.includes("connection terminated")||i.includes("econnreset")?"infrastructure":"agent_run_failed"===o||"reply_failed"===o?"agent_runtime":"unknown"}(s,l,o),u=tg(o,"message")||tg(o,"user_message")||tg(a,"message")||tg(i,"message")||function(e){try{return JSON.stringify(e)}catch{return String(e)}}(r);if(!u)return;let d=a?.arguments_json??o.arguments_json??o.arguments,p=a?.input_schema_json??o.input_schema_json??o.input_schema,m={round:e,origin:"simulator_response",source:t,family:c,code:s,stage:l,message:u,user_message:tg(o,"user_message")||tg(a,"user_message"),tool_name:tg(o,"tool_name")||tg(a,"tool_name")||n.toolName,tool_call_id:tg(o,"tool_call_id")||tg(a,"tool_call_id"),log_id:tg(o,"log_id")||tg(a,"log_id")||n.logId,arguments:tm(d),input_schema:tm(p),schema_errors:function(e){if(Array.isArray(e)){let t=e.filter(e=>"string"==typeof e).map(e=>e.trim()).filter(Boolean);return t.length>0?t:void 0}if("string"!=typeof e||!e.trim())return;let t=e.split(";").map(e=>e.trim()).filter(Boolean);return t.length>0?t:void 0}(a?.schema_errors??o.schema_errors)},f=(0,eS.createHash)("sha256").update(t_(r)).digest("hex");return{event_id:`simfail_${f.slice(0,20)}`,...m,raw_digest:f}}function tm(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function tf(e){return"object"!=typeof e||null===e||Array.isArray(e)?void 0:e}function tg(e,t){let r=e?.[t];return"string"==typeof r&&r.trim()?r.trim():void 0}function t_(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):"object"!=typeof t||null===t?t:Object.fromEntries(Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).map(([t,r])=>[t,e(r)]))}(e))}let th="Asia/Shanghai";function ty(e=new Date){return e.toISOString()}function tb(e){let t=function(e){let t=e?new Date(e):new Date;if(!Number.isFinite(t.getTime()))throw Error(`Invalid eval reference time: ${e}`);return t}(e),r=new Intl.DateTimeFormat("zh-CN",{timeZone:th,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23",timeZoneName:"longOffset"}).format(t);return`基准时间:${r}(${th})
|
|
10
|
+
只输出完整、严格合法的 JSON 对象,不要输出解释或 Markdown 代码围栏。`)}],a=eY({...e.completionOptions,temperature:.2,response_format:{type:"json_object"}},t),i=eQ(e.llmClient,o,a),s=await e0(e.llmClient,o,a)}throw new eV(e.stage,n)}function eG(e,t){eB.set(e,(0,x.resolve)(t))}function eW(e){var t;let r,n,o=JSON.parse((n=(r=e.trim()).match(/^```(?:json)?\s*\n?([\s\S]*?)\n?```\s*$/i),(n?.[1]??r).trim()));if(!((t=o)&&"object"==typeof t&&!Array.isArray(t)))throw Error("response JSON must be an object");return o}function eX(e,t){let r=new Date().toISOString(),n=eq++,o=`${e2(t.stage)}-${Date.now()}-${n}.json`,a=(0,x.join)((0,x.resolve)(e),"llm-errors",o);return s(a,{stage:t.stage,label:t.requestContext.label,prompt_source:t.requestContext.promptSource,timestamp:r,...e1(t.requestDiagnostic),response_count:t.failures.length,failures:t.failures.map((e,t)=>({attempt:t+1,error:e.error,raw_response:e.response}))}),a}function eZ(e,t={}){let r=function(e){let t=e.split(":"),r=t.find(e=>/^case[_-]/i.test(e)),n=r?`(Case ${r})`:"";if("genChecklist"===t[0]){let r=t[1],o=e.endsWith(":correction")?"buildRubricCorrectionPrompt":({behavior:"buildBehaviorPrompt",skillRubric:"buildSkillRubricPrompt",flowRubric:"buildFlowRubricPrompt",rubric:"buildRubricPrompt",rubricSupplement:"buildRubricSupplementPrompt",rubricValidate:"buildRubricReviewPrompt"})[r]||"Checklist Prompt 构建器";return{label:`生成 Checklist${n}`,promptSource:`gen-checklist.ts / ${o}`}}if("genIntent"===t[0]){let e=t[1],r="flowBatch"===e&&t[2]?`(批次 ${t[2]})`:"";return{label:`生成测试用例${r}`,promptSource:`gen-intent.ts / ${({autoCount:"auto-count inline prompt",flowBatch:"buildFlowCaseBatchPrompt",enrichFlowSeeds:"buildFlowSeedEnrichmentPrompt",planSeeds:"seed-plan inline prompt",generateSeed:"generateCaseForSeedAttempt",validate:"validateCases"})[e]||"Intent Prompt 构建器"}`}}if("scorer"===t[0]){let n=e.match(/:batch(\d+)$/),o=[r?`Case ${r}`:void 0,n?`Rubric 批次 ${n[1]}`:void 0].filter(Boolean);return{label:`生成评分${o.length?`(${o.join(",")})`:""}`,promptSource:"rubric"===t[1]?"scorer.ts / buildRubricJudgePrompt":"scorer.ts / evaluability prompt"}}if("apiDeps"===t[0]){let e="shard"===t[1]&&t[2]?`(分片 ${t[2]})`:"";return{label:`生成 API 依赖关系${e}`,promptSource:"shard"===t[1]?"gen-api-deps.ts / buildAPIDepsShardPrompt":"gen-api-deps.ts / buildAPIDepsPrompt"}}if("entityPool"===t[0]){let e=t[1];return{label:`生成实体池${"expand"===e&&t[2]?`(${t[2]})`:""}`,promptSource:`entity-pool.ts / ${({summarize:"buildEntityAggregatePrompt",expand:"buildEntityExpandPrompt",intentSeeds:"buildIntentSeedPrompt"})[e]||"Entity Pool Prompt 构建器"}`}}if("attribution"===t[0]){let e="v3"===t[1]?t[2]:t[1];return{label:`生成失败归因${e?`(Case ${e})`:""}`,promptSource:"attribution-v3.ts / buildAttributionV3Prompt"}}if("userExperience"===t[0])return{label:`生成用户体验评分${t[1]?`(Case ${t[1]})`:""}`,promptSource:"user-experience.ts / buildUserExperiencePrompt"};if("trajectory"===t[0]&&"ua"===t[1]){let t=e.match(/:round(\d+)$/),n=[r?`Case ${r}`:void 0,t?`第 ${t[1]} 轮`:void 0].filter(Boolean);return{label:`生成用户模拟输入${n.length?`(${n.join(",")})`:""}`,promptSource:"prompts.ts / buildUASystemPrompt + buildUATurnPrompt"}}let o={"explore:action":{label:"生成工具探索动作",promptSource:"prompts.ts / buildExploreSystemPrompt + buildExploreStepPrompt"},skillReview:{label:"生成 Skill 审查",promptSource:"skill-review.ts / buildSkillReviewPrompt"},developerSummary:{label:"生成开发者总结",promptSource:"developer-summary.ts / buildDeveloperSummaryPrompt"},flowMap:{label:"生成业务流程图",promptSource:"gen-flow-map.ts / buildFlowMapPrompt"},flowTopology:{label:"生成业务流程拓扑",promptSource:"gen-flow-topology.ts / buildFlowTopologyPrompt"},"entityPool:summarize":{label:"生成实体池",promptSource:"entity-pool.ts / buildEntityAggregatePrompt"}}[e];return o||{label:`生成评测内容(${v(e)})`,promptSource:`${t[0]||"unknown"}.ts / 未标注的 Prompt 构建器`}}(e);return{stage:v(t.stage||e),label:v(t.label||r.label),promptSource:v(t.promptSource||r.promptSource)}}function eY(e,t){return{...e,request_context:t}}function eQ(e,t,r){try{return e.describeRequest?.(t,r)}catch{return}}async function e0(e,t,r){try{return await e.chatCompletion(t,r)}catch(n){throw function(e,t,r){let n=eB.get(e);if(!n)return;let o=eA(t)??r;if(o)try{var a,i,l,c;let e,r,u,d;a=n,i=t,l=o,e=new Date().toISOString(),r=eq++,u=`${e2(l.stage)}-request-${Date.now()}-${r}.json`,d=(0,x.join)((0,x.resolve)(a),"llm-errors",u),s(d,{stage:l.stage,label:l.label,prompt_source:l.prompt_source,timestamp:e,...e1(l),error_summary:(c=i)instanceof eC?`LLM 请求失败(HTTP ${c.httpStatus??"未知"})`:c instanceof Error?`${c.name}: ${v(c.message)}`:v(String(c))})}catch(e){L.warn(`[structured-output] LLM 请求诊断保存失败(${E(e)})`)}}(e,n,eQ(e,t,r)),n}}function e1(e){return e?{backend:e.backend,transport:e.transport,model:e.model,http_status:e.http_status,response_code:e.response_code,attempts:e.attempts,retry_count:e.retry_count,max_http_attempts:e.max_http_attempts,retryable:e.retryable,log_id:e.log_id,error_type:e.error_type,request_body:e.request_body}:{}}function e2(e){return e.replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"unknown-stage"}let e3=/(^|[_.-])(add|book|cancel|confirm|create|delete|edit|modify|pay|purchase|refund|remove|reserve|save|send|set|submit|update|upsert|write)([_.-]|$)/i,e4=/^(?:\[[^\]]+\]\s*)?(创建|新增|更新|修改|删除|移除|取消|提交|支付|写入|设置|保存|发送|预订|预约|退款)/;function e5(e){return!e3.test(e.name)&&!e4.test(e.description?.trim()??"")}let e9="DBX_EVAL_SIMULATOR_CHAT_QPS",e6=(e={runSimulatorStream:u,waitForStart:function(e){if(!Number.isFinite(e.minIntervalMs)||e.minIntervalMs<0)throw Error("minIntervalMs must be a non-negative finite number");let t=e.now??Date.now,r=e.sleep??tn,n=0,o=Promise.resolve();return a=>{let i=o.then(async()=>{a?.throwIfAborted();let o=Math.max(0,n-t());o>0&&await r(o,a),a?.throwIfAborted(),n=t()+e.minIntervalMs});return o=i.catch(()=>void 0),i}}({minIntervalMs:function(e=process.env[e9]){let t=e?.trim(),r=void 0===t||""===t?.5:Number(t);if(!Number.isFinite(r)||r<=0)throw Error(`${e9} must be a positive finite number`);return 1e3/r}()}),sleep:tn,random:Math.random,now:Date.now},async(t,r={})=>{let n=[];for(let i=1;i<=5;i++){r.signal?.throwIfAborted(),await e.waitForStart(r.signal);let s=e.now();try{let o=await e.runSimulatorStream(t),a=e.now(),l=function(e){for(let t of e){if(tl(t)&&"tool_call_or_report_failed"===t.code)continue;let e=(function e(t,r=0){if(r>4)return[];if("string"==typeof t)return[t];if(Array.isArray(t))return t.flatMap(t=>e(t,r+1));if(!tl(t))return[];let n=[];for(let e of["code","message"]){let r=t[e];"string"==typeof r&&n.push(r)}for(let o of["error","details"])n.push(...e(t[o],r+1));return n})(t).find(e=>(function(e){let t=e.trim().toLowerCase();return"rate_limit_exceeded"===t||t.includes("ratelimit triggered")||t.includes("rate limit exceeded")})(e));if(e)return e}}(o.streamErrors),c=l?void 0:function(e){let t=e.map(e=>(function e(t){if("string"==typeof t)return t;if(!tl(t))return ta(t);let r=ts(t,"code"),n=ts(t,"message")||ts(t,"msg")||ts(t,"error_message"),o=ts(t,"reason"),a=ts(t,"detail")||ts(t,"details"),i=e(t.error),s=[r&&n?`${r}: ${n}`:n??r,o,a,i,"string"==typeof t.details?void 0:e(t.details)].filter(e=>!!e);return s.length>0?s.join(" | "):ta(t)})(e)).filter(e=>!!e);if(0!==t.length){var r;return(r=t.join(" | ")).length>1e3?`${r.slice(0,997)}...`:r}}(o.streamErrors),u={attempt:i,started_at_ms:s,ended_at_ms:a,duration_ms:a-s,status:200,log_id:o.logID,outcome:l?"rate_limited":c?"failed":"success",error:l??c};n.push(u);let d=c&&0===o.toolCalls.length&&to(c)?c:void 0;if(!l&&!d)return c?L.warn(`[simulator-chat] failed attempt=${i}/5 logid=${o.logID||"-"} error=${tr(c)}`):i>1&&L.log(`[simulator-chat] success attempt=${i}/5 logid=${o.logID||"-"}`),{state:o,attempts:n};if(l&&o.toolCalls.length>0)throw L.warn(`[simulator-chat] retry blocked reason=tool_call_observed attempts=${i} logids=${ti(n)}`),new e7(`simulator chat rate limited after tool call: ${l}`,o,n,{retryBlockedReason:"tool_call_observed"});let p=!!l,m=p?"rate limited":"connection error",f=l??d;if(5===i)throw L.error(`[simulator-chat] retry exhausted attempts=${i} logids=${ti(n)}`),function(e,t,r,n,o={}){return e?new e7(t,r,n,o):new e8(t,r,n,o)}(p,`simulator chat ${m} retry exhausted after ${i} attempts: ${f}`,o,n,{retryExhausted:!0});await tt(i,u,e,r.signal,m)}catch(p){var o,a;if(r.signal?.aborted)throw r.signal.reason;if(p instanceof e8)throw p;let t=e.now(),u=te(p);if(p instanceof l&&429===u){let o={attempt:i,started_at_ms:s,ended_at_ms:t,duration_ms:t-s,status:u,log_id:p.logId,outcome:"rate_limited",error:p.message};n.push(o);let a={requestID:"",logID:p.logId,answer:"",toolCalls:[],cards:[],traceEvents:[],streamErrors:[]};if(5===i)throw L.error(`[simulator-chat] retry exhausted attempts=${i} logids=${ti(n)}`),new e7(`simulator chat HTTP 429 retry exhausted after ${i} attempts`,a,n,{retryExhausted:!0,cause:p});await tt(i,o,e,r.signal,"rate limited");continue}let d={attempt:i,started_at_ms:s,ended_at_ms:t,duration_ms:t-s,status:te(p),log_id:ts(o=p,"logId")||ts(o,"log_id")||ts(o,"logID"),outcome:"failed",error:(a=p)instanceof Error?a.message:String(a)};if(n.push(d),p instanceof c){let t=to(p.message),o=p.state.toolCalls.length>0;if(t&&!o&&i<5){await tt(i,d,e,r.signal,"connection error");continue}throw t&&o?L.warn(`[simulator-chat] retry blocked reason=tool_call_observed attempts=${i} logids=${ti(n)}`):t&&L.error(`[simulator-chat] retry exhausted attempts=${i} logids=${ti(n)}`),new e8(p.message,p.state,n,{cause:p,retryExhausted:t&&!o,retryBlockedReason:t&&o?"tool_call_observed":void 0})}throw p}}throw Error("simulator chat retry loop ended unexpectedly")});class e8 extends c{attempts;retryExhausted;retryBlockedReason;constructor(e,t,r,n={}){super(e,t,t.logID),this.attempts=r,this.name="EvalSimulatorStreamError",this.retryExhausted=n.retryExhausted??!1,this.retryBlockedReason=n.retryBlockedReason,this.cause=n.cause}}class e7 extends e8{constructor(e,t,r,n={}){super(e,t,r,n),this.name="EvalSimulatorRateLimitError"}}function te(e){if(!(e instanceof l))return;let t=e.status;if("number"==typeof t&&Number.isInteger(t))return t;let r=e.message.match(/\bHTTP\s+(\d{3})\b/i);return r?Number(r[1]):void 0}async function tt(e,t,r,n,o="rate limited"){let a=function(e,t=Math.random){if(!Number.isInteger(e)||e<1||e>=5)throw Error("retryNumber must be between 1 and 4");return Math.round(1e3*2**(e-1)*(.8+.4*Math.min(1,Math.max(0,t()))))}(e,r.random);t.retry_delay_ms=a,L.warn(`[simulator-chat] ${o} attempt=${t.attempt}/5 logid=${t.log_id||"-"} retry_in=${a}ms error=${t.error?tr(t.error):"-"}`),await r.sleep(a,n)}function tr(e){let t=e.match(/(?:^|\|\s)([A-Z][A-Z0-9_]{2,})(?=[:\s|]|$)/)?.[1];return t||(to(e)?"SIMULATOR_CONNECTION_ERROR":E(Error(e)))}function tn(e,t){return t?.aborted?Promise.reject(t.reason):new Promise((r,n)=>{let o=setTimeout(function(){t?.removeEventListener("abort",a),r()},e);function a(){clearTimeout(o),n(t?.reason)}t?.addEventListener("abort",a,{once:!0})})}function to(e){let t=e.trim().toLowerCase();return!!t&&("terminated"===t||t.includes("code = 14")||t.includes("code=14")||t.includes("connection termination")||t.includes("connection terminated")||t.includes("connection reset")||t.includes("connection closed")||t.includes("connection refused")||t.includes("connection error")||t.includes("premature close")||t.includes("other side closed")||t.includes("econnreset")||t.includes("econnrefused")||t.includes("epipe")||t.includes("etimedout")||t.includes("socket hang up")||t.includes("stream disconnected")||t.includes("network error")||t.includes("unavailable")||t.includes("timeout")||t.includes("timed out"))}function ta(e){if(void 0!==e)try{return JSON.stringify(e)}catch{return String(e)}}function ti(e){return e.map(e=>e.log_id||"-").join(",")}function ts(e,t){if(!tl(e))return;let r=e[t];return"string"==typeof r&&r?r:void 0}function tl(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let tc=new Set(["posthook_tool_input","posthook_tool_output","posthook_tool_report"]);function tu(e){return"simulator_response"===e.origin&&tc.has(e.family)}function td(e,t){var r,n;let o,a=e.rounds.flatMap(e=>e.simulator_failures||[]),i=a.filter(tu);return 0===i.length?"terminated"===e.metadata.stop_reason?"terminated_infrastructure":"scoreable_clean":(r=e,n=t,o=r.rounds.flatMap(e=>e.tool_calls.filter(e=>!e.is_error)),n.length>0?o.length>0:r.rounds.some(e=>"terminated"!==e.status&&e.assistant_answer.trim().length>0&&0===(e.simulator_failures||[]).length))?"scoreable_with_posthook":i.length===a.length?"blocked_posthook":"scoreable_with_posthook"}function tp(e,t,r,n){let o=tf(r);if(!o)return;let a=tf(o.details),i=tf(o.error);if("cli_tool_callback"===o.origin)return;let s=tg(o,"code")||tg(a,"code")||tg(i,"code"),l=tg(o,"stage")||tg(a,"stage")||tg(i,"stage"),c=function(e,t,r){let n,o=e?.trim().toLowerCase(),a=t?.trim().toLowerCase();if("tool_call_arguments_invalid"===o||"tool_call_validation"===a)return"posthook_tool_input";if("miniapp_mcp_result_invalid"===o||"context_post_hook"===a||"tool_result_validation"===a)return"posthook_tool_output";if("tool_report_validation"===a||"tool_call_or_report_failed"===o&&((n=t_(r).toLowerCase()).includes("schema validation")||n.includes("protocol validation")||n.includes("entity validation")||n.includes("mcp tool invalid response")))return"posthook_tool_report";let i=t_(r).toLowerCase();return"rate_limit_exceeded"===o||i.includes("ratelimit triggered")||i.includes("rate limit exceeded")||i.includes("code = 14")||i.includes("timed out")||i.includes("timeout")||i.includes("connection terminated")||i.includes("econnreset")?"infrastructure":"agent_run_failed"===o||"reply_failed"===o?"agent_runtime":"unknown"}(s,l,o),u=tg(o,"message")||tg(o,"user_message")||tg(a,"message")||tg(i,"message")||function(e){try{return JSON.stringify(e)}catch{return String(e)}}(r);if(!u)return;let d=a?.arguments_json??o.arguments_json??o.arguments,p=a?.input_schema_json??o.input_schema_json??o.input_schema,m={round:e,origin:"simulator_response",source:t,family:c,code:s,stage:l,message:u,user_message:tg(o,"user_message")||tg(a,"user_message"),tool_name:tg(o,"tool_name")||tg(a,"tool_name")||n.toolName,tool_call_id:tg(o,"tool_call_id")||tg(a,"tool_call_id"),log_id:tg(o,"log_id")||tg(a,"log_id")||n.logId,arguments:tm(d),input_schema:tm(p),schema_errors:function(e){if(Array.isArray(e)){let t=e.filter(e=>"string"==typeof e).map(e=>e.trim()).filter(Boolean);return t.length>0?t:void 0}if("string"!=typeof e||!e.trim())return;let t=e.split(";").map(e=>e.trim()).filter(Boolean);return t.length>0?t:void 0}(a?.schema_errors??o.schema_errors)},f=(0,eS.createHash)("sha256").update(t_(r)).digest("hex");return{event_id:`simfail_${f.slice(0,20)}`,...m,raw_digest:f}}function tm(e){if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}}function tf(e){return"object"!=typeof e||null===e||Array.isArray(e)?void 0:e}function tg(e,t){let r=e?.[t];return"string"==typeof r&&r.trim()?r.trim():void 0}function t_(e){return JSON.stringify(function e(t){return Array.isArray(t)?t.map(e):"object"!=typeof t||null===t?t:Object.fromEntries(Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).map(([t,r])=>[t,e(r)]))}(e))}let th="Asia/Shanghai";function ty(e=new Date){return e.toISOString()}function tb(e){let t=function(e){let t=e?new Date(e):new Date;if(!Number.isFinite(t.getTime()))throw Error(`Invalid eval reference time: ${e}`);return t}(e),r=new Intl.DateTimeFormat("zh-CN",{timeZone:th,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23",timeZoneName:"longOffset"}).format(t);return`基准时间:${r}(${th})
|
|
11
11
|
相对日期说明:明天、后天、周五等时间表达均以基准时间所在日期和时区推算。`}function tw(e){try{return(JSON.stringify(e??{})??"{}").replace(/[<>&]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}catch{return"{}"}}function t$(e,t){return e.map((e,r)=>{let n;return 0===r?(n=tw(t),`${e}
|
|
12
12
|
|
|
13
13
|
---
|
|
@@ -38,7 +38,7 @@ ${n}
|
|
|
38
38
|
|
|
39
39
|
`);return r+`当前是第 ${t+1} 轮。
|
|
40
40
|
请先依据完整历史、后台剧本、成功条件和用户画像,判断目标进度、信息是否需要继续释放、是否出现体验摩擦、情绪如何变化;再决定继续发消息还是停止。
|
|
41
|
-
只输出严格 JSON。`}function tS(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function tE(e,t){let r=JSON.stringify(function e(t,r){return null===t||"number"==typeof t||"boolean"==typeof t?t:"string"==typeof t?t.length>300?`${t.slice(0,300)}...`:t:r>=4?"[nested]":Array.isArray(t)?t.slice(0,3).map(t=>e(t,r+1)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).sort(([e],[t])=>tj(e)-tj(t)).slice(0,20).map(([t,n])=>[t,e(n,r+1)])):String(t)}(e,0));return r.length<=t?r:`${r.slice(0,t)}...`}function tj(e){let t=e.toLowerCase();return"error_code"===t||"error_msg"===t?0:"restaurant_id"===t||"item_id"===t||"order_id"===t||"address_id"===t||"sku_code"===t?1:"id"===t||"entity_id"===t||t.endsWith("_id")?2:"ok"===t||"name"===t||t.endsWith("_name")||"status"===t||t.endsWith("_status")||"location"===t?3:10}function tk(e,t){if(t&&"object"==typeof t)return t;if(!e)return{};try{let t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}async function tx(e){let r,{chromium:o}=await import("node:module").then(function(e){return n.t(e.createRequire(import.meta.url)("playwright-core"),22)}),a="chrome"===(r=(process.env.DBX_EVAL_BROWSER||"").trim().toLowerCase())?["chrome"]:"chromium"===r?["chromium"]:t?[t]:["chrome","chromium"],i=[];for(let r of a)try{let n=await o.launch(function(e,t){let r={headless:!0,...t};return"chrome"===e?{...r,channel:"chrome"}:{...r,args:["--no-sandbox",...t?.args??[]]}}(r,e));return r!==t&&(t=r,"chromium"===r&&a.length>1&&L.warn("[browser] system Chrome unavailable; using Playwright bundled Chromium.")),n}catch(t){let e=t.message?.split("\n")[0]||String(t);i.push(`${r}: ${e}`)}throw Error(`failed to launch a headless browser (tried ${a.join(", ")}). ${i.join(" | ")}. Install Google Chrome or run 'npx playwright install chromium'.`)}function tP(){return t}let tC=0,tI=null,tA=null;async function tT(e,t,r){let n=++tC,o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:"tools/call",params:{name:t,arguments:r}})});if(!o.ok)throw Error(`wsdMcp ${t} HTTP ${o.status}: ${await o.text()}`);let a=X(await o.text(),o.headers.get("content-type"),n);if(a.error)throw Error(`wsdMcp ${t} error: ${a.error.message}`);return a.result||{}}let tM=null;async function
|
|
41
|
+
只输出严格 JSON。`}function tS(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function tE(e,t){let r=JSON.stringify(function e(t,r){return null===t||"number"==typeof t||"boolean"==typeof t?t:"string"==typeof t?t.length>300?`${t.slice(0,300)}...`:t:r>=4?"[nested]":Array.isArray(t)?t.slice(0,3).map(t=>e(t,r+1)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).sort(([e],[t])=>tj(e)-tj(t)).slice(0,20).map(([t,n])=>[t,e(n,r+1)])):String(t)}(e,0));return r.length<=t?r:`${r.slice(0,t)}...`}function tj(e){let t=e.toLowerCase();return"error_code"===t||"error_msg"===t?0:"restaurant_id"===t||"item_id"===t||"order_id"===t||"address_id"===t||"sku_code"===t?1:"id"===t||"entity_id"===t||t.endsWith("_id")?2:"ok"===t||"name"===t||t.endsWith("_name")||"status"===t||t.endsWith("_status")||"location"===t?3:10}function tk(e,t){if(t&&"object"==typeof t)return t;if(!e)return{};try{let t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}async function tx(e){let r,{chromium:o}=await import("node:module").then(function(e){return n.t(e.createRequire(import.meta.url)("playwright-core"),22)}),a="chrome"===(r=(process.env.DBX_EVAL_BROWSER||"").trim().toLowerCase())?["chrome"]:"chromium"===r?["chromium"]:t?[t]:["chrome","chromium"],i=[];for(let r of a)try{let n=await o.launch(function(e,t){let r={headless:!0,...t};return"chrome"===e?{...r,channel:"chrome"}:{...r,args:["--no-sandbox",...t?.args??[]]}}(r,e));return r!==t&&(t=r,"chromium"===r&&a.length>1&&L.warn("[browser] system Chrome unavailable; using Playwright bundled Chromium.")),n}catch(t){let e=t.message?.split("\n")[0]||String(t);i.push(`${r}: ${e}`)}throw Error(`failed to launch a headless browser (tried ${a.join(", ")}). ${i.join(" | ")}. Install Google Chrome or run 'npx playwright install chromium'.`)}function tP(){return t}let tC=0,tI=null,tA=null;async function tT(e,t,r){let n=++tC,o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:"tools/call",params:{name:t,arguments:r}})});if(!o.ok)throw Error(`wsdMcp ${t} HTTP ${o.status}: ${await o.text()}`);let a=X(await o.text(),o.headers.get("content-type"),n);if(a.error)throw Error(`wsdMcp ${t} error: ${a.error.message}`);return a.result||{}}let tM=null;async function tN(e,t=2e4){let r=Date.now()+t;for(;Date.now()<r;){try{let t=await tT(e,"list_render_targets",{type:"all"}),r=t?.structuredContent?.widgets;if(Array.isArray(r)&&r.length>0)return!0}catch{}await new Promise(e=>setTimeout(e,800))}return!1}async function tO(e){if(tM)try{if(tA){try{await tA.close()}catch{}tA=null}if(tI){try{await tI.close()}catch{}tI=null}tI=await tx(),tA=await tI.newPage(),await tA.goto(tM,{waitUntil:"domcontentloaded",timeout:3e4}),await tN(e,2e4)}catch{}}async function tD(e,t,r=2e4){if(tM=t,tA)return!0;L.log(`[gen-trajectory] Launching headless Chromium for ${t} ...`);try{tI=await tx(),tA=await tI.newPage(),await tA.goto(t,{waitUntil:"domcontentloaded",timeout:3e4})}catch(e){return L.warn(`[gen-trajectory] 截图渲染服务不可用(${E(e)}),已跳过截图`),await tL(),!1}return await tN(e,r)?(await new Promise(e=>setTimeout(e,3e3)),L.log("[gen-trajectory] Headless SDK ready."),!0):(L.warn(`[gen-trajectory] SDK not ready after ${r}ms; screenshots will be skipped.`),await tL(),!1)}async function tL(){if(tA){try{await tA.close()}catch{}tA=null}if(tI){try{await tI.close()}catch{}tI=null}}async function tR(e,t,r,n){let o,a,i;await tO(e);let s=!1;for(let n=0;n<3;n++){o=await tT(e,"render_widget",{widgetId:t,structuredContent:r});let i=o?.structuredContent;if(i?.rendered){s=!0;break}a=i?.error,L.log(`[gen-trajectory] render_widget failed (attempt ${n+1}, ${i?.error?.code||"unknown"}); reloading SPA...`),await tO(e)}if(!s||!o){let t="";try{if(tA){let r=await tT(e,"list_console_messages",{levels:["error","warn"],pageSize:5});t=JSON.stringify(r?.structuredContent||r?.content?.[0]?.text||"").slice(0,500)}}catch{}throw Error(`render_widget did not report rendered:true (err=${JSON.stringify(a).slice(0,200)}${t?`, page=${t}`:""})`)}let l=o.structuredContent?.target?.uid,c="";for(let t=0;t<5;t++){await new Promise(e=>setTimeout(e,500));let t=await tT(e,"take_screenshot",{format:"png",...l&&{uid:l}}),r=t?.content?.find(e=>"image"===e.type&&e.data);if(r?.data){i=r.data;break}c=t?.content?.map(e=>e.text||"").join(" | ")||""}if(!i)throw Error(`take_screenshot returned no image after 5 attempts (last: ${c.slice(0,200)})`);(0,k.writeFileSync)(n,Buffer.from(i,"base64"))}async function tJ(e,t,r,n,o=[]){if(0!==n.length){(0,k.existsSync)(t)||(0,k.mkdirSync)(t,{recursive:!0});for(let a=0;a<n.length;a++){let i=n[a],s=function(e,t,r){let n=function(e){let t=e.result,r=Array.isArray(t?.entities)?t.entities:t?.entity_list;if(Array.isArray(r)&&0!==r.length)return r[0]}(e);if(!n)return;let o=function(e){let t=e.widget_id;if("string"==typeof t)return t;let r=e._meta;if(!r||"object"!=typeof r||Array.isArray(r))return;let n=r.widget_id;return"string"==typeof n?n:void 0}(n)||t?.widget_id||r.find(e=>e.entity_id===n.entity_id)?.widget_id||r.find(e=>e.entity_id===n.order_id)?.widget_id;return o?{widgetId:o,entity:n}:void 0}(i,o[a],o);if(!s)continue;let l=`round-${r}-call-${a+1}-${i.tool_name}.png`,c=(0,x.join)(t,l);try{await tR(e,s.widgetId,s.entity,c),i.screenshot_path=c,L.log("[gen-trajectory] 截图已生成")}catch(e){L.warn(`[gen-trajectory] ${i.tool_name} 截图失败(${E(e)})`)}}}}async function tU(e,t,r={}){let n;e.signal?.throwIfAborted();let o=new Date().toISOString(),a=r.caseLabel||r.caseId||"Trajectory";L.log(`[gen-trajectory] 开始生成评测轨迹(${a},Attempt ${r.attemptK??1})`),r.onDetail?.({title:`${a} \xb7 开始生成轨迹`,technicalName:"gen_trajectory",fields:[["Attempt",r.attemptK??1]]});let i=await et(e.mcp.url,e.app.appId);e.signal?.throwIfAborted();let s=i.tools;L.log(`[gen-trajectory] MCP 服务连接完成(工具 ${s.tools.length} 个)`);try{var l,u,d,p;let m,f,g,_;if(e.dev?.autoStart&&!e.dev.url&&(L.log("[gen-trajectory] Starting isolated eval dev runtime ..."),n=await V(e.dev.autoStart),e.dev={...e.dev,url:n.webDebuggerUrl}),e.dev?.url){let t=e.dev.url,r=new URL(t).origin;await tD(t,r)?L.log("[gen-trajectory] 截图渲染服务已就绪"):(L.warn("[gen-trajectory] 截图渲染服务未就绪,已跳过截图"),e.dev=void 0)}let h=new eN({...e.llm,appKey:e.app.appId},e.signal);r.diagnosticDir&&eG(h,r.diagnosticDir);let y=function(e,t,r={},n){let o=t.map(e=>`- ${e.name}: ${e.description||""}`).join("\n");return`你是小程序评测链路里的真实用户模拟器(User Agent)。你不是裁判,也不是脚本复读器。你的任务:在不泄露后台剧本的前提下,像一个有具体目标的真实用户那样,和被测 AI 助手多轮对话,并且每一轮都根据完整对话历史动态决定说什么、是否纠正、是否继续、是否停止。
|
|
42
42
|
|
|
43
43
|
## 后台剧本(仅供你内部理解,禁止原样说出或泄露给助手)
|
|
44
44
|
${e}
|
|
@@ -88,13 +88,13 @@ ${o}
|
|
|
88
88
|
{"action":"message","message":"你要对助手说的话","reason":"一句话说明为什么这么说","goal_progress":"none|partial|done|blocked","info_released":[],"friction_seen":[],"emotion_delta":0.0}
|
|
89
89
|
或(停止时)
|
|
90
90
|
{"action":"stop","message":"","reason":"停止原因","goal_progress":"done|blocked","info_released":[],"friction_seen":[],"emotion_delta":0.0}`}(t,s.tools,r.scenario,r.referenceTime??o),b=t$(e.app.skills,r.scenario?.initialState),w=[],$=[],v="max_rounds";for(let t=0;t<e.run.maxRounds;t++){let n,o;e.signal?.throwIfAborted();let d=[];try{L.debug(`[gen-trajectory] 开始第 ${t+1} 轮`),r.onDetail?.({title:`${a} \xb7 生成用户输入`,technicalName:"gen_trajectory",fields:[["Round",t+1],["Attempt",r.attemptK??1]]});let c=tv(w,t),p=await ez({llmClient:h,stage:`trajectory:ua:${r.caseId??"unknown"}:k${r.attemptK??1}:round${t+1}`,messages:[{role:"system",content:y},{role:"user",content:c}],completionOptions:{response_format:{type:"json_object"}},parse:tz});if("stop"===p.action){L.log(`[gen-trajectory] 用户模拟结束(Round ${t+1},状态 ${p.goal_progress??"stop"})`),r.onDetail?.({title:`${a} \xb7 用户模拟结束`,technicalName:"gen_trajectory",fields:[["Round",t+1],["状态",p.goal_progress??"stop"]]}),v="ua_stop",m=tG(p);break}n=p.content,o=p,L.debug(`[gen-trajectory] 已生成第 ${t+1} 轮用户输入`),r.onDetail?.({title:`${a} \xb7 执行用户请求`,technicalName:"gen_trajectory",fields:[["Round",t+1],["状态","已生成用户输入"]]});let f=await (l={evalCase:{app_key:e.app.appId,app_name:e.app.appId,query:n,skills:b,manifest:e.app.manifestYAML,mcp:{url:e.mcp.url},history_messages:w,max_step:e.run.maxStep},manifestYAML:e.app.manifestYAML,mcp:s,gatewayOrigin:e.gateway.origin,callbacks:{onToolCall:async e=>{let n=e.arguments_json?JSON.parse(e.arguments_json):{},o=Date.now();L.log(`[gen-trajectory] 正在调用工具:${e.tool_name}(Round ${t+1})`),r.onDetail?.({title:`${a} \xb7 调用工具`,technicalName:"gen_trajectory",fields:[["Round",t+1],["工具",e.tool_name],["状态","调用中"]]});let s=await i.callTool({tool_name:e.tool_name,arguments:n,tool_call_id:e.tool_call_id,server_id:e.server_id,app_key:e.app_key}),l=Date.now()-o;return L.log(`[gen-trajectory] 工具调用完成:${e.tool_name}(${s.is_error?"失败":"成功"},耗时 ${J(l)})`),r.onDetail?.({title:`${a} \xb7 工具返回`,technicalName:"gen_trajectory",fields:[["Round",t+1],["工具",e.tool_name],["状态",s.is_error?"ERROR":"OK"],["耗时",J(l)]]}),s}}},u={signal:e.signal},e6(l,u)),g=f.state;for(let{toolCall:e,result:r}of(d=f.attempts,L.log(`[gen-trajectory] 助手回复生成完成(Round ${t+1},工具调用 ${g.toolCalls.length} 次,卡片 ${g.cards.length} 张)`),L.debug(`[gen-trajectory] 第 ${t+1} 轮完成(工具调用 ${g.toolCalls.length} 次)`),w.push({role:"USER",content:n}),g.toolCalls))w.push({role:"ASSISTANT",content:JSON.stringify({tool_call_id:e.tool_call_id,tool_name:e.tool_name,arguments:e.arguments_json})}),w.push({role:"TOOL",content:r?.content||r?.raw_result_text||JSON.stringify(r?.structured)||""});if(w.push({role:"ASSISTANT",content:g.cards.length>0?`${g.answer}
|
|
91
|
-
[已出卡片 ${g.cards.length} 张]`:g.answer}),$.push(tH(t+1,n,g,"completed",o,d)),e.dev?.url){let t=$[$.length-1],n=r.screenshotSubDir?(0,x.join)(e.dev.screenshotDir,r.screenshotSubDir):e.dev.screenshotDir;await tJ(e.dev.url,n,t.round,t.tool_calls,t.cards),r.onDetail?.({title:`${a} \xb7 截图处理完成`,technicalName:"gen_trajectory",fields:[["Round",t.round],["工具调用",t.tool_calls.length],["截图",t.tool_calls.filter(e=>e.screenshot_path).length]]})}}catch(i){if(e.signal?.aborted)throw e.signal.reason;if(eT(i)||i instanceof eV)throw i;let r=i?.message||String(i),a=i instanceof c?i.logId:void 0;if(L.warn(`[gen-trajectory] 第 ${t+1} 轮异常终止(${
|
|
91
|
+
[已出卡片 ${g.cards.length} 张]`:g.answer}),$.push(tH(t+1,n,g,"completed",o,d)),e.dev?.url){let t=$[$.length-1],n=r.screenshotSubDir?(0,x.join)(e.dev.screenshotDir,r.screenshotSubDir):e.dev.screenshotDir;await tJ(e.dev.url,n,t.round,t.tool_calls,t.cards),r.onDetail?.({title:`${a} \xb7 截图处理完成`,technicalName:"gen_trajectory",fields:[["Round",t.round],["工具调用",t.tool_calls.length],["截图",t.tool_calls.filter(e=>e.screenshot_path).length]]})}}catch(i){if(e.signal?.aborted)throw e.signal.reason;if(eT(i)||i instanceof eV)throw i;let r=i?.message||String(i),a=i instanceof c?i.logId:void 0;if(L.warn(`[gen-trajectory] 第 ${t+1} 轮异常终止(${tq(i)}${a?`,LogID ${a}`:""})`),v="terminated",f=t+1,g=r,_=a,n&&i instanceof c){let e=i instanceof e8?i.attempts:d;$.push(tH(t+1,n,i.state,"terminated",o,e))}break}}if("max_rounds"===v&&$.length===e.run.maxRounds)try{let t=await ez({llmClient:h,stage:`trajectory:ua:${r.caseId??"unknown"}:k${r.attemptK??1}:final`,messages:[{role:"system",content:y},{role:"user",content:(d=e.run.maxRounds,`${tv(w,d)}
|
|
92
92
|
|
|
93
93
|
这是达到最大对话轮次后的终态复核,不会再把 message 发送给助手。
|
|
94
94
|
- 如果成功条件已经全部满足,输出 action=stop、goal_progress=done。
|
|
95
95
|
- 如果核心目标明确无法完成,输出 action=stop、goal_progress=blocked。
|
|
96
96
|
- 只有确实仍需继续对话才能判断或完成目标时,才输出 action=message、goal_progress=partial。
|
|
97
|
-
不得为了结束评测而虚报 done 或 blocked。`)}],completionOptions:{temperature:0,response_format:{type:"json_object"}},parse:tz}),n=(p=t,"stop"===p.action?"ua_stop":"max_rounds");"ua_stop"===n?(v=n,m=tG(t),L.log(`[gen-trajectory] 最终用户状态复核完成(状态 ${m??"stop"})`)):L.warn("[gen-trajectory] 已达到最大轮次,用户目标尚未完成")}catch(t){if(e.signal?.aborted)throw e.signal.reason;L.warn(`[gen-trajectory] 最终用户状态复核失败(${
|
|
97
|
+
不得为了结束评测而虚报 done 或 blocked。`)}],completionOptions:{temperature:0,response_format:{type:"json_object"}},parse:tz}),n=(p=t,"stop"===p.action?"ua_stop":"max_rounds");"ua_stop"===n?(v=n,m=tG(t),L.log(`[gen-trajectory] 最终用户状态复核完成(状态 ${m??"stop"})`)):L.warn("[gen-trajectory] 已达到最大轮次,用户目标尚未完成")}catch(t){if(e.signal?.aborted)throw e.signal.reason;L.warn(`[gen-trajectory] 最终用户状态复核失败(${tq(t)}),保留 max_rounds 状态`)}return{metadata:{app_id:e.app.appId,intent:t,total_rounds:$.length,stop_reason:v,terminal_goal_progress:m,terminated_round:f,termination_error:g,termination_log_id:_,started_at:o,finished_at:new Date().toISOString(),run_id:r.runId,case_id:r.caseId,attempt_k:r.attemptK},rounds:$}}finally{i.close(),await tL(),n&&(L.log("[gen-trajectory] Stopping isolated eval dev runtime ..."),await n.stop().catch(()=>void 0))}}async function tF(e,t,r={}){e.signal?.throwIfAborted();let n=new Date().toISOString(),o=r.caseLabel||r.caseId||"Trajectory";L.log(`[gen-direct-trajectory] 开始生成单轮评测轨迹(${o},Attempt ${r.attemptK??1})`);let a=await et(e.mcp.url,e.app.appId);e.signal?.throwIfAborted();let i=a.tools,s=t$(e.app.skills,r.scenario?.initialState);try{let o,d=[];try{var l,u;let r=await (l={evalCase:{app_key:e.app.appId,app_name:e.app.appId,query:t,skills:s,manifest:e.app.manifestYAML,mcp:{url:e.mcp.url},history_messages:[],max_step:e.run.maxStep},manifestYAML:e.app.manifestYAML,mcp:i,gatewayOrigin:e.gateway.origin,callbacks:{onToolCall:async e=>{let t=e.arguments_json?JSON.parse(e.arguments_json):{},r=Date.now();L.log(`[gen-direct-trajectory] 正在调用工具:${e.tool_name}(Round 1)`);let n=await a.callTool({tool_name:e.tool_name,arguments:t,tool_call_id:e.tool_call_id,server_id:e.server_id,app_key:e.app_key});return L.log(`[gen-direct-trajectory] 工具调用完成:${e.tool_name}(${n.is_error?"失败":"成功"},耗时 ${J(Date.now()-r)})`),n}}},u={signal:e.signal},e6(l,u));o=r.state,d=r.attempts}catch(l){if(e.signal?.aborted)throw e.signal.reason;let o=l?.message||String(l),a=l instanceof c?l.state:void 0,i=l instanceof c?l.logId:void 0,s=l instanceof e8?l.attempts:d;return L.warn(`[gen-direct-trajectory] 单轮轨迹异常终止(${tq(l)}${i?`,LogID ${i}`:""})`),{metadata:{app_id:e.app.appId,intent:t,total_rounds:+!!a,stop_reason:"terminated",terminated_round:1,termination_error:o,termination_log_id:i,started_at:n,finished_at:new Date().toISOString(),run_id:r.runId,case_id:r.caseId,attempt_k:r.attemptK},rounds:a?[tH(1,t,a,"terminated",void 0,s)]:[]}}L.log(`[gen-direct-trajectory] 助手回复生成完成(Round 1,工具调用 ${o.toolCalls.length} 次,卡片 ${o.cards.length} 张)`);let p=tH(1,t,o,"completed",void 0,d);return{metadata:{app_id:e.app.appId,intent:t,total_rounds:1,stop_reason:"ua_stop",started_at:n,finished_at:new Date().toISOString(),run_id:r.runId,case_id:r.caseId,attempt_k:r.attemptK},rounds:[p]}}finally{a.close()}}function tH(e,t,r,n="completed",o,a=[]){return{round:e,status:n,user_query:t,assistant_answer:r.answer,tool_calls:r.toolCalls.map(({toolCall:e,result:t})=>{let n=t?void 0:function(e,t){if(t)for(let r=e.length-1;r>=0;r--){let n=e[r];if("object"==typeof n&&null!==n&&!Array.isArray(n)&&n.tool_call_id===t)return{...n}}}(r.streamErrors,e.tool_call_id);return{tool_name:e.tool_name,tool_call_id:e.tool_call_id,arguments:e.arguments_json?tX(e.arguments_json):void 0,result:t?.structured||t?.content||t?.raw_result_text||n||null,is_error:t?.is_error||void 0!==n}}),cards:r.cards,trace_events:r.traceEvents,simulator_failures:function(e,t){let r=[...t.traceEvents.flatMap(r=>r.error?[tp(e,"trace_event",r.error,{logId:t.logID,toolName:r.tool_name})]:[]),...t.streamErrors.map(r=>{var n;return tp(e,(n=r,tf(n)?.origin==="simulator_tool_report_response")?"tool_report":"stream_error",r,{logId:t.logID})})].flatMap(e=>e?[e]:[]),n=new Map;for(let e of r){let t=[e.family,e.code,e.stage,e.tool_call_id,e.message].join("\0");n.has(t)||n.set(t,e)}return[...n.values()]}(e,r),log_id:r.logID,simulator_attempts:a,ua_decision:o}}async function tK(e,t={}){e.signal?.throwIfAborted();let r=new Date().toISOString();L.debug("[gen-explore] 正在连接 MCP 服务");let n=await et(e.mcp.url,e.app.appId);e.signal?.throwIfAborted();try{var o,a;let i=n.tools.tools,s=i.filter(e5),l=i.filter(e=>!e5(e));L.log(`[gen-explore] MCP 服务连接完成(工具 ${i.length} 个)`),l.length>0&&L.log(`[gen-explore] 已排除写操作工具(${l.length} 个)`);let c=new eN({...e.llm,appKey:e.app.appId},e.signal);t.diagnosticDir&&eG(c,t.diagnosticDir);let u=[],d={},p=new Set,m=tB(t.trajectories,1),f=tB(t.maxSteps,(o=s.length,Math.max(0,3*o))),g=new Set(s.map(e=>e.name)),_=(a=t.referenceTime??r,`你是小程序的随机探索智能体。目标是尽量覆盖不同工具、发现不同类型的实体。
|
|
98
98
|
|
|
99
99
|
${tb(a)}
|
|
100
100
|
|
|
@@ -138,7 +138,7 @@ ${JSON.stringify(e.apiDependencies||{},null,2)}
|
|
|
138
138
|
- 利用历史返回的 ID 调用需要前置数据的工具(如用 restaurant_id 搜菜品)
|
|
139
139
|
${function(e){let t=["- 本轨迹侧重工具覆盖和常见查询参数","- 本轨迹侧重沿依赖关系深挖详情、关联实体和多级查询","- 本轨迹侧重边界筛选、不同关键字和空结果后的参数修正"];return t[(Math.max(e,1)-1)%t.length]}(e.trajectory??1)}
|
|
140
140
|
|
|
141
|
-
请决定下一步。`}({tools:s,traces:o,entityPool:a,toolsCovered:[...i],step:l,trajectory:r,apiDependencies:t.apiDependencies}),h=await tV(c,_,f,g);if(h.done){L.log(`[gen-explore] 探索轨迹 ${r} 已完成(Step ${l+1})`);break}L.log(`[gen-explore] 正在调用工具:${h.tool_name}(轨迹 ${r},Step ${l+1})`);let y=Date.now();try{m=await n.callTool({tool_name:h.tool_name,arguments:h.arguments})}catch(t){if(e.signal?.aborted)throw e.signal.reason;m={content:t.message,is_error:!0}}L.log(`[gen-explore] 工具调用完成:${h.tool_name}(轨迹 ${r},Step ${l+1},${m.is_error?"失败":"成功"},耗时 ${J(Date.now()-y)})`);let b=m.structured||(m.content?tX(m.content):null)||m.content,w=function(e){if(!e||"object"!=typeof e)return[];for(let t of["products","entities","entity_list","items","orders","results","data"])if(Array.isArray(e[t]))return e[t];return Array.isArray(e)?e:Object.keys(e).some(e=>e.includes("id"))?[e]:[]}(b);w.length>0&&(d[h.tool_name]||(d[h.tool_name]=[]),a[h.tool_name]||(a[h.tool_name]=[]),d[h.tool_name].push(...w),a[h.tool_name].push(...w)),m.is_error||(p.add(h.tool_name),i.add(h.tool_name));let $={trajectory:r,step:l+1,tool_name:h.tool_name,arguments:h.arguments,result:b,is_error:m.is_error||!1,entities_extracted:w};o.push($),u.push($)}}let h=s.map(e=>e.name),y=u.filter(e=>e.is_error).length,b=u.length-y,w=h.filter(e=>!p.has(e));return L.log(`[gen-explore] Done. ${m} trajectories, ${u.length} steps (${b} ok / ${y} failed), covered: ${p.size}/${h.length}${w.length?`, uncovered: ${w.join(", ")}`:""}`),{metadata:{app_id:e.app.appId,total_steps:u.length,total_trajectories:m,tools_covered:h.filter(e=>p.has(e)),tools_not_covered:h.filter(e=>!p.has(e)),started_at:r,finished_at:new Date().toISOString(),run_id:t.runId},traces:u,entity_pool:d}}finally{n.close()}}function
|
|
141
|
+
请决定下一步。`}({tools:s,traces:o,entityPool:a,toolsCovered:[...i],step:l,trajectory:r,apiDependencies:t.apiDependencies}),h=await tV(c,_,f,g);if(h.done){L.log(`[gen-explore] 探索轨迹 ${r} 已完成(Step ${l+1})`);break}L.log(`[gen-explore] 正在调用工具:${h.tool_name}(轨迹 ${r},Step ${l+1})`);let y=Date.now();try{m=await n.callTool({tool_name:h.tool_name,arguments:h.arguments})}catch(t){if(e.signal?.aborted)throw e.signal.reason;m={content:t.message,is_error:!0}}L.log(`[gen-explore] 工具调用完成:${h.tool_name}(轨迹 ${r},Step ${l+1},${m.is_error?"失败":"成功"},耗时 ${J(Date.now()-y)})`);let b=m.structured||(m.content?tX(m.content):null)||m.content,w=function(e){if(!e||"object"!=typeof e)return[];for(let t of["products","entities","entity_list","items","orders","results","data"])if(Array.isArray(e[t]))return e[t];return Array.isArray(e)?e:Object.keys(e).some(e=>e.includes("id"))?[e]:[]}(b);w.length>0&&(d[h.tool_name]||(d[h.tool_name]=[]),a[h.tool_name]||(a[h.tool_name]=[]),d[h.tool_name].push(...w),a[h.tool_name].push(...w)),m.is_error||(p.add(h.tool_name),i.add(h.tool_name));let $={trajectory:r,step:l+1,tool_name:h.tool_name,arguments:h.arguments,result:b,is_error:m.is_error||!1,entities_extracted:w};o.push($),u.push($)}}let h=s.map(e=>e.name),y=u.filter(e=>e.is_error).length,b=u.length-y,w=h.filter(e=>!p.has(e));return L.log(`[gen-explore] Done. ${m} trajectories, ${u.length} steps (${b} ok / ${y} failed), covered: ${p.size}/${h.length}${w.length?`, uncovered: ${w.join(", ")}`:""}`),{metadata:{app_id:e.app.appId,total_steps:u.length,total_trajectories:m,tools_covered:h.filter(e=>p.has(e)),tools_not_covered:h.filter(e=>!p.has(e)),started_at:r,finished_at:new Date().toISOString(),run_id:t.runId},traces:u,entity_pool:d}}finally{n.close()}}function tq(e){let t=e instanceof Error&&e.name?e.name:"RuntimeError",r=e instanceof Error?e.message:String(e),n=r.match(/\bHTTP\s+(\d{3})\b/i)?.[1];return n?`${t},HTTP ${n}`:t}function tB(e,t){let r=Number(e);return Number.isInteger(r)&&r>0?r:t}async function tV(e,t,r,n){return ez({llmClient:e,stage:"explore:action",messages:[{role:"system",content:t},{role:"user",content:r}],completionOptions:{response_format:{type:"json_object"}},parse:e=>(function(e,t){var r;let n=eW(e),o="string"==typeof n.selected_function?n.selected_function:"string"==typeof n.tool_name?n.tool_name:void 0;if("__STOP__"===o||!0===n.done)return{done:!0,reason:"string"==typeof n.reasoning?n.reasoning:"string"==typeof n.reason?n.reason:"done"};if(!o)throw Error('response must contain string field "selected_function"');if(!t.has(o))throw Error(`selected_function "${o}" is not an allowed read-only tool`);let a=n.arguments??{};if(!((r=a)&&"object"==typeof r&&!Array.isArray(r)))throw Error('"arguments" must be a JSON object');return{done:!1,tool_name:o,arguments:a}})(e,n),buildRepairPrompt:({error:e})=>{var t;return t=[...n],`上一个 Explore 决策未通过结构校验,请只修复 JSON,不要解释。
|
|
142
142
|
|
|
143
143
|
校验错误:${e}
|
|
144
144
|
允许的只读工具:${JSON.stringify(t)}
|
|
@@ -148,4 +148,4 @@ ${function(e){let t=["- 本轨迹侧重工具覆盖和常见查询参数","- 本
|
|
|
148
148
|
{"selected_function":"__STOP__","arguments":{}}
|
|
149
149
|
|
|
150
150
|
arguments 必须是 JSON 对象,selected_function 必须严格取自允许工具列表。`}})}function tz(e){let t=eW(e),r="string"==typeof t.reason?t.reason.trim():"",n=function(e,t){let r=e.goal_progress;if(void 0!==r&&"none"!==r&&"partial"!==r&&"done"!==r&&"blocked"!==r)throw Error("UA goal_progress is invalid");let n=tW(e.info_released,"info_released"),o=tW(e.friction_seen,"friction_seen"),a=e.emotion_delta;if(void 0!==a&&("number"!=typeof a||!Number.isFinite(a)||a<-1||a>1))throw Error("UA emotion_delta must be a number between -1 and 1");return{reason:t,...r?{goal_progress:r}:{},...n?{info_released:n}:{},...o?{friction_seen:o}:{},..."number"==typeof a?{emotion_delta:a}:{}}}(t,r);if("message"===t.action){let e="string"==typeof t.message?t.message:t.content,o="string"!=typeof t.message;if("string"==typeof e&&e.trim()&&(o||r))return{action:"message",content:e,...n}}if("stop"===t.action&&r){if(n.goal_progress&&"done"!==n.goal_progress&&"blocked"!==n.goal_progress)throw Error("UA stop goal_progress must be done or blocked");return{action:"stop",brief_title:"string"==typeof t.brief_title?t.brief_title:"用户模拟结束",...n}}throw Error(`Invalid UA action: ${e.trim().slice(0,100)}`)}function tG(e){return"done"===e.goal_progress||"blocked"===e.goal_progress?e.goal_progress:void 0}function tW(e,t){if(void 0!==e){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(`UA ${t} must be a string array`);return e}}function tX(e){try{return JSON.parse(e)}catch{return e}}let tZ=n("../../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js");async function tY(e){let t,r,n,o=(0,k.existsSync)((0,x.join)((0,x.resolve)(e.projectPath),".dbx","config.json"));try{({simulatorManifestPath:t,skillsDirectory:r}=d({projectPath:e.projectPath,manifest:e.manifest,skill:e.skill}))}catch(e){if(o)throw Error(`dbx eval cannot start the screenshot runtime: ${e.message}`);return}if(!t||!r){if(o){let e=t?"skill":"manifest";throw Error(`dbx eval cannot start the screenshot runtime: ${e} file not found`)}return}let a=function(e){let t=_(e).frontend;if(i(t)&&"string"==typeof t.directory){let r=t.directory.trim();if(r)return(0,x.resolve)(e,r)}return e}(e.projectPath);try{n=(await p(t)).manifest}catch(e){if(e?.message?.includes("Not logged in")||e?.message?.includes("Token expired")||e?.constructor?.name==="NotLoggedInError"||e?.constructor?.name==="TokenExpiredError")try{n=tZ.qg((0,k.readFileSync)(t,"utf8"))}catch(e){if(o)throw Error(`dbx eval cannot parse manifest: ${e.message}`);return}else{if(o)throw Error(`dbx eval cannot validate the screenshot runtime manifest: ${e.message}`);return}}let s=f(t),l=await m(process.env,void 0,t,n);if(!l){if(o)throw Error("dbx eval cannot start the screenshot runtime: MCP endpoint not resolved");return}return{miniappDir:a,simulatorManifestPath:t,skillsDirectory:r,mcpEndpoint:l,appId:s}}let tQ=(0,x.join)((0,F.homedir)(),".dbx","config.yaml");function t0(){if(void 0!==r)return r??{};try{if(!(0,k.existsSync)(tQ))return r=null,{};let e=(0,k.readFileSync)(tQ,"utf-8"),t=tZ.qg(e);if(t&&"object"==typeof t&&!Array.isArray(t))return r=t;return r=null,{}}catch{return r=null,{}}}function t1(e){return t9(e,20,100)}function t2(e){return t9(e,1,2)}function t3(e){return t9(e,10,20)}function t4(e){return t6(e,1,2)}function t5(e){return{...e,intentCount:t6(e.intentCount,20,100),explicitIntents:e.explicitIntents?.slice(0,100),concurrency:t4(e.concurrency),checklistConcurrency:t4(e.checklistConcurrency),scoringConcurrency:t4(e.scoringConcurrency),judgeConcurrency:t4(e.judgeConcurrency),maxRounds:t6(e.maxRounds,10,20)}}function t9(e,t,r){if(void 0===e||""===e)return t;let n=Number(e);return Number.isInteger(n)?Math.min(n,r):NaN}function t6(e,t,r){return Number.isFinite(e)?Math.min(Math.max(Math.floor(e),1),r):t}let t8=[".dbx","eval.yaml"],t7=["ua","judge","gateway","app","mcp","run"];class re extends Error{cause;code;configPath;missingFields;issues;constructor(e){super(e.message),void 0!==e.cause&&(this.cause=e.cause),this.name="EvalProjectConfigError",this.code=e.code,this.configPath=e.configPath,this.missingFields=e.missingFields??[],this.issues=e.issues??[]}}function rt(e){return(0,x.resolve)(e,...t8)}function rr(e){let t,r=(0,x.resolve)(e);try{t=tZ.qg((0,k.readFileSync)(r,"utf8"))}catch(e){throw new re({code:"EVAL_CONFIG_INVALID",configPath:r,message:`Invalid Eval config at ${r}: ${e.message}`,cause:e})}if(!i(t))throw new re({code:"EVAL_CONFIG_INVALID",configPath:r,message:`Invalid Eval config at ${r}: YAML root must be a mapping`});let n=t7.flatMap(e=>void 0===t[e]||i(t[e])?[]:[`${e} must be a mapping`]);if(n.length>0)throw new re({code:"EVAL_CONFIG_INVALID",configPath:r,message:`Invalid Eval config at ${r}: ${n.join("; ")}`,issues:n});return t}function rn(e){try{let t=tZ.qg(e);if(!i(t)||!i(t.mcp_server))return;let r=t.mcp_server.end_point;return"string"==typeof r&&r.trim()?r.trim():void 0}catch{return}}function ro(e){let t=rt((0,x.resolve)(e.projectPath)),r={},n="generated";return e.explicitConfigPath?(r=rr(e.explicitConfigPath),n="explicit"):(0,k.existsSync)(t)&&(r=rr(t),n="project"),{config:rs(e.globalConfig??{},r,e.cliOverrides??{}),configPath:t,source:n}}function ra(e,t){var r,n,o;let a,i,s=(0,x.resolve)(t.projectPath),l=t.configPath??rt(t.projectPath),c=[],u=[],d=e.run?.mode==="score_only";d?ru(e.judge)?rd(e.judge,"judge",u,e.ua):rd(e.ua,"ua",u):(rd(e.ua,"ua",u),ru(e.judge)&&rd(e.judge,"judge",u,e.ua));let p=d?void 0:rc(e.app?.manifest,"app.manifest",c),m=d?void 0:rc(e.app?.skill,"app.skill",c);for(let[t,l]of(d?rc(e.run?.eval_bundle,"run.eval_bundle",c):(rc(e.app?.app_id,"app.app_id",c),rc(e.mcp?.url,"mcp.url",c)),p&&rf(s,p,"app.manifest",u),m&&(r=s,n=m,o=u,"resolved"!==(i=y(a=(0,x.isAbsolute)(n)?(0,x.resolve)(n):(0,x.resolve)(r,n))).layout&&o.push(i.error??`app.skill: skill directory contains no runtime Skill: ${a}; add at least one regular file named SKILL.md anywhere under it`)),e.run?.eval_bundle&&rf(s,e.run.eval_bundle,"run.eval_bundle",u),e.run?.rubrics&&rf(s,e.run.rubrics,"run.rubrics",u),rg(e.ua?.base_url,"ua.base_url",u),rg(e.judge?.base_url,"judge.base_url",u),rg(e.gateway?.origin,"gateway.origin",u),d||rg(e.mcp?.url,"mcp.url",u),r_(e.ua?.temperature,"ua.temperature",u),r_(e.judge?.temperature,"judge.temperature",u),rh(e.ua?.max_tokens,"ua.max_tokens",u),rh(e.judge?.max_tokens,"judge.max_tokens",u),ry(e.run?.mode,"run.mode",["full_pipeline","rollout_and_score","score_only"],u),ry(e.run?.rollout_mode,"run.rollout_mode",["ua_driven","direct"],u),[["run.intent_count",e.run?.intent_count],["run.pass_k",e.run?.pass_k],["run.concurrency",e.run?.concurrency],["run.checklist_concurrency",e.run?.checklist_concurrency],["run.scoring_concurrency",e.run?.scoring_concurrency],["run.judge_concurrency",e.run?.judge_concurrency],["run.max_rounds",e.run?.max_rounds],["run.max_step",e.run?.max_step],["run.explore_trajectories",e.run?.explore_trajectories],["run.explore_max_steps",e.run?.explore_max_steps]]))rh(l,t,u);if(e.run?.pass_threshold!==void 0){let t=Number(e.run.pass_threshold);(!Number.isFinite(t)||t<0||t>1)&&u.push("run.pass_threshold must be between 0 and 1")}if(c.length>0||u.length>0){let e=[...c.length>0?["Missing required Eval configuration:",...c.map(e=>`- ${e}`)]:[],...u.length>0?["Invalid Eval configuration:",...u.map(e=>`- ${e}`)]:[]];throw new re({code:c.length>0?"EVAL_PROJECT_CONFIG_INCOMPLETE":"EVAL_CONFIG_INVALID",configPath:l,missingFields:c,issues:u,message:[`Project Eval config invalid: ${l}`,"",...e,"","Provide the missing values with -c/CLI flags, or use the dbx-eval Skill to create the project configuration."].join("\n")})}return e}function ri(e,t){var r,n;let o=(0,x.resolve)(e),a=rt(o),i=(0,x.dirname)(a),s=(r=o,rs(n=t,{app:n.app?{...n.app,manifest:rl(r,n.app.manifest),skill:rl(r,n.app.skill)}:void 0,run:n.run?{...n.run,output_dir:rl(r,n.run.output_dir),eval_bundle:rl(r,n.run.eval_bundle),prebuilt_trajectories:rl(r,n.run.prebuilt_trajectories),rubrics:rl(r,n.run.rubrics)}:void 0})),l=`${a}.${process.pid}.${Date.now()}.tmp`,c=(0,k.existsSync)(i);(0,k.mkdirSync)(i,{recursive:!0,mode:448}),c||rb(i,448);try{(0,k.writeFileSync)(l,`# Contains plaintext LLM credentials. Do not commit or share this file.
|
|
151
|
-
${tZ.As(s,{lineWidth:0})}`,{encoding:"utf8",mode:384}),rb(l,384),(0,k.renameSync)(l,a),rb(a,384)}catch(e){throw(0,k.rmSync)(l,{force:!0}),e}return a}function rs(...e){let t={};for(let r of e)for(let[e,n]of Object.entries(r)){if(void 0===n)continue;let r=t[e];t[e]=i(r)&&i(n)?function(e,t){let r={...e};for(let[e,n]of Object.entries(t))void 0!==n&&(r[e]=n);return r}(r,n):n}return t}function rl(e,t){if(!t?.trim())return t;let r=(0,x.isAbsolute)(t)?(0,x.resolve)(t):(0,x.resolve)(e,t),n=(0,x.relative)(e,r);return""!==n&&(n.startsWith(`..${x.sep}`)||".."===n||(0,x.isAbsolute)(n))?r:n?`./${n.split(x.sep).join("/")}`:"."}function rc(e,t,r){return"string"==typeof e&&e.trim()?e.trim():void r.push(t)}function ru(e){return!!e&&(rm(e.base_url)||rm(e.api_key)||rm(e.model))}function rd(e,t,r,n){let o=rp(e?.base_url,n?.base_url),a=rp(e?.api_key,n?.api_key),i=rp(e?.model,n?.model);if(!o&&!a)return;let s=[o?void 0:"base_url",a?void 0:"api_key",i?void 0:"model"].filter(e=>!!e);if(0===s.length)return;let l=n?" after inheriting ua fields":"";r.push(`${t} effective LLM config${l} must either omit base_url/api_key to use the gateway, or provide base_url/api_key/model for a custom endpoint (missing: ${s.join(", ")})`)}function rp(e,t){return rm(e)?String(e).trim():rm(t)?String(t).trim():void 0}function rm(e){return"string"==typeof e&&e.trim().length>0}function rf(e,t,r,n){let o=(0,x.isAbsolute)(t)?(0,x.resolve)(t):(0,x.resolve)(e,t);try{(0,k.statSync)(o).isFile()||n.push(`${r} is not a file: ${o}`)}catch{n.push(`${r} file not found: ${o}`)}}function rg(e,t,r){if(void 0!==e&&""!==e){if("string"!=typeof e)return void r.push(`${t} must be a URL string`);try{let n=new URL(e);"http:"!==n.protocol&&"https:"!==n.protocol&&r.push(`${t} must use http or https`)}catch{r.push(`${t} must be an absolute URL`)}}}function r_(e,t,r){void 0!==e&&""!==e&&(Number.isFinite(Number(e))||r.push(`${t} must be a number`))}function rh(e,t,r,n=!1){if(void 0===e||""===e)return;let o=Number(e);(!Number.isInteger(o)||(n?o<0:o<=0))&&r.push(`${t} must be ${n?"a non-negative":"a positive"} integer`)}function ry(e,t,r,n){void 0!==e&&""!==e&&("string"==typeof e&&r.includes(e)||n.push(`${t} must be one of: ${r.join(", ")}`))}function rb(e,t){if("win32"!==process.platform)try{(0,k.chmodSync)(e,t)}catch{}}async function rw(e){let t=(0,x.resolve)(e.projectPath),r=ro({projectPath:t,explicitConfigPath:e.config,globalConfig:t0(),cliOverrides:{ua:{base_url:e.baseUrl,api_key:e.apiKey,model:e.model},gateway:{origin:e.gateway},app:{manifest:e.manifest,skill:e.skill,app_id:e.appId},mcp:{url:e.mcpUrl},run:{max_rounds:e.maxRounds,max_step:e.maxStep}}}),n=r.config,o=n.ua??{},a=n.app??{},i=n.run??{},s=(0,x.resolve)(t,a.manifest||"manifest.yaml"),l=(0,x.resolve)(t,a.skill||"skill");(0,k.existsSync)(s)&&(0,k.existsSync)(l)||ra(rs(n,{app:{manifest:s,skill:l,app_id:r$(a.app_id)||void 0}}),{projectPath:t,configPath:r.configPath});let c=(0,k.readFileSync)(s,"utf-8"),u=h(l).map(e=>e.content),d=g(t,a.app_id||void 0,s),p=r$(n.mcp?.url)||rn(c)||r$(process.env.DOUBAO_SIMULATOR_MCP_ENDPOINT)||"",m=rs(n,{ua:{base_url:r$(o.base_url)||void 0,api_key:r$(o.api_key)||void 0,model:r$(o.model)||void 0,temperature:rv(o.temperature,.7),max_tokens:rS(o.max_tokens,4096),api_format:r$(o.api_format)||void 0},gateway:{origin:r$(n.gateway?.origin)||"https://doubao-developer.bytedance.net"},app:{manifest:s,skill:l,app_id:d},mcp:{url:p},run:{mode:r$(i.mode)||"full_pipeline",rollout_mode:r$(i.rollout_mode)||"ua_driven",intent_count:t1(i.intent_count),pass_k:rS(i.pass_k,1),concurrency:t2(i.concurrency),checklist_concurrency:t2(i.checklist_concurrency),scoring_concurrency:t2(i.scoring_concurrency),judge_concurrency:t2(i.judge_concurrency),pass_threshold:rv(i.pass_threshold,.6),max_rounds:t3(i.max_rounds),max_step:rS(i.max_step,8),output_dir:r$(i.output_dir)||"./data",skip_render:rE(i.skip_render),push_lark:rE(i.push_lark),lark_doc_token:r$(i.lark_doc_token)||void 0,prebuilt_trajectories:r$(i.prebuilt_trajectories)||void 0}});ra(m,{projectPath:t,configPath:r.configPath}),ri(t,m);let f=rE(m.run?.skip_render)?void 0:await tY({projectPath:t,manifest:m.app?.manifest,skill:m.app?.skill});return{llm:{baseUrl:r$(m.ua?.base_url)||void 0,apiKey:r$(m.ua?.api_key)||void 0,model:r$(m.ua?.model)||void 0,temperature:rv(m.ua?.temperature,.7),maxTokens:rS(m.ua?.max_tokens,4096)},gateway:{origin:r$(m.gateway?.origin)||"https://doubao-developer.bytedance.net",headers:{"X-TT-ENV":"","X-USE-PPE":"","x-schedule-vdc":"hl","Developer-Open-UserId":"i_1234"}},app:{appId:d,skills:u,manifestYAML:c},mcp:{url:p},dev:f?{screenshotDir:"",autoStart:f}:void 0,run:{maxRounds:t3(m.run?.max_rounds),maxStep:rS(m.run?.max_step,8)}}}function r$(e){return"string"==typeof e?e.trim():""}function rv(e,t){let r=Number(e);return Number.isFinite(r)?r:t}function rS(e,t){let r="string"==typeof e?e.trim():e;if(null==r||""===r)return t;if("string"!=typeof r&&"number"!=typeof r)return NaN;let n=Number(r);return Number.isInteger(n)?n:NaN}function rE(e){return!0===e||"true"===e}export{eE as DEFAULT_EVAL_MODEL_ALIAS,
|
|
151
|
+
${tZ.As(s,{lineWidth:0})}`,{encoding:"utf8",mode:384}),rb(l,384),(0,k.renameSync)(l,a),rb(a,384)}catch(e){throw(0,k.rmSync)(l,{force:!0}),e}return a}function rs(...e){let t={};for(let r of e)for(let[e,n]of Object.entries(r)){if(void 0===n)continue;let r=t[e];t[e]=i(r)&&i(n)?function(e,t){let r={...e};for(let[e,n]of Object.entries(t))void 0!==n&&(r[e]=n);return r}(r,n):n}return t}function rl(e,t){if(!t?.trim())return t;let r=(0,x.isAbsolute)(t)?(0,x.resolve)(t):(0,x.resolve)(e,t),n=(0,x.relative)(e,r);return""!==n&&(n.startsWith(`..${x.sep}`)||".."===n||(0,x.isAbsolute)(n))?r:n?`./${n.split(x.sep).join("/")}`:"."}function rc(e,t,r){return"string"==typeof e&&e.trim()?e.trim():void r.push(t)}function ru(e){return!!e&&(rm(e.base_url)||rm(e.api_key)||rm(e.model))}function rd(e,t,r,n){let o=rp(e?.base_url,n?.base_url),a=rp(e?.api_key,n?.api_key),i=rp(e?.model,n?.model);if(!o&&!a)return;let s=[o?void 0:"base_url",a?void 0:"api_key",i?void 0:"model"].filter(e=>!!e);if(0===s.length)return;let l=n?" after inheriting ua fields":"";r.push(`${t} effective LLM config${l} must either omit base_url/api_key to use the gateway, or provide base_url/api_key/model for a custom endpoint (missing: ${s.join(", ")})`)}function rp(e,t){return rm(e)?String(e).trim():rm(t)?String(t).trim():void 0}function rm(e){return"string"==typeof e&&e.trim().length>0}function rf(e,t,r,n){let o=(0,x.isAbsolute)(t)?(0,x.resolve)(t):(0,x.resolve)(e,t);try{(0,k.statSync)(o).isFile()||n.push(`${r} is not a file: ${o}`)}catch{n.push(`${r} file not found: ${o}`)}}function rg(e,t,r){if(void 0!==e&&""!==e){if("string"!=typeof e)return void r.push(`${t} must be a URL string`);try{let n=new URL(e);"http:"!==n.protocol&&"https:"!==n.protocol&&r.push(`${t} must use http or https`)}catch{r.push(`${t} must be an absolute URL`)}}}function r_(e,t,r){void 0!==e&&""!==e&&(Number.isFinite(Number(e))||r.push(`${t} must be a number`))}function rh(e,t,r,n=!1){if(void 0===e||""===e)return;let o=Number(e);(!Number.isInteger(o)||(n?o<0:o<=0))&&r.push(`${t} must be ${n?"a non-negative":"a positive"} integer`)}function ry(e,t,r,n){void 0!==e&&""!==e&&("string"==typeof e&&r.includes(e)||n.push(`${t} must be one of: ${r.join(", ")}`))}function rb(e,t){if("win32"!==process.platform)try{(0,k.chmodSync)(e,t)}catch{}}async function rw(e){let t=(0,x.resolve)(e.projectPath),r=ro({projectPath:t,explicitConfigPath:e.config,globalConfig:t0(),cliOverrides:{ua:{base_url:e.baseUrl,api_key:e.apiKey,model:e.model},gateway:{origin:e.gateway},app:{manifest:e.manifest,skill:e.skill,app_id:e.appId},mcp:{url:e.mcpUrl},run:{max_rounds:e.maxRounds,max_step:e.maxStep}}}),n=r.config,o=n.ua??{},a=n.app??{},i=n.run??{},s=(0,x.resolve)(t,a.manifest||"manifest.yaml"),l=(0,x.resolve)(t,a.skill||"skill");(0,k.existsSync)(s)&&(0,k.existsSync)(l)||ra(rs(n,{app:{manifest:s,skill:l,app_id:r$(a.app_id)||void 0}}),{projectPath:t,configPath:r.configPath});let c=(0,k.readFileSync)(s,"utf-8"),u=h(l).map(e=>e.content),d=g(t,a.app_id||void 0,s),p=r$(n.mcp?.url)||rn(c)||r$(process.env.DOUBAO_SIMULATOR_MCP_ENDPOINT)||"",m=rs(n,{ua:{base_url:r$(o.base_url)||void 0,api_key:r$(o.api_key)||void 0,model:r$(o.model)||void 0,temperature:rv(o.temperature,.7),max_tokens:rS(o.max_tokens,4096),api_format:r$(o.api_format)||void 0},gateway:{origin:r$(n.gateway?.origin)||"https://doubao-developer.bytedance.net"},app:{manifest:s,skill:l,app_id:d},mcp:{url:p},run:{mode:r$(i.mode)||"full_pipeline",rollout_mode:r$(i.rollout_mode)||"ua_driven",intent_count:t1(i.intent_count),pass_k:rS(i.pass_k,1),concurrency:t2(i.concurrency),checklist_concurrency:t2(i.checklist_concurrency),scoring_concurrency:t2(i.scoring_concurrency),judge_concurrency:t2(i.judge_concurrency),pass_threshold:rv(i.pass_threshold,.6),max_rounds:t3(i.max_rounds),max_step:rS(i.max_step,8),output_dir:r$(i.output_dir)||"./data",skip_render:rE(i.skip_render),push_lark:rE(i.push_lark),lark_doc_token:r$(i.lark_doc_token)||void 0,prebuilt_trajectories:r$(i.prebuilt_trajectories)||void 0}});ra(m,{projectPath:t,configPath:r.configPath}),ri(t,m);let f=rE(m.run?.skip_render)?void 0:await tY({projectPath:t,manifest:m.app?.manifest,skill:m.app?.skill});return{llm:{baseUrl:r$(m.ua?.base_url)||void 0,apiKey:r$(m.ua?.api_key)||void 0,model:r$(m.ua?.model)||void 0,temperature:rv(m.ua?.temperature,.7),maxTokens:rS(m.ua?.max_tokens,4096)},gateway:{origin:r$(m.gateway?.origin)||"https://doubao-developer.bytedance.net",headers:{"X-TT-ENV":"","X-USE-PPE":"","x-schedule-vdc":"hl","Developer-Open-UserId":"i_1234"}},app:{appId:d,skills:u,manifestYAML:c},mcp:{url:p},dev:f?{screenshotDir:"",autoStart:f}:void 0,run:{maxRounds:t3(m.run?.max_rounds),maxStep:rS(m.run?.max_step,8)}}}function r$(e){return"string"==typeof e?e.trim():""}function rv(e,t){let r=Number(e);return Number.isFinite(r)?r:t}function rS(e,t){let r="string"==typeof e?e.trim():e;if(null==r||""===r)return t;if("string"!=typeof r&&"number"!=typeof r)return NaN;let n=Number(r);return Number.isInteger(n)?n:NaN}function rE(e){return!0===e||"true"===e}export{eE as DEFAULT_EVAL_MODEL_ALIAS,K as EvalDevRuntimeProcessError,eN as LLMClient,eI as LLMRequestTimeoutError,eC as LLMResponseError,eV as StructuredOutputError,rE as booleanValue,tY as buildAutoStartPayload,rw as buildConfig,td as classifyAttemptExecution,ty as createReferenceTime,ee as fetchMCPDescriptor,J as formatMs,tb as formatReferenceTimeContext,tF as genDirectTrajectory,tK as genExplore,tU as genTrajectory,tP as getActiveBrowserStrategy,rS as integerConfigValue,eM as isAppQuotaExhausted,eT as isGatewayAuthFailure,tu as isPostHookFailure,tx as launchHeadlessBrowser,t5 as limitPipelineRunConfig,t2 as limitedEvalConcurrency,t1 as limitedIntentCount,t3 as limitedMaxRounds,t0 as loadGlobalConfig,L as logger,rs as mergeEvalConfigs,rv as numberValue,eW as parseJSONObject,X as parseMCPHTTPBody,rt as projectEvalConfigPath,rr as project_config_readEvalConfigFile,rn as readManifestMcpUrl,eG as registerStructuredOutputDiagnostics,ez as requestStructuredOutput,ro as resolveProjectEvalConfig,S as sanitizeDetailField,v as sanitizeLogText,j as sanitizeProgressFailure,I as setTerminalMuted,r$ as shared_stringValue,V as startEvalDevRuntime,E as summarizeLogError,R as timed,ra as validateProjectEvalConfig,ri as writeProjectEvalConfig,eX as writeStructuredOutputDiagnostic};
|
package/dist/4931.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
let e;import"node:module";import{__webpack_require__ as t}from"./rslib-runtime.js";import{onExit as i,external_node_process_namespaceObject as l,external_node_readline_namespaceObject as n}from"./1664.js";import"./180.js";t.add({"../../../node_modules/.pnpm/cli-width@4.1.0/node_modules/cli-width/index.js"(e,t,i){e.exports=function(e){let t,l=(t={defaultWidth:0,output:process.stdout,tty:i("tty")},e?(Object.keys(t).forEach(function(i){e[i]||(e[i]=t[i])}),e):t);if(l.output.getWindowSize)return l.output.getWindowSize()[0]||l.defaultWidth;if(l.tty.getWindowSize)return l.tty.getWindowSize()[1]||l.defaultWidth;if(l.output.columns)return l.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&0!==e)return e}return l.defaultWidth}},"../../../node_modules/.pnpm/mute-stream@3.0.0/node_modules/mute-stream/lib/index.js"(e,t,i){let l=i("stream");e.exports=class extends l{#e=null;constructor(e={}){super(e),this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){return this._dest?this._dest[e]:this._src?this._src[e]:t}#i(e,...t){"function"==typeof this._dest?.[e]&&this._dest[e](...t),"function"==typeof this._src?.[e]&&this._src[e](...t)}get isTTY(){return null!==this.#e?this.#e:this.#t("isTTY",!1)}set isTTY(e){this.#e=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/))return 0===e.indexOf(this._prompt)&&(e=(e=e.slice(this._prompt.length)).replace(/./g,this.replace),e=this._prompt+e),this._hadControl=!0,this.emit("data",e);this._prompt&&this._hadControl&&0===e.indexOf(this._prompt)&&(this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length)),e=e.toString().replace(/./g,this.replace)}this.emit("data",e)}end(e){this.muted&&(e=e&&this.replace?e.toString().replace(/./g,this.replace):null),e&&this.emit("data",e),this.emit("end")}destroy(...e){return this.#i("destroy",...e)}destroySoon(...e){return this.#i("destroySoon",...e)}close(...e){return this.#i("close",...e)}}}});let o={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"█",squareDarkShade:"▓",squareMediumShade:"▒",squareLightShade:"░",squareTop:"▀",squareBottom:"▄",squareLeft:"▌",squareRight:"▐",squareCenter:"■",bullet:"●",dot:"․",ellipsis:"…",pointerSmall:"›",triangleUp:"▲",triangleUpSmall:"▴",triangleDown:"▼",triangleDownSmall:"▾",triangleLeftSmall:"◂",triangleRightSmall:"▸",home:"⌂",heart:"♥",musicNote:"♪",musicNoteBeamed:"♫",arrowUp:"↑",arrowDown:"↓",arrowLeft:"←",arrowRight:"→",arrowLeftRight:"↔",arrowUpDown:"↕",almostEqual:"≈",notEqual:"≠",lessOrEqual:"≤",greaterOrEqual:"≥",identical:"≡",infinity:"∞",subscriptZero:"₀",subscriptOne:"₁",subscriptTwo:"₂",subscriptThree:"₃",subscriptFour:"₄",subscriptFive:"₅",subscriptSix:"₆",subscriptSeven:"₇",subscriptEight:"₈",subscriptNine:"₉",oneHalf:"\xbd",oneThird:"⅓",oneQuarter:"\xbc",oneFifth:"⅕",oneSixth:"⅙",oneEighth:"⅛",twoThirds:"⅔",twoFifths:"⅖",threeQuarters:"\xbe",threeFifths:"⅗",threeEighths:"⅜",fourFifths:"⅘",fiveSixths:"⅚",fiveEighths:"⅝",sevenEighths:"⅞",line:"─",lineBold:"━",lineDouble:"═",lineDashed0:"┄",lineDashed1:"┅",lineDashed2:"┈",lineDashed3:"┉",lineDashed4:"╌",lineDashed5:"╍",lineDashed6:"╴",lineDashed7:"╶",lineDashed8:"╸",lineDashed9:"╺",lineDashed10:"╼",lineDashed11:"╾",lineDashed12:"−",lineDashed13:"–",lineDashed14:"‐",lineDashed15:"⁃",lineVertical:"│",lineVerticalBold:"┃",lineVerticalDouble:"║",lineVerticalDashed0:"┆",lineVerticalDashed1:"┇",lineVerticalDashed2:"┊",lineVerticalDashed3:"┋",lineVerticalDashed4:"╎",lineVerticalDashed5:"╏",lineVerticalDashed6:"╵",lineVerticalDashed7:"╷",lineVerticalDashed8:"╹",lineVerticalDashed9:"╻",lineVerticalDashed10:"╽",lineVerticalDashed11:"╿",lineDownLeft:"┐",lineDownLeftArc:"╮",lineDownBoldLeftBold:"┓",lineDownBoldLeft:"┒",lineDownLeftBold:"┑",lineDownDoubleLeftDouble:"╗",lineDownDoubleLeft:"╖",lineDownLeftDouble:"╕",lineDownRight:"┌",lineDownRightArc:"╭",lineDownBoldRightBold:"┏",lineDownBoldRight:"┎",lineDownRightBold:"┍",lineDownDoubleRightDouble:"╔",lineDownDoubleRight:"╓",lineDownRightDouble:"╒",lineUpLeft:"┘",lineUpLeftArc:"╯",lineUpBoldLeftBold:"┛",lineUpBoldLeft:"┚",lineUpLeftBold:"┙",lineUpDoubleLeftDouble:"╝",lineUpDoubleLeft:"╜",lineUpLeftDouble:"╛",lineUpRight:"└",lineUpRightArc:"╰",lineUpBoldRightBold:"┗",lineUpBoldRight:"┖",lineUpRightBold:"┕",lineUpDoubleRightDouble:"╚",lineUpDoubleRight:"╙",lineUpRightDouble:"╘",lineUpDownLeft:"┤",lineUpBoldDownBoldLeftBold:"┫",lineUpBoldDownBoldLeft:"┨",lineUpDownLeftBold:"┥",lineUpBoldDownLeftBold:"┩",lineUpDownBoldLeftBold:"┪",lineUpDownBoldLeft:"┧",lineUpBoldDownLeft:"┦",lineUpDoubleDownDoubleLeftDouble:"╣",lineUpDoubleDownDoubleLeft:"╢",lineUpDownLeftDouble:"╡",lineUpDownRight:"├",lineUpBoldDownBoldRightBold:"┣",lineUpBoldDownBoldRight:"┠",lineUpDownRightBold:"┝",lineUpBoldDownRightBold:"┡",lineUpDownBoldRightBold:"┢",lineUpDownBoldRight:"┟",lineUpBoldDownRight:"┞",lineUpDoubleDownDoubleRightDouble:"╠",lineUpDoubleDownDoubleRight:"╟",lineUpDownRightDouble:"╞",lineDownLeftRight:"┬",lineDownBoldLeftBoldRightBold:"┳",lineDownLeftBoldRightBold:"┯",lineDownBoldLeftRight:"┰",lineDownBoldLeftBoldRight:"┱",lineDownBoldLeftRightBold:"┲",lineDownLeftRightBold:"┮",lineDownLeftBoldRight:"┭",lineDownDoubleLeftDoubleRightDouble:"╦",lineDownDoubleLeftRight:"╥",lineDownLeftDoubleRightDouble:"╤",lineUpLeftRight:"┴",lineUpBoldLeftBoldRightBold:"┻",lineUpLeftBoldRightBold:"┷",lineUpBoldLeftRight:"┸",lineUpBoldLeftBoldRight:"┹",lineUpBoldLeftRightBold:"┺",lineUpLeftRightBold:"┶",lineUpLeftBoldRight:"┵",lineUpDoubleLeftDoubleRightDouble:"╩",lineUpDoubleLeftRight:"╨",lineUpLeftDoubleRightDouble:"╧",lineUpDownLeftRight:"┼",lineUpBoldDownBoldLeftBoldRightBold:"╋",lineUpDownBoldLeftBoldRightBold:"╈",lineUpBoldDownLeftBoldRightBold:"╇",lineUpBoldDownBoldLeftRightBold:"╊",lineUpBoldDownBoldLeftBoldRight:"╉",lineUpBoldDownLeftRight:"╀",lineUpDownBoldLeftRight:"╁",lineUpDownLeftBoldRight:"┽",lineUpDownLeftRightBold:"┾",lineUpBoldDownBoldLeftRight:"╂",lineUpDownLeftBoldRightBold:"┿",lineUpBoldDownLeftBoldRight:"╃",lineUpBoldDownLeftRightBold:"╄",lineUpDownBoldLeftBoldRight:"╅",lineUpDownBoldLeftRightBold:"╆",lineUpDoubleDownDoubleLeftDoubleRightDouble:"╬",lineUpDoubleDownDoubleLeftRight:"╫",lineUpDownLeftDoubleRightDouble:"╪",lineCross:"╳",lineBackslash:"╲",lineSlash:"╱"},r={tick:"✔",info:"ℹ",warning:"⚠",cross:"✘",squareSmall:"◻",squareSmallFilled:"◼",circle:"◯",circleFilled:"◉",circleDotted:"◌",circleDouble:"◎",circleCircle:"ⓞ",circleCross:"ⓧ",circlePipe:"Ⓘ",radioOn:"◉",radioOff:"◯",checkboxOn:"☒",checkboxOff:"☐",checkboxCircleOn:"ⓧ",checkboxCircleOff:"Ⓘ",pointer:"❯",triangleUpOutline:"△",triangleLeft:"◀",triangleRight:"▶",lozenge:"◆",lozengeOutline:"◇",hamburger:"☰",smiley:"㋡",mustache:"෴",star:"★",play:"▶",nodejs:"⬢",oneSeventh:"⅐",oneNinth:"⅑",oneTenth:"⅒"},s={...o,...r},a={...o,tick:"√",info:"i",warning:"‼",cross:"\xd7",squareSmall:"□",squareSmallFilled:"■",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(○)",circleCross:"(\xd7)",circlePipe:"(│)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xd7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xd7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"∆",triangleLeft:"◄",triangleRight:"►",lozenge:"♦",lozengeOutline:"◊",hamburger:"≡",smiley:"☺",mustache:"┌─┐",star:"✶",play:"►",nodejs:"♦",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},u=(l.platform.startsWith("win")?!l.env.CI&&!l.env.WT_SESSION&&!l.env.TERMINUS_SUBLIME&&"{cmd::Cmder}"!==l.env.ConEmuTask&&"Terminus-Sublime"!==l.env.TERM_PROGRAM&&"vscode"!==l.env.TERM_PROGRAM&&"xterm-256color"!==l.env.TERM&&"alacritty"!==l.env.TERM&&"JetBrains-JediTerm"!==l.env.TERMINAL_EMULATOR:"linux"===l.env.TERM)?a:s;Object.entries(r);let h=t("node:util");class d{separator=(0,h.styleText)("dim",Array.from({length:15}).join(u.line));type="separator";constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&"object"==typeof e&&"type"in e&&"separator"===e.type)}}let c=(e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,t=>{let i=0;for(e.lastIndex=0;e.test(t);)i+=1;return t.length-i}),p=e=>12288===e||e>=65281&&e<=65376||e>=65504&&e<=65510,f=e=>8987===e||9001===e||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,g=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,m=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,D=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,w=/\t{1,1000}/y,b=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,B=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,R=/\p{M}+/gu,L={limit:1/0,ellipsis:""},x=(e,t={},i={})=>{let l=t.limit??1/0,n=t.ellipsis??"",o=t?.ellipsisWidth??(n?x(n,L,i).width:0),r=i.controlWidth??0,s=i.tabWidth??8,a=i.emojiWidth??2,u=i.regularWidth??1,h=i.wideWidth??2,d=[[B,u],[g,0],[m,r],[w,s],[b,a],[D,h]],y=0,U=0,E=e.length,S=0,_=!1,T=E,v=Math.max(0,l-o),k=0,C=0,F=0,P=0;e:for(;;){if(C>k||U>=E&&U>y){for(let t of(S=0,(e.slice(k,C)||e.slice(y,U)).replaceAll(R,""))){let e=t.codePointAt(0)||0;if(F+(P=p(e)?2:f(e)?h:u)>v&&(T=Math.min(T,Math.max(k,y)+S)),F+P>l){_=!0;break e}S+=t.length,F+=P}k=C=0}if(U>=E)break;for(let t=0,i=d.length;t<i;t++){let[i,n]=d[t];if(i.lastIndex=U,i.test(e)){if(F+(P=(S=i===D?c(e.slice(U,i.lastIndex)):i===b?1:i.lastIndex-U)*n)>v&&(T=Math.min(T,U+Math.floor((v-F)/n))),F+P>l){_=!0;break e}F+=P,k=y,C=U,U=y=i.lastIndex;continue e}}U+=1}return{width:_?v:F,index:_?T:E,truncated:_,ellipsed:_&&l>=o}},y={limit:1/0,ellipsis:"",ellipsisWidth:0},U=(e,t={})=>x(e,y,t).width,E="]8;;",S=RegExp(`(?:\\[(?<code>\\d+)m|\\${E}(?<uri>.*)\u0007)`,"y"),_=e=>e>=30&&e<=37||e>=90&&e<=97?39:e>=40&&e<=47||e>=100&&e<=107?49:1===e||2===e?22:3===e?23:4===e?24:7===e?27:8===e?28:9===e?29:0===e?0:void 0,T=e=>`\x1b[${e}m`,v=e=>`\x1b${E}${e}\u0007`,k=(e,t,i)=>{let l=t[Symbol.iterator](),n=!1,o=!1,r=e.at(-1),s=void 0===r?0:U(r),a=l.next(),u=l.next(),h=0;for(;!a.done;){let r=a.value,d=U(r);s+d<=i?e[e.length-1]+=r:(e.push(r),s=0),("\x1b"===r||"\x9b"===r)&&(n=!0,o=t.startsWith(E,h+1)),n?o?"\x07"===r&&(n=!1,o=!1):"m"===r&&(n=!1):(s+=d)!==i||u.done||(e.push(""),s=0),a=u,u=l.next(),h+=r.length}r=e.at(-1),!s&&void 0!==r&&r.length&&e.length>1&&(e[e.length-2]+=e.pop())},C=/\r?\n/;class F extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}}class P extends Error{name="CancelPromptError";message="Prompt was canceled"}class M extends Error{name="ExitPromptError"}class O extends Error{name="HookError"}class A extends Error{name="ValidationError"}let j=t("node:async_hooks"),I=new j.AsyncLocalStorage;function W(){let e=I.getStore();if(!e)throw new O("[Inquirer] Hook functions can only be called from within a prompt");return e}function N(e){return j.AsyncResource.bind((...t)=>{let i=W(),l=!1,n=i.handleChange;i.handleChange=()=>{l=!0};let o=e(...t);return l&&n(),i.handleChange=n,o})}function q(e){let t=W(),{index:i}=t,l=e({get:()=>t.hooks[i],set(e){t.hooks[i]=e},initialized:i in t.hooks});return t.index++,l}let V={queue(e){let t=W(),{index:i}=t;t.hooksEffect.push(()=>{t.hooksCleanup[i]?.();let l=e(W().rl);if(null!=l&&"function"!=typeof l)throw new A("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[i]=l})},run(){let e=W();N(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=W();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}},K=t("../../../node_modules/.pnpm/cli-width@4.1.0/node_modules/cli-width/index.js");function $(e,t){return e.split("\n").flatMap(e=>{var i;return(i={trim:!1,wordWrap:!1},String(e).normalize().split(C).map(e=>((e,t,i={})=>{let l,n;if(!1!==i.trim&&""===e.trim())return"";let o="",r=e.split(" "),s=[""],a=0;for(let e=0;e<r.length;e++){let l=r[e];if(!1!==i.trim){let e=s.at(-1)??"",t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,a=U(t))}0!==e&&(a>=t&&(!1===i.wordWrap||!1===i.trim)&&(s.push(""),a=0),(a||!1===i.trim)&&(s[s.length-1]+=" ",a++));let n=U(l);if(i.hard&&n>t){let e=1+Math.floor((n-(t-a)-1)/t);Math.floor((n-1)/t)<e&&s.push(""),k(s,l,t),a=U(s.at(-1)??"");continue}if(a+n>t&&a&&n){if(!1===i.wordWrap&&a<t){k(s,l,t),a=U(s.at(-1)??"");continue}s.push(""),a=0}if(a+n>t&&!1===i.wordWrap){k(s,l,t),a=U(s.at(-1)??"");continue}s[s.length-1]+=l,a+=n}!1!==i.trim&&(s=s.map(e=>(e=>{let t=e.split(" "),i=t.length;for(;i&&!U(t[i-1]);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")})(e)));let u=s.join("\n"),h=!1;for(let e=0;e<u.length;e++){let t=u[e];if(o+=t,h)h=!1;else if(h=t>="\uD800"&&t<="\uDBFF")continue;if("\x1b"===t||"\x9b"===t){S.lastIndex=e+1;let t=S.exec(u),i=t?.groups;if(i?.code!==void 0){let e=Number.parseFloat(i.code);l=39===e?void 0:e}else i?.uri!==void 0&&(n=0===i.uri.length?void 0:i.uri)}if("\n"===u[e+1]){n&&(o+=v(""));let e=l?_(l):void 0;l&&e&&(o+=T(e))}else"\n"===t&&(l&&_(l)&&(o+=T(l)),n&&(o+=v(n)))}return o})(e,t,i)).join("\n")).split("\n").map(e=>e.trimEnd())}).join("\n")}function H(){return K({defaultWidth:80,output:W().rl.output})}let z=(e=1)=>e>0?`\u001B[${e}A`:"",G=(e=1)=>e>0?`\u001B[${e}B`:"",Y=(e,t)=>"number"!=typeof t||Number.isNaN(t)?`\u001B[${e+1}G`:`\u001B[${t+1};${e+1}H`,Q="\x1b[2K",J=e=>e>0?(Q+z(1)).repeat(e-1)+Q+"\x1b[G":"";class Z{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=""){let i=e.split("\n").pop()??"",l=(0,h.stripVTControlCharacters)(i),n=l;this.rl.line.length>0&&(n=n.slice(0,-this.rl.line.length)),this.rl.setPrompt(n),this.cursorPos=this.rl.getCursorPos();let o=H();e=$(e,o),t=$(t,o),l.length%o==0&&(e+="\n");let r=e+(t?"\n"+t:""),s=Math.floor(l.length/o)-this.cursorPos.rows+(t?t.split("\n").length:0);s>0&&(r+=z(s)),r+=Y(this.cursorPos.cols),this.write(G(this.extraLinesUnderPrompt)+J(this.height)+r),this.extraLinesUnderPrompt=s,this.height=r.split("\n").length}checkCursorPos(){let e=this.rl.getCursorPos();e.cols!==this.cursorPos.cols&&(this.write(Y(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt("");let t=G(this.extraLinesUnderPrompt);t+=e?J(this.height):"\n",t+="\x1b[G",t+="\x1b[?25h",this.write(t),this.rl.close()}}class X extends Promise{static withResolver(){let e,t;return{promise:new Promise((i,l)=>{e=i,t=l}),resolve:e,reject:t}}}let ee=t("../../../node_modules/.pnpm/mute-stream@3.0.0/node_modules/mute-stream/lib/index.js"),et=t("node:path"),ei=globalThis.setImmediate;function el(e){let t=function(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(e,i)=>{let l=i.slice(1);return t=l,l},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}();return(l,o={})=>{let{input:r=process.stdin,signal:s}=o,a=new Set,u=new ee;u.pipe(o.output??process.stdout);let h=n.createInterface({terminal:!0,input:r,output:u});u.mute();let d=new Z(h),{promise:c,resolve:p,reject:f}=X.withResolver(),g=()=>f(new P);if(s){let e=()=>f(new F({cause:s.reason}));if(s.aborted)return e(),Object.assign(c,{cancel:g});s.addEventListener("abort",e),a.add(()=>s.removeEventListener("abort",e))}a.add(i((e,t)=>{f(new M(`User force closed the prompt with ${e} ${t}`))}));let m=()=>f(new M("User force closed the prompt with SIGINT"));h.on("SIGINT",m),a.add(()=>h.removeListener("SIGINT",m));let D={rl:h,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}};return I.run(D,()=>{var i;let n,s;return i=function(e){D.handleChange=()=>{D.index=0,e()},D.handleChange()},n=j.AsyncResource.bind(()=>V.clearAll()),h.on("close",n),a.add(()=>h.removeListener("close",n)),s=()=>{let n=()=>d.checkCursorPos();h.input.on("keypress",n),a.add(()=>h.input.removeListener("keypress",n));let o=null;i(()=>{let i=!1;try{let n=e(l,e=>{i?p(e):o={value:e}});if(void 0===n){let e=t[1]?.getFileName();throw e&&!e.startsWith("file://")&&(e=et.resolve(e)),Error(`Prompt functions must return a string.
|
|
2
|
-
at ${e}`)}let[r,s]="string"==typeof n?[n]:n;d.render(r,s),V.run()}catch(e){f(e)}if(i=!0,null!==o){let{value:e}=o;o=null,p(e)}})},"readableFlowing"in r?ei(s):s(),Object.assign(c.then(e=>(V.clearAll(),e),e=>{throw V.clearAll(),e}).finally(()=>{a.forEach(e=>e()),d.done({clearContent:!!o.clearPromptOnDone}),u.end()}).then(()=>c),{cancel:g})})}}let en=new Set(["emacs","vim"]);function eo(e){return en.has(e)}let er=(e,t=[])=>"up"===e.name||t.includes("vim")&&"k"===e.name||t.includes("emacs")&&e.ctrl&&"p"===e.name,es=(e,t=[])=>"down"===e.name||t.includes("vim")&&"j"===e.name||t.includes("emacs")&&e.ctrl&&"n"===e.name,ea=e=>"space"===e.name,eu=e=>"backspace"===e.name,eh=e=>"tab"===e.name,ed=e=>"1234567890".includes(e.name),ec=e=>"enter"===e.name||"return"===e.name,ep={prefix:{idle:(0,h.styleText)("blue","?"),done:(0,h.styleText)("green",u.tick)},spinner:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"].map(e=>(0,h.styleText)("yellow",e))},keybindings:[],style:{answer:e=>(0,h.styleText)("cyan",e),message:e=>(0,h.styleText)("bold",e),error:e=>(0,h.styleText)("red",`> ${e}`),defaultAnswer:e=>(0,h.styleText)("dim",`(${e})`),help:e=>(0,h.styleText)("dim",e),highlight:e=>(0,h.styleText)("cyan",e),key:e=>(0,h.styleText)("cyan",(0,h.styleText)("bold",`<${e}>`))}};function ef(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function eg(...e){let t;return function e(...t){let i={};for(let l of t)for(let[t,n]of Object.entries(l)){let l=i[t];i[t]=ef(l)&&ef(n)?e(l,n):n}return i}({...ep,keybindings:(t=process.env.INQUIRER_KEYBINDINGS)?Array.from(new Set(t.toLowerCase().split(/[\s,]+/).filter(eo))):[]},...e.filter(e=>null!=e))}function em(e){return q(t=>{let i=j.AsyncResource.bind(function(e){t.get()!==e&&(t.set(e),W().handleChange())});if(t.initialized)return[t.get(),i];let l="function"==typeof e?e():e;return t.set(l),[l,i]})}function eD(e,t){q(i=>{let l=i.get();(!Array.isArray(l)||t.some((e,t)=>!Object.is(e,l[t])))&&V.queue(e),i.set(t)})}function ew({status:e="idle",theme:t}){let[i,l]=em(!1),[n,o]=em(0),{prefix:r,spinner:s}=eg(t);if(eD(()=>{if("loading"===e){let e,t=-1,i=setTimeout(()=>{l(!0),e=setInterval(()=>{o((t+=1)%s.frames.length)},s.interval)},300);return()=>{clearTimeout(i),clearInterval(e)}}l(!1)},[e]),i)return s.frames[n];let a="loading"===e?"idle":e;return"string"==typeof r?r:r[a]??r.idle}function eb(e){return em({current:e})[0]}function eB(e,t){return q(i=>{let l=i.get();if(!l||l.dependencies.length!==t.length||l.dependencies.some((e,i)=>e!==t[i])){let l=e();return i.set({value:l,dependencies:t}),l}return l.value})}function eR(e){let t=eb(e);t.current=e,eD(e=>{let i=!1,l=N((l,n)=>{i||t.current(n,e)});return e.input.on("keypress",l),()=>{i=!0,e.input.removeListener("keypress",l)}},[])}function eL({items:e,active:t,renderItem:i,pageSize:l,loop:n=!0}){let o=H(),r=t=>(t%e.length+e.length)%e.length,s=e.map((e,l)=>null==e?[]:$(i({item:e,index:l,isActive:l===t}),o).split("\n")),a=s.reduce((e,t)=>e+t.length,0),u=e=>s[e]??[],h=function({active:e,renderedItems:t,pageSize:i,loop:l}){let n=eb({lastPointer:e,lastActive:void 0}),{lastPointer:o,lastActive:r}=n.current,s=Math.floor(i/2),a=t.reduce((e,t)=>e+t.length,0),u=t.slice(0,e).reduce((e,t)=>e+t.length,0),h=u;if(a>i)if(l)h=o,null!=r&&r<e&&e-r<i&&(h=Math.min(s,1===Math.abs(e-r)?Math.min(o+(t[r]?.length??0),Math.max(u,o)):o+e-r));else{let l=t.slice(e).reduce((e,t)=>e+t.length,0);h=l<i-s?i-l:Math.min(u,s)}return n.current.lastPointer=h,n.current.lastActive=e,h}({active:t,renderedItems:s,pageSize:l,loop:n}),d=u(t).slice(0,l),c=h+d.length<=l?h:l-d.length,p=Array.from({length:l});p.splice(c,d.length,...d);let f=new Set([t]),g=c+d.length,m=r(t+1);for(;g<l&&!f.has(m)&&(n&&a>l?m!==t:m>t);){let e=u(m).slice(0,l-g);p.splice(g,e.length,...e),f.add(m),g+=e.length,m=r(m+1)}for(g=c-1,m=r(t-1);g>=0&&!f.has(m)&&(n&&a>l?m!==t:m<t);){let e=u(m),t=e.slice(Math.max(0,e.length-g-1));p.splice(g-t.length+1,t.length,...t),f.add(m),g-=t.length,m=r(m-1)}return p.filter(e=>"string"==typeof e).join("\n")}export{F as AbortPromptError,d as Separator,A as ValidationError,el as createPrompt,u as dist,eu as isBackspaceKey,es as isDownKey,ec as isEnterKey,ed as isNumberKey,ea as isSpaceKey,eh as isTabKey,er as isUpKey,eg as makeTheme,eD as useEffect,eR as useKeypress,eB as useMemo,eL as usePagination,ew as usePrefix,eb as useRef,em as useState};
|
|
1
|
+
let e;import"node:module";import{__webpack_require__ as t}from"./rslib-runtime.js";import{external_node_readline_namespaceObject as i,external_node_process_namespaceObject as l}from"./3768.js";import{onExit as n}from"./6780.js";import"./180.js";t.add({"../../../node_modules/.pnpm/cli-width@4.1.0/node_modules/cli-width/index.js"(e,t,i){e.exports=function(e){let t,l=(t={defaultWidth:0,output:process.stdout,tty:i("tty")},e?(Object.keys(t).forEach(function(i){e[i]||(e[i]=t[i])}),e):t);if(l.output.getWindowSize)return l.output.getWindowSize()[0]||l.defaultWidth;if(l.tty.getWindowSize)return l.tty.getWindowSize()[1]||l.defaultWidth;if(l.output.columns)return l.output.columns;if(process.env.CLI_WIDTH){let e=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(e)&&0!==e)return e}return l.defaultWidth}},"../../../node_modules/.pnpm/mute-stream@3.0.0/node_modules/mute-stream/lib/index.js"(e,t,i){let l=i("stream");e.exports=class extends l{#e=null;constructor(e={}){super(e),this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){return this._dest?this._dest[e]:this._src?this._src[e]:t}#i(e,...t){"function"==typeof this._dest?.[e]&&this._dest[e](...t),"function"==typeof this._src?.[e]&&this._src[e](...t)}get isTTY(){return null!==this.#e?this.#e:this.#t("isTTY",!1)}set isTTY(e){this.#e=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/))return 0===e.indexOf(this._prompt)&&(e=(e=e.slice(this._prompt.length)).replace(/./g,this.replace),e=this._prompt+e),this._hadControl=!0,this.emit("data",e);this._prompt&&this._hadControl&&0===e.indexOf(this._prompt)&&(this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length)),e=e.toString().replace(/./g,this.replace)}this.emit("data",e)}end(e){this.muted&&(e=e&&this.replace?e.toString().replace(/./g,this.replace):null),e&&this.emit("data",e),this.emit("end")}destroy(...e){return this.#i("destroy",...e)}destroySoon(...e){return this.#i("destroySoon",...e)}close(...e){return this.#i("close",...e)}}}});let o=(e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,t=>{let i=0;for(e.lastIndex=0;e.test(t);)i+=1;return t.length-i}),r=e=>12288===e||e>=65281&&e<=65376||e>=65504&&e<=65510,s=e=>8987===e||9001===e||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,a=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,u=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,h=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,d=/\t{1,1000}/y,c=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,p=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,f=/\p{M}+/gu,g={limit:1/0,ellipsis:""},m=(e,t={},i={})=>{let l=t.limit??1/0,n=t.ellipsis??"",D=t?.ellipsisWidth??(n?m(n,g,i).width:0),w=i.controlWidth??0,b=i.tabWidth??8,B=i.emojiWidth??2,R=i.regularWidth??1,L=i.wideWidth??2,x=[[p,R],[a,0],[u,w],[d,b],[c,B],[h,L]],y=0,U=0,E=e.length,_=0,S=!1,T=E,v=Math.max(0,l-D),k=0,C=0,F=0,P=0;e:for(;;){if(C>k||U>=E&&U>y){for(let t of(_=0,(e.slice(k,C)||e.slice(y,U)).replaceAll(f,""))){let e=t.codePointAt(0)||0;if(F+(P=r(e)?2:s(e)?L:R)>v&&(T=Math.min(T,Math.max(k,y)+_)),F+P>l){S=!0;break e}_+=t.length,F+=P}k=C=0}if(U>=E)break;for(let t=0,i=x.length;t<i;t++){let[i,n]=x[t];if(i.lastIndex=U,i.test(e)){if(F+(P=(_=i===h?o(e.slice(U,i.lastIndex)):i===c?1:i.lastIndex-U)*n)>v&&(T=Math.min(T,U+Math.floor((v-F)/n))),F+P>l){S=!0;break e}F+=P,k=y,C=U,U=y=i.lastIndex;continue e}}U+=1}return{width:S?v:F,index:S?T:E,truncated:S,ellipsed:S&&l>=D}},D={limit:1/0,ellipsis:"",ellipsisWidth:0},w=(e,t={})=>m(e,D,t).width,b="]8;;",B=RegExp(`(?:\\[(?<code>\\d+)m|\\${b}(?<uri>.*)\u0007)`,"y"),R=e=>e>=30&&e<=37||e>=90&&e<=97?39:e>=40&&e<=47||e>=100&&e<=107?49:1===e||2===e?22:3===e?23:4===e?24:7===e?27:8===e?28:9===e?29:0===e?0:void 0,L=e=>`\x1b[${e}m`,x=e=>`\x1b${b}${e}\u0007`,y=(e,t,i)=>{let l=t[Symbol.iterator](),n=!1,o=!1,r=e.at(-1),s=void 0===r?0:w(r),a=l.next(),u=l.next(),h=0;for(;!a.done;){let r=a.value,d=w(r);s+d<=i?e[e.length-1]+=r:(e.push(r),s=0),("\x1b"===r||"\x9b"===r)&&(n=!0,o=t.startsWith(b,h+1)),n?o?"\x07"===r&&(n=!1,o=!1):"m"===r&&(n=!1):(s+=d)!==i||u.done||(e.push(""),s=0),a=u,u=l.next(),h+=r.length}r=e.at(-1),!s&&void 0!==r&&r.length&&e.length>1&&(e[e.length-2]+=e.pop())},U=/\r?\n/;class E extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}}class _ extends Error{name="CancelPromptError";message="Prompt was canceled"}class S extends Error{name="ExitPromptError"}class T extends Error{name="HookError"}class v extends Error{name="ValidationError"}let k=t("node:async_hooks"),C=new k.AsyncLocalStorage;function F(){let e=C.getStore();if(!e)throw new T("[Inquirer] Hook functions can only be called from within a prompt");return e}function P(e){return k.AsyncResource.bind((...t)=>{let i=F(),l=!1,n=i.handleChange;i.handleChange=()=>{l=!0};let o=e(...t);return l&&n(),i.handleChange=n,o})}function M(e){let t=F(),{index:i}=t,l=e({get:()=>t.hooks[i],set(e){t.hooks[i]=e},initialized:i in t.hooks});return t.index++,l}let A={queue(e){let t=F(),{index:i}=t;t.hooksEffect.push(()=>{t.hooksCleanup[i]?.();let l=e(F().rl);if(null!=l&&"function"!=typeof l)throw new v("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[i]=l})},run(){let e=F();P(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=F();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}},O=t("../../../node_modules/.pnpm/cli-width@4.1.0/node_modules/cli-width/index.js");function j(e,t){return e.split("\n").flatMap(e=>{var i;return(i={trim:!1,wordWrap:!1},String(e).normalize().split(U).map(e=>((e,t,i={})=>{let l,n;if(!1!==i.trim&&""===e.trim())return"";let o="",r=e.split(" "),s=[""],a=0;for(let e=0;e<r.length;e++){let l=r[e];if(!1!==i.trim){let e=s.at(-1)??"",t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,a=w(t))}0!==e&&(a>=t&&(!1===i.wordWrap||!1===i.trim)&&(s.push(""),a=0),(a||!1===i.trim)&&(s[s.length-1]+=" ",a++));let n=w(l);if(i.hard&&n>t){let e=1+Math.floor((n-(t-a)-1)/t);Math.floor((n-1)/t)<e&&s.push(""),y(s,l,t),a=w(s.at(-1)??"");continue}if(a+n>t&&a&&n){if(!1===i.wordWrap&&a<t){y(s,l,t),a=w(s.at(-1)??"");continue}s.push(""),a=0}if(a+n>t&&!1===i.wordWrap){y(s,l,t),a=w(s.at(-1)??"");continue}s[s.length-1]+=l,a+=n}!1!==i.trim&&(s=s.map(e=>(e=>{let t=e.split(" "),i=t.length;for(;i&&!w(t[i-1]);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")})(e)));let u=s.join("\n"),h=!1;for(let e=0;e<u.length;e++){let t=u[e];if(o+=t,h)h=!1;else if(h=t>="\uD800"&&t<="\uDBFF")continue;if("\x1b"===t||"\x9b"===t){B.lastIndex=e+1;let t=B.exec(u),i=t?.groups;if(i?.code!==void 0){let e=Number.parseFloat(i.code);l=39===e?void 0:e}else i?.uri!==void 0&&(n=0===i.uri.length?void 0:i.uri)}if("\n"===u[e+1]){n&&(o+=x(""));let e=l?R(l):void 0;l&&e&&(o+=L(e))}else"\n"===t&&(l&&R(l)&&(o+=L(l)),n&&(o+=x(n)))}return o})(e,t,i)).join("\n")).split("\n").map(e=>e.trimEnd())}).join("\n")}function I(){return O({defaultWidth:80,output:F().rl.output})}let N=(e=1)=>e>0?`\u001B[${e}A`:"",W=(e=1)=>e>0?`\u001B[${e}B`:"",q=(e,t)=>"number"!=typeof t||Number.isNaN(t)?`\u001B[${e+1}G`:`\u001B[${t+1};${e+1}H`,K="\x1b[2K",V=e=>e>0?(K+N(1)).repeat(e-1)+K+"\x1b[G":"",$=t("node:util");class H{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=""){let i=e.split("\n").pop()??"",l=(0,$.stripVTControlCharacters)(i),n=l;this.rl.line.length>0&&(n=n.slice(0,-this.rl.line.length)),this.rl.setPrompt(n),this.cursorPos=this.rl.getCursorPos();let o=I();e=j(e,o),t=j(t,o),l.length%o==0&&(e+="\n");let r=e+(t?"\n"+t:""),s=Math.floor(l.length/o)-this.cursorPos.rows+(t?t.split("\n").length:0);s>0&&(r+=N(s)),r+=q(this.cursorPos.cols),this.write(W(this.extraLinesUnderPrompt)+V(this.height)+r),this.extraLinesUnderPrompt=s,this.height=r.split("\n").length}checkCursorPos(){let e=this.rl.getCursorPos();e.cols!==this.cursorPos.cols&&(this.write(q(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt("");let t=W(this.extraLinesUnderPrompt);t+=e?V(this.height):"\n",t+="\x1b[G",t+="\x1b[?25h",this.write(t),this.rl.close()}}class z extends Promise{static withResolver(){let e,t;return{promise:new Promise((i,l)=>{e=i,t=l}),resolve:e,reject:t}}}let G=t("../../../node_modules/.pnpm/mute-stream@3.0.0/node_modules/mute-stream/lib/index.js"),Y=t("node:path"),Q=globalThis.setImmediate;function J(e){let t=function(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(e,i)=>{let l=i.slice(1);return t=l,l},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}();return(l,o={})=>{let{input:r=process.stdin,signal:s}=o,a=new Set,u=new G;u.pipe(o.output??process.stdout);let h=i.createInterface({terminal:!0,input:r,output:u});u.mute();let d=new H(h),{promise:c,resolve:p,reject:f}=z.withResolver(),g=()=>f(new _);if(s){let e=()=>f(new E({cause:s.reason}));if(s.aborted)return e(),Object.assign(c,{cancel:g});s.addEventListener("abort",e),a.add(()=>s.removeEventListener("abort",e))}a.add(n((e,t)=>{f(new S(`User force closed the prompt with ${e} ${t}`))}));let m=()=>f(new S("User force closed the prompt with SIGINT"));h.on("SIGINT",m),a.add(()=>h.removeListener("SIGINT",m));let D={rl:h,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}};return C.run(D,()=>{var i;let n,s;return i=function(e){D.handleChange=()=>{D.index=0,e()},D.handleChange()},n=k.AsyncResource.bind(()=>A.clearAll()),h.on("close",n),a.add(()=>h.removeListener("close",n)),s=()=>{let n=()=>d.checkCursorPos();h.input.on("keypress",n),a.add(()=>h.input.removeListener("keypress",n));let o=null;i(()=>{let i=!1;try{let n=e(l,e=>{i?p(e):o={value:e}});if(void 0===n){let e=t[1]?.getFileName();throw e&&!e.startsWith("file://")&&(e=Y.resolve(e)),Error(`Prompt functions must return a string.
|
|
2
|
+
at ${e}`)}let[r,s]="string"==typeof n?[n]:n;d.render(r,s),A.run()}catch(e){f(e)}if(i=!0,null!==o){let{value:e}=o;o=null,p(e)}})},"readableFlowing"in r?Q(s):s(),Object.assign(c.then(e=>(A.clearAll(),e),e=>{throw A.clearAll(),e}).finally(()=>{a.forEach(e=>e()),d.done({clearContent:!!o.clearPromptOnDone}),u.end()}).then(()=>c),{cancel:g})})}}let Z={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"█",squareDarkShade:"▓",squareMediumShade:"▒",squareLightShade:"░",squareTop:"▀",squareBottom:"▄",squareLeft:"▌",squareRight:"▐",squareCenter:"■",bullet:"●",dot:"․",ellipsis:"…",pointerSmall:"›",triangleUp:"▲",triangleUpSmall:"▴",triangleDown:"▼",triangleDownSmall:"▾",triangleLeftSmall:"◂",triangleRightSmall:"▸",home:"⌂",heart:"♥",musicNote:"♪",musicNoteBeamed:"♫",arrowUp:"↑",arrowDown:"↓",arrowLeft:"←",arrowRight:"→",arrowLeftRight:"↔",arrowUpDown:"↕",almostEqual:"≈",notEqual:"≠",lessOrEqual:"≤",greaterOrEqual:"≥",identical:"≡",infinity:"∞",subscriptZero:"₀",subscriptOne:"₁",subscriptTwo:"₂",subscriptThree:"₃",subscriptFour:"₄",subscriptFive:"₅",subscriptSix:"₆",subscriptSeven:"₇",subscriptEight:"₈",subscriptNine:"₉",oneHalf:"\xbd",oneThird:"⅓",oneQuarter:"\xbc",oneFifth:"⅕",oneSixth:"⅙",oneEighth:"⅛",twoThirds:"⅔",twoFifths:"⅖",threeQuarters:"\xbe",threeFifths:"⅗",threeEighths:"⅜",fourFifths:"⅘",fiveSixths:"⅚",fiveEighths:"⅝",sevenEighths:"⅞",line:"─",lineBold:"━",lineDouble:"═",lineDashed0:"┄",lineDashed1:"┅",lineDashed2:"┈",lineDashed3:"┉",lineDashed4:"╌",lineDashed5:"╍",lineDashed6:"╴",lineDashed7:"╶",lineDashed8:"╸",lineDashed9:"╺",lineDashed10:"╼",lineDashed11:"╾",lineDashed12:"−",lineDashed13:"–",lineDashed14:"‐",lineDashed15:"⁃",lineVertical:"│",lineVerticalBold:"┃",lineVerticalDouble:"║",lineVerticalDashed0:"┆",lineVerticalDashed1:"┇",lineVerticalDashed2:"┊",lineVerticalDashed3:"┋",lineVerticalDashed4:"╎",lineVerticalDashed5:"╏",lineVerticalDashed6:"╵",lineVerticalDashed7:"╷",lineVerticalDashed8:"╹",lineVerticalDashed9:"╻",lineVerticalDashed10:"╽",lineVerticalDashed11:"╿",lineDownLeft:"┐",lineDownLeftArc:"╮",lineDownBoldLeftBold:"┓",lineDownBoldLeft:"┒",lineDownLeftBold:"┑",lineDownDoubleLeftDouble:"╗",lineDownDoubleLeft:"╖",lineDownLeftDouble:"╕",lineDownRight:"┌",lineDownRightArc:"╭",lineDownBoldRightBold:"┏",lineDownBoldRight:"┎",lineDownRightBold:"┍",lineDownDoubleRightDouble:"╔",lineDownDoubleRight:"╓",lineDownRightDouble:"╒",lineUpLeft:"┘",lineUpLeftArc:"╯",lineUpBoldLeftBold:"┛",lineUpBoldLeft:"┚",lineUpLeftBold:"┙",lineUpDoubleLeftDouble:"╝",lineUpDoubleLeft:"╜",lineUpLeftDouble:"╛",lineUpRight:"└",lineUpRightArc:"╰",lineUpBoldRightBold:"┗",lineUpBoldRight:"┖",lineUpRightBold:"┕",lineUpDoubleRightDouble:"╚",lineUpDoubleRight:"╙",lineUpRightDouble:"╘",lineUpDownLeft:"┤",lineUpBoldDownBoldLeftBold:"┫",lineUpBoldDownBoldLeft:"┨",lineUpDownLeftBold:"┥",lineUpBoldDownLeftBold:"┩",lineUpDownBoldLeftBold:"┪",lineUpDownBoldLeft:"┧",lineUpBoldDownLeft:"┦",lineUpDoubleDownDoubleLeftDouble:"╣",lineUpDoubleDownDoubleLeft:"╢",lineUpDownLeftDouble:"╡",lineUpDownRight:"├",lineUpBoldDownBoldRightBold:"┣",lineUpBoldDownBoldRight:"┠",lineUpDownRightBold:"┝",lineUpBoldDownRightBold:"┡",lineUpDownBoldRightBold:"┢",lineUpDownBoldRight:"┟",lineUpBoldDownRight:"┞",lineUpDoubleDownDoubleRightDouble:"╠",lineUpDoubleDownDoubleRight:"╟",lineUpDownRightDouble:"╞",lineDownLeftRight:"┬",lineDownBoldLeftBoldRightBold:"┳",lineDownLeftBoldRightBold:"┯",lineDownBoldLeftRight:"┰",lineDownBoldLeftBoldRight:"┱",lineDownBoldLeftRightBold:"┲",lineDownLeftRightBold:"┮",lineDownLeftBoldRight:"┭",lineDownDoubleLeftDoubleRightDouble:"╦",lineDownDoubleLeftRight:"╥",lineDownLeftDoubleRightDouble:"╤",lineUpLeftRight:"┴",lineUpBoldLeftBoldRightBold:"┻",lineUpLeftBoldRightBold:"┷",lineUpBoldLeftRight:"┸",lineUpBoldLeftBoldRight:"┹",lineUpBoldLeftRightBold:"┺",lineUpLeftRightBold:"┶",lineUpLeftBoldRight:"┵",lineUpDoubleLeftDoubleRightDouble:"╩",lineUpDoubleLeftRight:"╨",lineUpLeftDoubleRightDouble:"╧",lineUpDownLeftRight:"┼",lineUpBoldDownBoldLeftBoldRightBold:"╋",lineUpDownBoldLeftBoldRightBold:"╈",lineUpBoldDownLeftBoldRightBold:"╇",lineUpBoldDownBoldLeftRightBold:"╊",lineUpBoldDownBoldLeftBoldRight:"╉",lineUpBoldDownLeftRight:"╀",lineUpDownBoldLeftRight:"╁",lineUpDownLeftBoldRight:"┽",lineUpDownLeftRightBold:"┾",lineUpBoldDownBoldLeftRight:"╂",lineUpDownLeftBoldRightBold:"┿",lineUpBoldDownLeftBoldRight:"╃",lineUpBoldDownLeftRightBold:"╄",lineUpDownBoldLeftBoldRight:"╅",lineUpDownBoldLeftRightBold:"╆",lineUpDoubleDownDoubleLeftDoubleRightDouble:"╬",lineUpDoubleDownDoubleLeftRight:"╫",lineUpDownLeftDoubleRightDouble:"╪",lineCross:"╳",lineBackslash:"╲",lineSlash:"╱"},X={tick:"✔",info:"ℹ",warning:"⚠",cross:"✘",squareSmall:"◻",squareSmallFilled:"◼",circle:"◯",circleFilled:"◉",circleDotted:"◌",circleDouble:"◎",circleCircle:"ⓞ",circleCross:"ⓧ",circlePipe:"Ⓘ",radioOn:"◉",radioOff:"◯",checkboxOn:"☒",checkboxOff:"☐",checkboxCircleOn:"ⓧ",checkboxCircleOff:"Ⓘ",pointer:"❯",triangleUpOutline:"△",triangleLeft:"◀",triangleRight:"▶",lozenge:"◆",lozengeOutline:"◇",hamburger:"☰",smiley:"㋡",mustache:"෴",star:"★",play:"▶",nodejs:"⬢",oneSeventh:"⅐",oneNinth:"⅑",oneTenth:"⅒"},ee={...Z,...X},et={...Z,tick:"√",info:"i",warning:"‼",cross:"\xd7",squareSmall:"□",squareSmallFilled:"■",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(○)",circleCross:"(\xd7)",circlePipe:"(│)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xd7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xd7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"∆",triangleLeft:"◄",triangleRight:"►",lozenge:"♦",lozengeOutline:"◊",hamburger:"≡",smiley:"☺",mustache:"┌─┐",star:"✶",play:"►",nodejs:"♦",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},ei=(l.platform.startsWith("win")?!l.env.CI&&!l.env.WT_SESSION&&!l.env.TERMINUS_SUBLIME&&"{cmd::Cmder}"!==l.env.ConEmuTask&&"Terminus-Sublime"!==l.env.TERM_PROGRAM&&"vscode"!==l.env.TERM_PROGRAM&&"xterm-256color"!==l.env.TERM&&"alacritty"!==l.env.TERM&&"JetBrains-JediTerm"!==l.env.TERMINAL_EMULATOR:"linux"===l.env.TERM)?et:ee;Object.entries(X);let el=new Set(["emacs","vim"]);function en(e){return el.has(e)}let eo=(e,t=[])=>"up"===e.name||t.includes("vim")&&"k"===e.name||t.includes("emacs")&&e.ctrl&&"p"===e.name,er=(e,t=[])=>"down"===e.name||t.includes("vim")&&"j"===e.name||t.includes("emacs")&&e.ctrl&&"n"===e.name,es=e=>"space"===e.name,ea=e=>"backspace"===e.name,eu=e=>"tab"===e.name,eh=e=>"1234567890".includes(e.name),ed=e=>"enter"===e.name||"return"===e.name,ec={prefix:{idle:(0,$.styleText)("blue","?"),done:(0,$.styleText)("green",ei.tick)},spinner:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"].map(e=>(0,$.styleText)("yellow",e))},keybindings:[],style:{answer:e=>(0,$.styleText)("cyan",e),message:e=>(0,$.styleText)("bold",e),error:e=>(0,$.styleText)("red",`> ${e}`),defaultAnswer:e=>(0,$.styleText)("dim",`(${e})`),help:e=>(0,$.styleText)("dim",e),highlight:e=>(0,$.styleText)("cyan",e),key:e=>(0,$.styleText)("cyan",(0,$.styleText)("bold",`<${e}>`))}};function ep(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function ef(...e){let t;return function e(...t){let i={};for(let l of t)for(let[t,n]of Object.entries(l)){let l=i[t];i[t]=ep(l)&&ep(n)?e(l,n):n}return i}({...ec,keybindings:(t=process.env.INQUIRER_KEYBINDINGS)?Array.from(new Set(t.toLowerCase().split(/[\s,]+/).filter(en))):[]},...e.filter(e=>null!=e))}function eg(e){return M(t=>{let i=k.AsyncResource.bind(function(e){t.get()!==e&&(t.set(e),F().handleChange())});if(t.initialized)return[t.get(),i];let l="function"==typeof e?e():e;return t.set(l),[l,i]})}function em(e,t){M(i=>{let l=i.get();(!Array.isArray(l)||t.some((e,t)=>!Object.is(e,l[t])))&&A.queue(e),i.set(t)})}function eD({status:e="idle",theme:t}){let[i,l]=eg(!1),[n,o]=eg(0),{prefix:r,spinner:s}=ef(t);if(em(()=>{if("loading"===e){let e,t=-1,i=setTimeout(()=>{l(!0),e=setInterval(()=>{o((t+=1)%s.frames.length)},s.interval)},300);return()=>{clearTimeout(i),clearInterval(e)}}l(!1)},[e]),i)return s.frames[n];let a="loading"===e?"idle":e;return"string"==typeof r?r:r[a]??r.idle}function ew(e){return eg({current:e})[0]}function eb(e){let t=ew(e);t.current=e,em(e=>{let i=!1,l=P((l,n)=>{i||t.current(n,e)});return e.input.on("keypress",l),()=>{i=!0,e.input.removeListener("keypress",l)}},[])}class eB{separator=(0,$.styleText)("dim",Array.from({length:15}).join(ei.line));type="separator";constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&"object"==typeof e&&"type"in e&&"separator"===e.type)}}function eR(e,t){return M(i=>{let l=i.get();if(!l||l.dependencies.length!==t.length||l.dependencies.some((e,i)=>e!==t[i])){let l=e();return i.set({value:l,dependencies:t}),l}return l.value})}function eL({items:e,active:t,renderItem:i,pageSize:l,loop:n=!0}){let o=I(),r=t=>(t%e.length+e.length)%e.length,s=e.map((e,l)=>null==e?[]:j(i({item:e,index:l,isActive:l===t}),o).split("\n")),a=s.reduce((e,t)=>e+t.length,0),u=e=>s[e]??[],h=function({active:e,renderedItems:t,pageSize:i,loop:l}){let n=ew({lastPointer:e,lastActive:void 0}),{lastPointer:o,lastActive:r}=n.current,s=Math.floor(i/2),a=t.reduce((e,t)=>e+t.length,0),u=t.slice(0,e).reduce((e,t)=>e+t.length,0),h=u;if(a>i)if(l)h=o,null!=r&&r<e&&e-r<i&&(h=Math.min(s,1===Math.abs(e-r)?Math.min(o+(t[r]?.length??0),Math.max(u,o)):o+e-r));else{let l=t.slice(e).reduce((e,t)=>e+t.length,0);h=l<i-s?i-l:Math.min(u,s)}return n.current.lastPointer=h,n.current.lastActive=e,h}({active:t,renderedItems:s,pageSize:l,loop:n}),d=u(t).slice(0,l),c=h+d.length<=l?h:l-d.length,p=Array.from({length:l});p.splice(c,d.length,...d);let f=new Set([t]),g=c+d.length,m=r(t+1);for(;g<l&&!f.has(m)&&(n&&a>l?m!==t:m>t);){let e=u(m).slice(0,l-g);p.splice(g,e.length,...e),f.add(m),g+=e.length,m=r(m+1)}for(g=c-1,m=r(t-1);g>=0&&!f.has(m)&&(n&&a>l?m!==t:m<t);){let e=u(m),t=e.slice(Math.max(0,e.length-g-1));p.splice(g-t.length+1,t.length,...t),f.add(m),g-=t.length,m=r(m-1)}return p.filter(e=>"string"==typeof e).join("\n")}export{E as AbortPromptError,eB as Separator,v as ValidationError,J as createPrompt,ei as figures_dist,ea as isBackspaceKey,er as isDownKey,ed as isEnterKey,eh as isNumberKey,es as isSpaceKey,eu as isTabKey,eo as isUpKey,ef as makeTheme,em as useEffect,eb as useKeypress,eR as useMemo,eL as usePagination,eD as usePrefix,ew as useRef,eg as useState};
|