@mk-co/neox-cli 2.0.51 → 2.0.52

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.
@@ -220,9 +220,9 @@ auto_login: { username: "admin", password: "123456" }`,properties:{username:{typ
220
220
 
221
221
  window.__NEOX_INJECTED__ = true;
222
222
  })();
223
- `;(t.collect_console!==false||t.collect_errors!==false)&&(await a.evaluateOnNewDocument(d),a.on("framenavigated",async x=>{if(x===a.mainFrame())try{await x.evaluate(d),m.debug("BROWSER",`Re-injected script after navigation to ${x.url()}`);}catch{}}));let p=await a.createCDPSession();await p.send("Runtime.enable"),await p.send("Log.enable"),t.collect_network!==false&&(r==="cdp"||r==="both")&&(await p.send("Network.enable"),m.debug("BROWSER","Network domain enabled (CDP mode)"));let h=x=>{let{type:R,args:j,timestamp:v}=x,L={log:"log",debug:"debug",info:"info",warning:"warn",error:"error",trace:"trace",assert:"error"}[R]||"log",I=j.map(A=>A.value!==void 0?String(A.value):A.description?A.description:A.preview?.properties?JSON.stringify(A.preview.properties.reduce((O,$)=>(O[$.name]=$.value,O),{})):String(A.type)).join(" ");i.push({type:L,timestamp:v?Math.floor(v):Date.now(),message:I}),m.debug("BROWSER",`[CDP] ${L}: ${I.substring(0,100)}`);},g=x=>{let{exceptionDetails:R}=x,j=R.exception?.description||R.text||"Unknown error";o.push({type:"exception",message:j,stack:R.stackTrace?.callFrames?.map(v=>` at ${v.functionName||"(anonymous)"} (${v.url}:${v.lineNumber}:${v.columnNumber})`).join(`
223
+ `;(t.collect_console!==false||t.collect_errors!==false)&&(await a.evaluateOnNewDocument(d),a.on("framenavigated",async x=>{if(x===a.mainFrame())try{await x.evaluate(d),m.debug("BROWSER",`Re-injected script after navigation to ${x.url()}`);}catch{}}));let p=await a.createCDPSession();await p.send("Runtime.enable"),await p.send("Log.enable"),t.collect_network!==false&&(r==="cdp"||r==="both")&&(await p.send("Network.enable"),m.debug("BROWSER","Network domain enabled (CDP mode)"));let h=x=>{let{type:R,args:j,timestamp:v}=x,P={log:"log",debug:"debug",info:"info",warning:"warn",error:"error",trace:"trace",assert:"error"}[R]||"log",I=j.map(A=>A.value!==void 0?String(A.value):A.description?A.description:A.preview?.properties?JSON.stringify(A.preview.properties.reduce((O,$)=>(O[$.name]=$.value,O),{})):String(A.type)).join(" ");i.push({type:P,timestamp:v?Math.floor(v):Date.now(),message:I}),m.debug("BROWSER",`[CDP] ${P}: ${I.substring(0,100)}`);},g=x=>{let{exceptionDetails:R}=x,j=R.exception?.description||R.text||"Unknown error";o.push({type:"exception",message:j,stack:R.stackTrace?.callFrames?.map(v=>` at ${v.functionName||"(anonymous)"} (${v.url}:${v.lineNumber}:${v.columnNumber})`).join(`
224
224
  `)||"",file:R.url,line:R.lineNumber,column:R.columnNumber,timestamp:Date.now()}),m.debug("BROWSER",`[CDP Exception] ${j}`);},f=x=>{let{entry:R}=x,j=R.level;j==="error"?R.text&&(R.text.includes("Uncaught")||R.text.includes("Error"))?(o.push({type:"exception",message:R.text,stack:R.stackTrace?.callFrames?.map(v=>` at ${v.functionName||"(anonymous)"} (${v.url}:${v.lineNumber}:${v.columnNumber})`).join(`
225
- `)||"",file:R.url,line:R.lineNumber,timestamp:Date.now()}),m.debug("BROWSER",`[CDP Log Error] ${R.text}`)):(i.push({type:"error",timestamp:Date.now(),message:R.text}),m.debug("BROWSER",`[CDP Log] error: ${R.text}`)):j==="warning"&&i.push({type:"warn",timestamp:Date.now(),message:R.text});};if(t.collect_console!==false&&p.on("Runtime.consoleAPICalled",h),t.collect_errors!==false&&(p.on("Runtime.exceptionThrown",g),p.on("Log.entryAdded",f),a.on("pageerror",x=>{let R=x;o.push({type:"exception",message:R.message,stack:R.stack||"",timestamp:Date.now()}),m.debug("BROWSER",`[Puppeteer pageerror] ${R.message}`);}),a.on("requestfailed",x=>{let R=x.failure();o.push({type:"browser_error",message:`Request failed: ${R?.errorText||"Unknown error"}`,stack:"",file:x.url(),timestamp:Date.now()});})),t.collect_network!==false&&(r==="cdp"||r==="both")&&(p.on("Network.requestWillBeSent",x=>{let R={url:x.request.url,method:x.request.method,resource_type:x.type?.toLowerCase()||"other",request_headers:x.request.headers,timing:{start:x.timestamp*1e3,end:0,duration:0}},j=x.type?.toLowerCase()||"other";if(!(n.xhr_only&&!["xhr","fetch"].includes(j))&&!(!n.xhr_only&&uu.includes(j))){if(x.request.postData){let v=n.body_max_length||5e3,E=x.request.postData;E.length>v?R.request_body=E.substring(0,v)+"...[truncated]":R.request_body=E;}u.set(x.requestId,R),m.debug("BROWSER",`[CDP Network] ${j.toUpperCase()} ${R.method} ${R.url}`);}}),p.on("Network.responseReceived",x=>{let R=u.get(x.requestId);R&&R.timing&&(R.status=x.response.status,R.status_text=x.response.statusText,R.response_headers=x.response.headers,R.timing.end=x.timestamp*1e3,R.timing.duration=R.timing.end-R.timing.start,m.debug("BROWSER",`[CDP Network] Response ${R.status} ${R.url} (${R.timing.duration.toFixed(0)}ms)`));}),p.on("Network.loadingFailed",x=>{let R=u.get(x.requestId);R&&(R.error=x.errorText,R.timing&&(R.timing.end=x.timestamp*1e3,R.timing.duration=R.timing.end-R.timing.start),m.debug("BROWSER",`[CDP Network] Failed ${R.url}: ${R.error}`));})),t.collect_console!==false&&a.on("console",x=>{let R=x.type();i.push({type:R,timestamp:Date.now(),message:x.text(),args:x.args().map(j=>j.toString())}),m.debug("BROWSER",`[Puppeteer console] ${R}: ${x.text().substring(0,100)}`);}),t.collect_network!==false&&(r==="puppeteer"||r==="both")){let x=null;if(n.url_pattern)try{x=new RegExp(n.url_pattern,"i");}catch{m.warn("BROWSER",`Invalid URL pattern: ${n.url_pattern}`);}a.on("request",R=>{let j=R.url(),v=R.resourceType();if(n.xhr_only&&!Hg.includes(v)||!n.xhr_only&&uu.includes(v)||x&&!x.test(j))return;`${R.method()}-${j}-${Date.now()}`;let L={url:j,method:R.method(),resource_type:v,request_headers:R.headers(),timing:{start:Date.now(),end:0,duration:0}},I=R.postData();if(I){let A=n.body_max_length||5e3;I.length>A?L.request_body=I.substring(0,A)+"...[truncated]":L.request_body=I;}c.set(j,L),m.debug("BROWSER",`[Network] ${v.toUpperCase()} ${R.method()} ${j}`);}),a.on("response",async R=>{let j=R.url(),v=c.get(j);if(!v||!v.timing)return;v.status=R.status(),v.status_text=R.statusText(),v.response_headers=R.headers(),v.timing.end=Date.now(),v.timing.duration=v.timing.end-v.timing.start;let E=v.status>=400;if(n.include_body&&(E||n.status_filter))try{let I=R.headers()["content-type"]||"";if(I.includes("json")||I.includes("text")||I.includes("html")){let A=await R.text(),O=n.body_max_length||5e3;A.length>O?(v.response_body=A.substring(0,O),v.response_truncated=!0):v.response_body=A;}}catch(I){m.debug("BROWSER",`Failed to get response body for ${j}: ${I}`);}m.debug("BROWSER",`[Network] Response ${v.status} ${j} (${v.timing.duration}ms)`);}),a.on("requestfailed",R=>{let j=R.url(),v=c.get(j),E=R.failure();v&&(v.error=E?.errorText||"Request failed",v.timing&&(v.timing.end=Date.now(),v.timing.duration=v.timing.end-v.timing.start)),o.push({type:"browser_error",message:`Request failed: ${E?.errorText||"Unknown error"}`,stack:"",file:j,timestamp:Date.now()});});}m.info("BROWSER",`Navigating to: ${e}`),await a.goto(e,{waitUntil:"networkidle2",timeout:3e4});try{await p.send("Runtime.enable"),await p.send("Log.enable"),m.debug("BROWSER","Re-enabled Runtime and Log domains after navigation");}catch{m.debug("BROWSER","Failed to re-enable CDP domains (may already be enabled)");}if(t.collect_console!==false||t.collect_errors!==false)try{await a.evaluate(d),m.debug("BROWSER","Ensured script injection after page.goto");}catch{m.debug("BROWSER","Script already injected or page not ready");}let b=t.wait_time||3e3;if(m.info("BROWSER",`Waiting ${b}ms for async content...`),await new Promise(x=>setTimeout(x,b)),m.debug("BROWSER","Starting to extract injected logs..."),t.collect_console!==false||t.collect_errors!==false)try{m.debug("BROWSER","Calling page.evaluate to get __NEOX_CONSOLE_LOGS__...");let x=await a.evaluate(()=>({consoleLogs:window.__NEOX_CONSOLE_LOGS__||[],errors:window.__NEOX_ERRORS__||[]}));m.debug("BROWSER",`Extracted ${x.consoleLogs.length} console logs and ${x.errors.length} errors from injected script`);for(let v of x.consoleLogs)m.debug("BROWSER",` [${v.type}] ${v.message?.substring(0,100)}`);let R=new Map;for(let v of x.consoleLogs){let E=`${v.type}:${v.message}`;R.has(E)||R.set(E,{type:v.type,timestamp:v.timestamp,message:v.message});}for(let v of i){let E=`${v.type}:${v.message}`;R.has(E)||R.set(E,v);}i.length=0,i.push(...Array.from(R.values()));let j=new Map;for(let v of x.errors){let E=`${v.type}:${v.message}`;j.has(E)||j.set(E,{type:v.type,message:v.message,stack:v.stack||"",file:v.file,line:v.line,column:v.column,timestamp:v.timestamp});}for(let v of o){let E=`${v.type}:${v.message}`;j.has(E)||j.set(E,v);}o.length=0,o.push(...Array.from(j.values())),m.info("BROWSER",`Final: ${i.length} console logs, ${o.length} errors`);}catch(x){m.error("BROWSER","Failed to extract injected logs",{error:x});}let y;if(t.collect_performance!==false)try{let x=await a.metrics(),R=await a.evaluate(()=>{let j=window.performance,v=j.timing,E=j.getEntriesByType("paint"),L=document.querySelectorAll("*"),I=0,A=0,O=0,$=Math.min(1e3,L.length),P=Math.max(1,Math.floor(L.length/$));for(let D=0;D<L.length;D+=P){let G=L[D],z=window.getComputedStyle(G);z.display!=="none"&&z.visibility!=="hidden"&&z.opacity!=="0"?I++:A++;let oe=0,ue=G.parentElement;for(;ue;)oe++,ue=ue.parentElement;O=Math.max(O,oe);}let N=L.length/$;return I=Math.round(I*N),A=Math.round(A*N),{domContentLoaded:v.domContentLoadedEventEnd-v.navigationStart,loadComplete:v.loadEventEnd-v.navigationStart,paintMetrics:{first_paint:E.find(D=>D.name==="first-paint")?.startTime||0,first_contentful_paint:E.find(D=>D.name==="first-contentful-paint")?.startTime||0},memory:j.memory?{used_heap:j.memory.usedJSHeapSize,total_heap:j.memory.totalJSHeapSize,heap_limit:j.memory.jsHeapSizeLimit}:void 0,domStats:{visible_nodes:I,hidden_nodes:A,max_depth:O}}});y={dom_content_loaded:R.domContentLoaded,load_complete:R.loadComplete,dom_nodes:x.Nodes||0,js_heap_size:x.JSHeapUsedSize||0,event_listeners:x.JSEventListeners||0,paint_metrics:R.paintMetrics,memory:R.memory,dom_stats:R.domStats},m.info("BROWSER",`Performance: ${y.dom_nodes} nodes, ${(y.js_heap_size/1024/1024).toFixed(1)}MB heap`);}catch(x){m.error("BROWSER","Failed to collect performance metrics",{error:x});}let w;if(t.take_screenshot===true)try{w=await a.screenshot({encoding:"base64"});}catch(x){m.error("BROWSER","Failed to capture screenshot",{error:x});}try{await p.detach();}catch{}if(r==="cdp"||r==="both")for(let[x,R]of u.entries())Array.from(c.values()).find(v=>v.url===R.url)||c.set(x,R);let C=Array.from(c.values());r==="cdp"&&(C=Array.from(u.values()));let k=C.length;n.status_filter&&(C=C.filter(x=>Jg(x.status,n.status_filter)));let T=C.filter(x=>x.error||x.status&&x.status>=400).length;C.sort((x,R)=>{let j=x.error||x.status&&x.status>=400,v=R.error||R.status&&R.status>=400;return j&&!v?-1:!j&&v?1:(x.timing?.start||0)-(R.timing?.start||0)});let _=n.max_results||20;C.length>_&&(C=C.slice(0,_));let M={total_captured:k,filtered_count:C.length,error_count:T};m.info("BROWSER",`Network: ${k} captured, ${C.length} returned, ${T} errors`);let F=Date.now()-s;return {console_logs:i,errors:o,network_requests:C,network_stats:M,performance:y,screenshot:w,load_time:F}}function Qr(a){let e=[];a.errors&&a.errors.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${a.errors.length} \u4E2A JavaScript \u5F02\u5E38\uFF1A`),a.errors.slice(0,5).forEach((i,o)=>{e.push(` ${o+1}. ${i.message}`),i.file&&e.push(` \u4F4D\u7F6E\uFF1A${i.file}:${i.line||""}`);}),e.push(""));let t=a.console_logs?.filter(i=>i.type==="error")||[];t.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${t.length} \u4E2A console.error \u65E5\u5FD7\uFF1A`),t.slice(0,5).forEach((i,o)=>{e.push(` ${o+1}. ${i.message}`);}),e.push(""));let s=a.console_logs?.filter(i=>i.type==="warn")||[];s.length>0&&(e.push(`\u26A0\uFE0F ${s.length} \u4E2A console.warn \u8B66\u544A\uFF1A`),s.slice(0,3).forEach((i,o)=>{e.push(` ${o+1}. ${i.message}`);}),e.push(""));let n=a.console_logs?.filter(i=>i.type==="debug")||[];if(n.length>0&&(e.push(`\u{1F50D} ${n.length} \u4E2A console.debug \u65E5\u5FD7\uFF1A`),n.slice(0,3).forEach((i,o)=>{e.push(` ${o+1}. ${i.message}`);}),e.push("")),a.errors?.length===0&&t.length===0&&s.length===0&&(e.push("\u2705 \u672A\u53D1\u73B0 JavaScript \u9519\u8BEF\u6216\u8B66\u544A"),e.push("")),a.network_stats){let i=a.network_stats;e.push(`\u{1F310} \u7F51\u7EDC\u8BF7\u6C42\uFF1A\u5171\u6355\u83B7 ${i.total_captured} \u4E2A\uFF0C\u8FD4\u56DE ${i.filtered_count} \u4E2A\uFF0C${i.error_count} \u4E2A\u9519\u8BEF`);}let r=a.network_requests?.filter(i=>i.error||i.status&&i.status>=400)||[];if(r.length>0&&(e.push(`\u{1F534} ${r.length} \u4E2A API \u9519\u8BEF\u8BF7\u6C42\uFF1A`),r.slice(0,5).forEach((i,o)=>{if(e.push(` ${o+1}. [${i.status||"Failed"}] ${i.method} ${i.url}`),i.response_body){let l=i.response_body.substring(0,200);e.push(` \u54CD\u5E94: ${l}${i.response_body.length>200?"...":""}`);}i.error&&e.push(` \u9519\u8BEF: ${i.error}`);}),e.push("")),a.performance){let i=a.performance;if(i.dom_nodes>15e3?e.push(`\u{1F534} \u4E25\u91CD\u8B66\u544A\uFF1ADOM \u8282\u70B9\u8FC7\u591A (${i.dom_nodes.toLocaleString()}), \u9875\u9762\u6027\u80FD\u6781\u5DEE`):i.dom_nodes>1e4?e.push(`\u26A0\uFE0F \u8B66\u544A\uFF1ADOM \u8282\u70B9\u504F\u591A (${i.dom_nodes.toLocaleString()}), \u53EF\u80FD\u5F71\u54CD\u6027\u80FD`):i.dom_nodes>5e3&&e.push(`\u26A1 \u63D0\u793A\uFF1ADOM \u8282\u70B9\u8F83\u591A (${i.dom_nodes.toLocaleString()}), \u5EFA\u8BAE\u4F18\u5316`),i.dom_stats){let o=i.dom_stats,l=o.hidden_nodes/i.dom_nodes*100;e.push(` \u{1F4CA} \u53EF\u89C1: ${o.visible_nodes.toLocaleString()}, \u9690\u85CF: ${o.hidden_nodes.toLocaleString()} (${l.toFixed(1)}%), \u6700\u5927\u6DF1\u5EA6: ${o.max_depth} \u5C42`),l>40&&e.push(" \u26A0\uFE0F \u9690\u85CF\u8282\u70B9\u5360\u6BD4\u8FC7\u9AD8\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6E05\u7406\u7684 DOM \u5143\u7D20"),o.max_depth>30&&e.push(` \u26A0\uFE0F DOM \u5D4C\u5957\u5C42\u7EA7\u8FC7\u6DF1 (${o.max_depth}), \u53EF\u80FD\u5B58\u5728\u6027\u80FD\u95EE\u9898`);}if(i.memory){let o=i.memory.used_heap/1024/1024,l=i.memory.heap_limit/1024/1024,c=i.memory.used_heap/i.memory.heap_limit*100;c>80?e.push(`\u26A1 \u5185\u5B58\u8B66\u544A\uFF1A\u5806\u4F7F\u7528\u7387 ${c.toFixed(1)}% (${o.toFixed(1)}MB / ${l.toFixed(1)}MB), \u63A5\u8FD1\u9650\u5236`):o>100&&e.push(`\u26A1 \u5185\u5B58\u63D0\u793A\uFF1A\u5806\u5185\u5B58\u8F83\u5927 ${o.toFixed(1)}MB`);}else i.js_heap_size>50*1024*1024&&e.push(`\u26A1 \u6027\u80FD\u8B66\u544A\uFF1AJS \u5806\u5185\u5B58\u8FC7\u5927 (${(i.js_heap_size/1024/1024).toFixed(1)}MB)`);i.paint_metrics&&i.paint_metrics.first_contentful_paint>3e3&&e.push(`\u26A1 \u6E32\u67D3\u6162\uFF1A\u9996\u6B21\u5185\u5BB9\u7ED8\u5236 ${i.paint_metrics.first_contentful_paint.toFixed(0)}ms (\u5EFA\u8BAE < 1500ms)`),i.load_complete>5e3&&e.push(`\u26A1 \u52A0\u8F7D\u6162\uFF1A\u9875\u9762\u5B8C\u5168\u52A0\u8F7D\u8017\u65F6 ${i.load_complete.toFixed(0)}ms (\u5EFA\u8BAE < 3000ms)`);}return e.join(`
225
+ `)||"",file:R.url,line:R.lineNumber,timestamp:Date.now()}),m.debug("BROWSER",`[CDP Log Error] ${R.text}`)):(i.push({type:"error",timestamp:Date.now(),message:R.text}),m.debug("BROWSER",`[CDP Log] error: ${R.text}`)):j==="warning"&&i.push({type:"warn",timestamp:Date.now(),message:R.text});};if(t.collect_console!==false&&p.on("Runtime.consoleAPICalled",h),t.collect_errors!==false&&(p.on("Runtime.exceptionThrown",g),p.on("Log.entryAdded",f),a.on("pageerror",x=>{let R=x;o.push({type:"exception",message:R.message,stack:R.stack||"",timestamp:Date.now()}),m.debug("BROWSER",`[Puppeteer pageerror] ${R.message}`);}),a.on("requestfailed",x=>{let R=x.failure();o.push({type:"browser_error",message:`Request failed: ${R?.errorText||"Unknown error"}`,stack:"",file:x.url(),timestamp:Date.now()});})),t.collect_network!==false&&(r==="cdp"||r==="both")&&(p.on("Network.requestWillBeSent",x=>{let R={url:x.request.url,method:x.request.method,resource_type:x.type?.toLowerCase()||"other",request_headers:x.request.headers,timing:{start:x.timestamp*1e3,end:0,duration:0}},j=x.type?.toLowerCase()||"other";if(!(n.xhr_only&&!["xhr","fetch"].includes(j))&&!(!n.xhr_only&&uu.includes(j))){if(x.request.postData){let v=n.body_max_length||5e3,E=x.request.postData;E.length>v?R.request_body=E.substring(0,v)+"...[truncated]":R.request_body=E;}u.set(x.requestId,R),m.debug("BROWSER",`[CDP Network] ${j.toUpperCase()} ${R.method} ${R.url}`);}}),p.on("Network.responseReceived",x=>{let R=u.get(x.requestId);R&&R.timing&&(R.status=x.response.status,R.status_text=x.response.statusText,R.response_headers=x.response.headers,R.timing.end=x.timestamp*1e3,R.timing.duration=R.timing.end-R.timing.start,m.debug("BROWSER",`[CDP Network] Response ${R.status} ${R.url} (${R.timing.duration.toFixed(0)}ms)`));}),p.on("Network.loadingFailed",x=>{let R=u.get(x.requestId);R&&(R.error=x.errorText,R.timing&&(R.timing.end=x.timestamp*1e3,R.timing.duration=R.timing.end-R.timing.start),m.debug("BROWSER",`[CDP Network] Failed ${R.url}: ${R.error}`));})),t.collect_console!==false&&a.on("console",x=>{let R=x.type();i.push({type:R,timestamp:Date.now(),message:x.text(),args:x.args().map(j=>j.toString())}),m.debug("BROWSER",`[Puppeteer console] ${R}: ${x.text().substring(0,100)}`);}),t.collect_network!==false&&(r==="puppeteer"||r==="both")){let x=null;if(n.url_pattern)try{x=new RegExp(n.url_pattern,"i");}catch{m.warn("BROWSER",`Invalid URL pattern: ${n.url_pattern}`);}a.on("request",R=>{let j=R.url(),v=R.resourceType();if(n.xhr_only&&!Hg.includes(v)||!n.xhr_only&&uu.includes(v)||x&&!x.test(j))return;`${R.method()}-${j}-${Date.now()}`;let P={url:j,method:R.method(),resource_type:v,request_headers:R.headers(),timing:{start:Date.now(),end:0,duration:0}},I=R.postData();if(I){let A=n.body_max_length||5e3;I.length>A?P.request_body=I.substring(0,A)+"...[truncated]":P.request_body=I;}c.set(j,P),m.debug("BROWSER",`[Network] ${v.toUpperCase()} ${R.method()} ${j}`);}),a.on("response",async R=>{let j=R.url(),v=c.get(j);if(!v||!v.timing)return;v.status=R.status(),v.status_text=R.statusText(),v.response_headers=R.headers(),v.timing.end=Date.now(),v.timing.duration=v.timing.end-v.timing.start;let E=v.status>=400;if(n.include_body&&(E||n.status_filter))try{let I=R.headers()["content-type"]||"";if(I.includes("json")||I.includes("text")||I.includes("html")){let A=await R.text(),O=n.body_max_length||5e3;A.length>O?(v.response_body=A.substring(0,O),v.response_truncated=!0):v.response_body=A;}}catch(I){m.debug("BROWSER",`Failed to get response body for ${j}: ${I}`);}m.debug("BROWSER",`[Network] Response ${v.status} ${j} (${v.timing.duration}ms)`);}),a.on("requestfailed",R=>{let j=R.url(),v=c.get(j),E=R.failure();v&&(v.error=E?.errorText||"Request failed",v.timing&&(v.timing.end=Date.now(),v.timing.duration=v.timing.end-v.timing.start)),o.push({type:"browser_error",message:`Request failed: ${E?.errorText||"Unknown error"}`,stack:"",file:j,timestamp:Date.now()});});}m.info("BROWSER",`Navigating to: ${e}`),await a.goto(e,{waitUntil:"networkidle2",timeout:3e4});try{await p.send("Runtime.enable"),await p.send("Log.enable"),m.debug("BROWSER","Re-enabled Runtime and Log domains after navigation");}catch{m.debug("BROWSER","Failed to re-enable CDP domains (may already be enabled)");}if(t.collect_console!==false||t.collect_errors!==false)try{await a.evaluate(d),m.debug("BROWSER","Ensured script injection after page.goto");}catch{m.debug("BROWSER","Script already injected or page not ready");}let b=t.wait_time||3e3;if(m.info("BROWSER",`Waiting ${b}ms for async content...`),await new Promise(x=>setTimeout(x,b)),m.debug("BROWSER","Starting to extract injected logs..."),t.collect_console!==false||t.collect_errors!==false)try{m.debug("BROWSER","Calling page.evaluate to get __NEOX_CONSOLE_LOGS__...");let x=await a.evaluate(()=>({consoleLogs:window.__NEOX_CONSOLE_LOGS__||[],errors:window.__NEOX_ERRORS__||[]}));m.debug("BROWSER",`Extracted ${x.consoleLogs.length} console logs and ${x.errors.length} errors from injected script`);for(let v of x.consoleLogs)m.debug("BROWSER",` [${v.type}] ${v.message?.substring(0,100)}`);let R=new Map;for(let v of x.consoleLogs){let E=`${v.type}:${v.message}`;R.has(E)||R.set(E,{type:v.type,timestamp:v.timestamp,message:v.message});}for(let v of i){let E=`${v.type}:${v.message}`;R.has(E)||R.set(E,v);}i.length=0,i.push(...Array.from(R.values()));let j=new Map;for(let v of x.errors){let E=`${v.type}:${v.message}`;j.has(E)||j.set(E,{type:v.type,message:v.message,stack:v.stack||"",file:v.file,line:v.line,column:v.column,timestamp:v.timestamp});}for(let v of o){let E=`${v.type}:${v.message}`;j.has(E)||j.set(E,v);}o.length=0,o.push(...Array.from(j.values())),m.info("BROWSER",`Final: ${i.length} console logs, ${o.length} errors`);}catch(x){m.error("BROWSER","Failed to extract injected logs",{error:x});}let y;if(t.collect_performance!==false)try{let x=await a.metrics(),R=await a.evaluate(()=>{let j=window.performance,v=j.timing,E=j.getEntriesByType("paint"),P=document.querySelectorAll("*"),I=0,A=0,O=0,$=Math.min(1e3,P.length),D=Math.max(1,Math.floor(P.length/$));for(let L=0;L<P.length;L+=D){let G=P[L],z=window.getComputedStyle(G);z.display!=="none"&&z.visibility!=="hidden"&&z.opacity!=="0"?I++:A++;let oe=0,ue=G.parentElement;for(;ue;)oe++,ue=ue.parentElement;O=Math.max(O,oe);}let N=P.length/$;return I=Math.round(I*N),A=Math.round(A*N),{domContentLoaded:v.domContentLoadedEventEnd-v.navigationStart,loadComplete:v.loadEventEnd-v.navigationStart,paintMetrics:{first_paint:E.find(L=>L.name==="first-paint")?.startTime||0,first_contentful_paint:E.find(L=>L.name==="first-contentful-paint")?.startTime||0},memory:j.memory?{used_heap:j.memory.usedJSHeapSize,total_heap:j.memory.totalJSHeapSize,heap_limit:j.memory.jsHeapSizeLimit}:void 0,domStats:{visible_nodes:I,hidden_nodes:A,max_depth:O}}});y={dom_content_loaded:R.domContentLoaded,load_complete:R.loadComplete,dom_nodes:x.Nodes||0,js_heap_size:x.JSHeapUsedSize||0,event_listeners:x.JSEventListeners||0,paint_metrics:R.paintMetrics,memory:R.memory,dom_stats:R.domStats},m.info("BROWSER",`Performance: ${y.dom_nodes} nodes, ${(y.js_heap_size/1024/1024).toFixed(1)}MB heap`);}catch(x){m.error("BROWSER","Failed to collect performance metrics",{error:x});}let w;if(t.take_screenshot===true)try{w=await a.screenshot({encoding:"base64"});}catch(x){m.error("BROWSER","Failed to capture screenshot",{error:x});}try{await p.detach();}catch{}if(r==="cdp"||r==="both")for(let[x,R]of u.entries())Array.from(c.values()).find(v=>v.url===R.url)||c.set(x,R);let C=Array.from(c.values());r==="cdp"&&(C=Array.from(u.values()));let k=C.length;n.status_filter&&(C=C.filter(x=>Jg(x.status,n.status_filter)));let T=C.filter(x=>x.error||x.status&&x.status>=400).length;C.sort((x,R)=>{let j=x.error||x.status&&x.status>=400,v=R.error||R.status&&R.status>=400;return j&&!v?-1:!j&&v?1:(x.timing?.start||0)-(R.timing?.start||0)});let _=n.max_results||20;C.length>_&&(C=C.slice(0,_));let M={total_captured:k,filtered_count:C.length,error_count:T};m.info("BROWSER",`Network: ${k} captured, ${C.length} returned, ${T} errors`);let F=Date.now()-s;return {console_logs:i,errors:o,network_requests:C,network_stats:M,performance:y,screenshot:w,load_time:F}}function Qr(a){let e=[];a.errors&&a.errors.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${a.errors.length} \u4E2A JavaScript \u5F02\u5E38\uFF1A`),a.errors.slice(0,5).forEach((i,o)=>{e.push(` ${o+1}. ${i.message}`),i.file&&e.push(` \u4F4D\u7F6E\uFF1A${i.file}:${i.line||""}`);}),e.push(""));let t=a.console_logs?.filter(i=>i.type==="error")||[];t.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${t.length} \u4E2A console.error \u65E5\u5FD7\uFF1A`),t.slice(0,5).forEach((i,o)=>{e.push(` ${o+1}. ${i.message}`);}),e.push(""));let s=a.console_logs?.filter(i=>i.type==="warn")||[];s.length>0&&(e.push(`\u26A0\uFE0F ${s.length} \u4E2A console.warn \u8B66\u544A\uFF1A`),s.slice(0,3).forEach((i,o)=>{e.push(` ${o+1}. ${i.message}`);}),e.push(""));let n=a.console_logs?.filter(i=>i.type==="debug")||[];if(n.length>0&&(e.push(`\u{1F50D} ${n.length} \u4E2A console.debug \u65E5\u5FD7\uFF1A`),n.slice(0,3).forEach((i,o)=>{e.push(` ${o+1}. ${i.message}`);}),e.push("")),a.errors?.length===0&&t.length===0&&s.length===0&&(e.push("\u2705 \u672A\u53D1\u73B0 JavaScript \u9519\u8BEF\u6216\u8B66\u544A"),e.push("")),a.network_stats){let i=a.network_stats;e.push(`\u{1F310} \u7F51\u7EDC\u8BF7\u6C42\uFF1A\u5171\u6355\u83B7 ${i.total_captured} \u4E2A\uFF0C\u8FD4\u56DE ${i.filtered_count} \u4E2A\uFF0C${i.error_count} \u4E2A\u9519\u8BEF`);}let r=a.network_requests?.filter(i=>i.error||i.status&&i.status>=400)||[];if(r.length>0&&(e.push(`\u{1F534} ${r.length} \u4E2A API \u9519\u8BEF\u8BF7\u6C42\uFF1A`),r.slice(0,5).forEach((i,o)=>{if(e.push(` ${o+1}. [${i.status||"Failed"}] ${i.method} ${i.url}`),i.response_body){let l=i.response_body.substring(0,200);e.push(` \u54CD\u5E94: ${l}${i.response_body.length>200?"...":""}`);}i.error&&e.push(` \u9519\u8BEF: ${i.error}`);}),e.push("")),a.performance){let i=a.performance;if(i.dom_nodes>15e3?e.push(`\u{1F534} \u4E25\u91CD\u8B66\u544A\uFF1ADOM \u8282\u70B9\u8FC7\u591A (${i.dom_nodes.toLocaleString()}), \u9875\u9762\u6027\u80FD\u6781\u5DEE`):i.dom_nodes>1e4?e.push(`\u26A0\uFE0F \u8B66\u544A\uFF1ADOM \u8282\u70B9\u504F\u591A (${i.dom_nodes.toLocaleString()}), \u53EF\u80FD\u5F71\u54CD\u6027\u80FD`):i.dom_nodes>5e3&&e.push(`\u26A1 \u63D0\u793A\uFF1ADOM \u8282\u70B9\u8F83\u591A (${i.dom_nodes.toLocaleString()}), \u5EFA\u8BAE\u4F18\u5316`),i.dom_stats){let o=i.dom_stats,l=o.hidden_nodes/i.dom_nodes*100;e.push(` \u{1F4CA} \u53EF\u89C1: ${o.visible_nodes.toLocaleString()}, \u9690\u85CF: ${o.hidden_nodes.toLocaleString()} (${l.toFixed(1)}%), \u6700\u5927\u6DF1\u5EA6: ${o.max_depth} \u5C42`),l>40&&e.push(" \u26A0\uFE0F \u9690\u85CF\u8282\u70B9\u5360\u6BD4\u8FC7\u9AD8\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6E05\u7406\u7684 DOM \u5143\u7D20"),o.max_depth>30&&e.push(` \u26A0\uFE0F DOM \u5D4C\u5957\u5C42\u7EA7\u8FC7\u6DF1 (${o.max_depth}), \u53EF\u80FD\u5B58\u5728\u6027\u80FD\u95EE\u9898`);}if(i.memory){let o=i.memory.used_heap/1024/1024,l=i.memory.heap_limit/1024/1024,c=i.memory.used_heap/i.memory.heap_limit*100;c>80?e.push(`\u26A1 \u5185\u5B58\u8B66\u544A\uFF1A\u5806\u4F7F\u7528\u7387 ${c.toFixed(1)}% (${o.toFixed(1)}MB / ${l.toFixed(1)}MB), \u63A5\u8FD1\u9650\u5236`):o>100&&e.push(`\u26A1 \u5185\u5B58\u63D0\u793A\uFF1A\u5806\u5185\u5B58\u8F83\u5927 ${o.toFixed(1)}MB`);}else i.js_heap_size>50*1024*1024&&e.push(`\u26A1 \u6027\u80FD\u8B66\u544A\uFF1AJS \u5806\u5185\u5B58\u8FC7\u5927 (${(i.js_heap_size/1024/1024).toFixed(1)}MB)`);i.paint_metrics&&i.paint_metrics.first_contentful_paint>3e3&&e.push(`\u26A1 \u6E32\u67D3\u6162\uFF1A\u9996\u6B21\u5185\u5BB9\u7ED8\u5236 ${i.paint_metrics.first_contentful_paint.toFixed(0)}ms (\u5EFA\u8BAE < 1500ms)`),i.load_complete>5e3&&e.push(`\u26A1 \u52A0\u8F7D\u6162\uFF1A\u9875\u9762\u5B8C\u5168\u52A0\u8F7D\u8017\u65F6 ${i.load_complete.toFixed(0)}ms (\u5EFA\u8BAE < 3000ms)`);}return e.join(`
226
226
  `)||"\u2705 \u9875\u9762\u8FD0\u884C\u6B63\u5E38\uFF0C\u672A\u53D1\u73B0\u660E\u663E\u95EE\u9898"}async function du(a){let e=await Kg(a);if(e)return {url:`http://localhost:${e}`,port:e,protocol:"http",source:"vite.config"};let t=await Vg(a);if(t)return {url:`http://localhost:${t}`,port:t,protocol:"http",source:"package.json"};let s=await Yg(a);if(s)return {url:`http://localhost:${s}`,port:s,protocol:"http",source:"env"};let n=await Xg(a);return {url:`http://localhost:${n}`,port:n,protocol:"http",source:"default"}}async function Kg(a){try{let e=join(a,"vite.config.js"),s=(await readFile(e,"utf-8")).match(/server\s*:\s*\{[^}]*port\s*:\s*(\d+)/);return s?parseInt(s[1]):null}catch{return null}}async function Vg(a){try{let e=join(a,"package.json"),t=await readFile(e,"utf-8"),n=JSON.parse(t).scripts?.dev||"",r=n.match(/--port\s+(\d+)/);if(r)return parseInt(r[1]);let i=n.match(/PORT=(\d+)/);return i?parseInt(i[1]):null}catch{return null}}async function Yg(a){try{let e=join(a,".env"),s=(await readFile(e,"utf-8")).match(/(?:VITE_)?PORT\s*=\s*(\d+)/);return s?parseInt(s[1]):null}catch{return null}}async function Xg(a){try{let e=join(a,"package.json"),t=await readFile(e,"utf-8"),s=JSON.parse(t),n={...s.dependencies,...s.devDependencies};return n.vite?5173:n.next||n["react-scripts"]?3e3:n.vue?8080:n.nuxt?3e3:n.svelte?5e3:3e3}catch{return 3e3}}async function ha(a,e=3e3){try{let t=new AbortController,s=setTimeout(()=>t.abort(),e),n=await fetch(a,{method:"HEAD",signal:t.signal});return clearTimeout(s),n.ok}catch{return false}}async function fa(a){let e=await du(a);if(await ha(e.url))return e;let s=[5173,3e3,8080,5e3,4200,8e3];for(let n of s){let r=`http://localhost:${n}`;if(await ha(r))return {url:r,port:n,protocol:"http",source:"default"}}return null}W();var sh="headers.json";function pu(a){try{return new URL(a).hostname}catch{return a}}function mu(){let a=Yr();return join(a,sh)}function gu(){let a=mu();if(!existsSync(a))return {};try{let e=readFileSync(a,"utf-8");return JSON.parse(e)}catch(e){return m.warn("HEADERS","Failed to read headers config",{error:e}),{}}}function hu(a){let e=mu();try{let t=JSON.stringify(a,null,2);writeFileSync(e,t,"utf-8"),m.info("HEADERS","Headers config saved",{path:e});}catch(t){m.error("HEADERS","Failed to save headers config",{error:t});}}function ti(a,e){let t=pu(a),s=gu(),n=nh(e);if(Object.keys(n).length===0){m.info("HEADERS","No headers to save for domain",{domain:t});return}s[t]={headers:n,lastUsed:Date.now(),createdAt:s[t]?.createdAt||Date.now(),url:a},hu(s),m.info("HEADERS","Saved headers for domain",{domain:t,headerCount:Object.keys(n).length});}function ya(a){let e=pu(a),t=gu(),s=t[e];return s?(s.lastUsed=Date.now(),hu(t),m.info("HEADERS","Retrieved headers for domain",{domain:e,headerCount:Object.keys(s.headers).length}),s.headers):(m.info("HEADERS","No saved headers for domain",{domain:e}),null)}function nh(a){let e={},t=[/^authorization$/i,/^x-/i,/^cookie$/i,/^token$/i,/^auth/i,/^api-key$/i,/^api_key$/i,/^apikey$/i],s=new Set(["user-agent","accept","accept-encoding","accept-language","content-type","content-length","host","origin","referer","connection","cache-control","pragma","upgrade-insecure-requests","sec-fetch-site","sec-fetch-mode","sec-fetch-dest","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform"]);for(let[n,r]of Object.entries(a)){let i=n.toLowerCase();if(s.has(i))continue;t.some(l=>l.test(n))&&(e[n]=r);}return e}var rh=["login","signin","sign-in","sign_in","auth","oauth","sso","account","passport","cas","saml","oidc"],ih=['input[type="password"]','form[action*="login"]','form[action*="signin"]','form[action*="auth"]','button[type="submit"]:has-text("\u767B\u5F55")','button[type="submit"]:has-text("Login")','button[type="submit"]:has-text("Sign in")'],oh=['input[name="username"]','input[name="user"]','input[name="email"]','input[name="account"]','input[name="login"]','input[name="userId"]','input[name="loginId"]','input[id="username"]','input[id="user"]','input[id="email"]','input[id="account"]','input[id="login"]','input[type="email"]','input[type="text"][autocomplete="username"]','input[placeholder*="\u7528\u6237\u540D"]','input[placeholder*="\u8D26\u53F7"]','input[placeholder*="\u90AE\u7BB1"]','input[placeholder*="\u624B\u673A"]','input[placeholder*="Username"]','input[placeholder*="Email"]'],ah=['input[type="password"]','input[name="password"]','input[name="pwd"]','input[name="pass"]','input[id="password"]','input[id="pwd"]'],lh=['button[type="submit"]','input[type="submit"]','button:has-text("\u767B\u5F55")','button:has-text("Login")','button:has-text("Sign in")','button:has-text("Log in")','button:has-text("\u786E\u5B9A")','button:has-text("Submit")','a:has-text("\u767B\u5F55")',".login-btn",".submit-btn","#login-btn","#submit"];async function fu(a,e){let t={},s=false,n=i=>{if(s)return;i.url();let l=i.resourceType();if(l==="xhr"||l==="fetch"||l==="document"){let c=i.headers();Object.assign(t,c);}},r=i=>{if(s)return;let o=i.status();i.url();let c=i.request().resourceType();o>=200&&o<300&&(c==="xhr"||c==="fetch")&&(s=true);};return a.on("request",n),a.on("response",r),t}async function ch(a,e){let t=ya(e);return !t||Object.keys(t).length===0?false:(await a.setExtraHTTPHeaders(t),true)}async function ba(a,e){let t=a.url(),s=t.toLowerCase();if(t!==e&&rh.some(r=>s.includes(r)))return {detected:true,original_url:e,redirected_url:t,redirect_type:"url_change",reason:`\u9875\u9762\u88AB\u91CD\u5B9A\u5411\u5230\u767B\u5F55\u9875\u9762: ${t}`};try{for(let n of ih)if(await a.$(n))return {detected:!0,original_url:e,redirected_url:t,redirect_type:"login_form",reason:`\u9875\u9762\u5305\u542B\u767B\u5F55\u8868\u5355\u5143\u7D20: ${n}`}}catch{}try{let n=await a.title(),r=n.toLowerCase(),i=["login","\u767B\u5F55","sign in","\u767B\u5165","authenticate","\u8BA4\u8BC1"];for(let o of i)if(r.includes(o))return {detected:!0,original_url:e,redirected_url:t,redirect_type:"auth_keyword",reason:`\u9875\u9762\u6807\u9898\u5305\u542B\u767B\u5F55\u5173\u952E\u8BCD: "${n}"`}}catch{}return {detected:false,original_url:e}}async function uh(a,e,t){try{t?.("auto_login_start",{message:"\u6B63\u5728\u81EA\u52A8\u586B\u5199\u767B\u5F55\u8868\u5355..."});let s=null;if(e.username_selector&&(s=await a.$(e.username_selector)),!s)for(let i of oh)try{if(s=await a.$(i),s)break}catch{}if(!s)return {success:!1,error:"\u627E\u4E0D\u5230\u7528\u6237\u540D\u8F93\u5165\u6846"};let n=null;if(e.password_selector&&(n=await a.$(e.password_selector)),!n)for(let i of ah)try{if(n=await a.$(i),n)break}catch{}if(!n)return {success:!1,error:"\u627E\u4E0D\u5230\u5BC6\u7801\u8F93\u5165\u6846"};let r=null;if(e.submit_selector&&(r=await a.$(e.submit_selector)),!r)for(let i of lh)try{if(r=await a.$(i),r)break}catch{}return r?(await s.click({clickCount:3}),await s.type(e.username,{delay:50}),t?.("auto_login_progress",{message:"\u5DF2\u586B\u5199\u7528\u6237\u540D"}),await n.click({clickCount:3}),await n.type(e.password,{delay:50}),t?.("auto_login_progress",{message:"\u5DF2\u586B\u5199\u5BC6\u7801"}),t?.("auto_login_progress",{message:"\u6B63\u5728\u63D0\u4EA4\u767B\u5F55..."}),await Promise.all([a.waitForNavigation({waitUntil:"networkidle0",timeout:3e4}).catch(()=>{}),r.click()]),await new Promise(i=>setTimeout(i,2e3)),{success:!0}):{success:!1,error:"\u627E\u4E0D\u5230\u767B\u5F55\u6309\u94AE"}}catch(s){return {success:false,error:String(s)}}}async function si(a,e,t){let s=null,r=a.open_for_login===true&&a.allow_manual_login===true,i=a.auto_login&&a.auto_login.username&&a.auto_login.password;try{let o=a.url||"auto";if(o==="auto"){t?.("detecting");let b=await fa(e);if(!b){let y={success:!1,error:"\u672A\u627E\u5230\u8FD0\u884C\u4E2D\u7684\u5F00\u53D1\u670D\u52A1\u5668\u3002\u8BF7\u5148\u542F\u52A8\u5F00\u53D1\u670D\u52A1\u5668\uFF08\u5982 npm run dev\uFF09",url:"",load_time:0,timestamp:Date.now(),summary:"\u9519\u8BEF\uFF1A\u672A\u627E\u5230\u5F00\u53D1\u670D\u52A1\u5668"};return t?.("error",{error:y.error}),y}o=b.url,t?.("detected",{url:o});}t?.("launching",{url:o});let l=r?!1:a.headless!==!1,c=a.use_profile!==!1;s=await ga({headless:l,useProfile:c}),t?.("loading",{url:o});let u=await s.newPage(),d=await ch(u,o);d&&t?.("headers_applied",{message:"\u5DF2\u5E94\u7528\u4FDD\u5B58\u7684\u8BA4\u8BC1 headers"}),await u.goto(o,{waitUntil:"networkidle0",timeout:3e4});let p=await ba(u,o);if(i&&p.detected){t?.("auto_login",{message:"\u68C0\u6D4B\u5230\u767B\u5F55\u9875\u9762\uFF0C\u6B63\u5728\u81EA\u52A8\u767B\u5F55..."});let b=fu(u,o),y=await uh(u,a.auto_login,t);if(!y.success)return await s.close(),{success:!1,url:o,load_time:0,timestamp:Date.now(),summary:`\u274C \u81EA\u52A8\u767B\u5F55\u5931\u8D25: ${y.error}`,login_redirect:p,needs_login:!0};let w=await ba(u,o),C=await b;if(w.detected)return await s.close(),{success:!1,url:o,load_time:0,timestamp:Date.now(),summary:"\u274C \u81EA\u52A8\u767B\u5F55\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u8D26\u53F7\u6216\u5BC6\u7801\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5",login_redirect:w,needs_login:!0};{Object.keys(C).length>0&&(ti(o,C),t?.("headers_saved",{headerCount:Object.keys(C).length})),t?.("auto_login_success",{message:"\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F"}),t?.("collecting",{url:o});let k=await Xr(u,o,{wait_time:a.wait_time,collect_console:a.collect_console,collect_errors:a.collect_errors,collect_network:a.collect_network,collect_performance:a.collect_performance,take_screenshot:a.take_screenshot,network_capture_mode:a.network_capture_mode||"cdp",network_filter:{xhr_only:a.network_xhr_only,url_pattern:a.network_url_pattern,status_filter:a.network_status_filter,include_body:a.network_include_body,body_max_length:a.network_body_max_length,max_results:a.network_max_results}}),T=Qr({console_logs:k.console_logs,errors:k.errors,network_requests:k.network_requests,network_stats:k.network_stats,performance:k.performance});return await s.close(),{success:!0,url:o,load_time:k.load_time,timestamp:Date.now(),console_logs:k.console_logs,errors:k.errors,network_requests:k.network_requests,performance:k.performance,screenshot:k.screenshot,summary:`\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F\uFF01
227
227
 
228
228
  ${T}`,login_redirect:{detected:!1,original_url:o},needs_login:!1,captured_headers:C}}}if(p.detected&&!r&&!i)return await s.close(),{success:!1,url:o,load_time:0,timestamp:Date.now(),summary:`\u26A0\uFE0F \u9875\u9762\u9700\u8981\u767B\u5F55: ${p.reason}
@@ -684,16 +684,16 @@ readfile(path="src/main.ts", range_start="// BEGIN CONFIG", range_end="// END CO
684
684
  - \u{1F525} edit_file \u524D\u5FC5\u987B\u5148 readfile(..., for_edit=true) - old_string \u987B\u4ECE\u8F93\u51FA\u7CBE\u786E\u590D\u5236
685
685
  - for_edit=true \u4F1A\u5305\u542B COPY \u533A\u5757\uFF08\u8F93\u51FA\u66F4\u5927\uFF09
686
686
  - max_output_chars \u53EF\u9650\u5236\u8F93\u51FA\u957F\u5EA6
687
- - \u652F\u6301 TypeScript/JavaScript/Python/Java \u7B49\u591A\u79CD\u8BED\u8A00`,parameters:{type:"object",properties:{path:{type:"string",description:"\u6587\u4EF6\u8DEF\u5F84 (\u5FC5\u9700)"},start_line:{type:"number",description:"\u8D77\u59CB\u884C\u53F7 (1-indexed)"},end_line:{type:"number",description:"\u7ED3\u675F\u884C\u53F7"},num_lines:{type:"number",description:`\u8BFB\u53D6\u884C\u6570 (\u9ED8\u8BA4: ${$n})`},symbol:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (\u51FD\u6570\u540D\u3001\u7C7B\u540D\u3001\u53D8\u91CF\u540D\u7B49)"},symbol_kind:{type:"string",description:"\u7B26\u53F7\u7C7B\u578B: function, class, interface, method, variable, type, enum",enum:["function","class","interface","method","variable","type","enum"]},class_name:{type:"string",description:"\u6240\u5C5E\u7C7B\u540D (\u7528\u4E8E\u5B9A\u4F4D\u7C7B\u7684\u65B9\u6CD5)"},function:{type:"string",description:"\u51FD\u6570\u540D (\u5FEB\u6377\u65B9\u5F0F\uFF0C\u7B49\u540C\u4E8E symbol + symbol_kind=function)"},class:{type:"string",description:"\u7C7B\u540D (\u5FEB\u6377\u65B9\u5F0F\uFF0C\u7B49\u540C\u4E8E symbol + symbol_kind=class)"},pattern:{type:"string",description:"\u641C\u7D22\u6A21\u5F0F (\u6B63\u5219\u8868\u8FBE\u5F0F)"},match_index:{type:"number",description:"\u5339\u914D\u7B2C\u51E0\u4E2A\u7ED3\u679C (\u9ED8\u8BA4: 1)"},list_matches:{type:"boolean",description:"\u4EC5\u5217\u51FA\u5339\u914D\u884C\u6458\u8981 (\u9ED8\u8BA4: false, \u9700\u914D\u5408 pattern)"},range_start:{type:"string",description:"\u8303\u56F4\u5F00\u59CB\u6A21\u5F0F"},range_end:{type:"string",description:"\u8303\u56F4\u7ED3\u675F\u6A21\u5F0F"},ranges:{type:"array",items:{type:"object",properties:{start:{type:"number"},end:{type:"number"}},required:["start"]},description:'\u591A\u4E2A\u884C\u8303\u56F4\u6279\u91CF\u8BFB\u53D6 (e.g., [{"start":10,"end":120},{"start":300,"end":480}])'},anchor_lines:{type:"array",items:{type:"number"},description:"\u6309\u884C\u53F7\u6279\u91CF\u8BFB\u53D6 (\u4F1A\u4EE5\u884C\u53F7\u4E3A\u4E2D\u5FC3\u5C55\u5F00 num_lines \u6216 context)"},context:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 10)"},use_index:{type:"boolean",description:"\u662F\u5426\u4F7F\u7528\u7D22\u5F15 (\u9ED8\u8BA4: true, \u5982\u679C\u7D22\u5F15\u53EF\u7528)"},for_edit:{type:"boolean",description:"\u662F\u5426\u5305\u542B edit_file \u53EF\u590D\u5236\u7684\u539F\u59CB\u5185\u5BB9\u5757 (\u9ED8\u8BA4: false)"},max_output_chars:{type:"number",description:`\u6700\u5927\u8F93\u51FA\u5B57\u7B26\u6570 (\u9ED8\u8BA4: ${Gd})`},read_all:{type:"boolean",description:"\u4E00\u6B21\u6027\u8BFB\u53D6\u6574\u4E2A\u6587\u4EF6 (\u5FFD\u7565 num_lines \u9650\u5236\uFF0C\u9002\u7528\u4E8E\u5C0F\u6587\u4EF6\u5982 SKILL.md)"}},required:["path"]},async function(l){let{path:c,start_line:u,end_line:d,num_lines:p,symbol:h,symbol_kind:g,class_name:f,function:b,class:y,pattern:w,match_index:C,list_matches:k,range_start:T,range_end:_,ranges:M,anchor_lines:F,context:x,use_index:R=true,for_edit:j,max_output_chars:v,read_all:E}=l,L=e(),I=ob(L),A=j===true,O=typeof x=="number"?Math.max(0,x):ui,$=typeof v=="number"&&v>0?Math.floor(v):Gd,P=E?Fn:p||(A?nb:$n);P=Math.min(P,Fn),!p&&w&&(P=Math.max(Pi,O*2+1));let N=Array.isArray(M)&&M.length>0,D=Array.isArray(F)&&F.length>0,G=k===true;if(A&&(N||D||G))return "\u2717 for_edit=true \u6682\u4E0D\u652F\u6301 list_matches / ranges / anchor_lines\uFF0C\u8BF7\u4F7F\u7528\u5355\u6B21 readfile \u83B7\u53D6\u53EF\u7F16\u8F91\u7247\u6BB5\u3002";let z=()=>te.isAbsolute(c)?c:te.resolve(L,c),oe=async()=>{let ee=z(),fe=await ce.readFile(ee,"utf-8"),le=Ks(fe).split(`
688
- `);return {absPath:ee,lines:le,totalLines:le.length}},ue=(ee,fe,ne)=>{let le=Math.max(1,Math.floor(ee)),Q=typeof fe=="number"?Math.floor(fe):le+P-1,Be=Math.min(ne,Math.max(Q,le));return {start:le,end:Be}},Se=ee=>{let fe=ee.filter(le=>Number.isFinite(le.start)&&Number.isFinite(le.end)).sort((le,Q)=>le.start-Q.start),ne=[];for(let le of fe){let Q=ne[ne.length-1];!Q||le.start>Q.end+1?ne.push({...le}):Q.end=Math.max(Q.end,le.end);}return ne};if(G){if(!w)return "\u2717 list_matches \u9700\u8981\u914D\u5408 pattern \u4F7F\u7528";try{let{absPath:ee,lines:fe,totalLines:ne}=await oe(),le;try{le=new RegExp(w,"gi");}catch(ae){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${ae.message}`}let Q=[];fe.forEach((ae,S)=>{le.test(ae)&&Q.push({line:S+1,text:ae}),le.lastIndex=0;});let Be=Dt(ee);if(Q.length===0){let ae=qe(fe.slice(0,Math.min(50,ne)),1);return [`\u2713 \u6587\u4EF6: ${Be}`,`\u603B\u884C\u6570: ${ne} | \u5339\u914D: 0`,"\u7B56\u7565: grep-list","",`\u672A\u627E\u5230\u5339\u914D: "${w}"`,"","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---",ae].join(`
689
- `)}let ze=il+12,B=Math.max(5,Math.min(ib,Math.floor($/ze))),re=Q.slice(0,B),V=re.map(ae=>{let S=ae.text.length>il?`${ae.text.slice(0,il)}...`:ae.text;return `${String(ae.line).padStart(6)} \u2502 ${S}`}),pe=[`\u2713 \u6587\u4EF6: ${Be}`,`\u603B\u884C\u6570: ${ne} | \u5339\u914D: ${Q.length}`,"\u7B56\u7565: grep-list","",`--- \u5339\u914D\u6458\u8981\uFF08\u524D ${V.length}/${Q.length}\uFF09---`,...V];V.length<Q.length&&pe.push("","\u26A0\uFE0F \u6458\u8981\u5DF2\u622A\u65AD\uFF0C\u8C03\u6574 max_output_chars \u6216\u7F29\u5C0F pattern");let Re=re.slice(0,5).map(ae=>ae.line).join(", ");return pe.push("",`\u{1F4A1} \u8BFB\u53D6\u5339\u914D\u9644\u8FD1: readfile(path="${Be}", anchor_lines=[${Re}], num_lines=${Math.min(200,P)})`),pe.join(`
690
- `)}catch(ee){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.message}`}}if(N||D)try{let{absPath:ee,lines:fe,totalLines:ne}=await oe(),le=[];if(N)for(let V of M)!V||typeof V.start!="number"||le.push(ue(V.start,V.end,ne));else if(D){let V=Math.max(1,p||O*2+1);for(let pe of F){if(typeof pe!="number"||Number.isNaN(pe))continue;let Re=Math.max(1,Math.floor(pe-Math.floor(V/2))),ae=Math.min(ne,Re+V-1);le.push({start:Re,end:ae});}}if(le.length===0)return "\u2717 ranges/anchor_lines \u4E3A\u7A7A\uFF0C\u65E0\u6CD5\u8BFB\u53D6";let Q=Se(le),ze=[`\u2713 \u6587\u4EF6: ${Dt(ee)}`,`\u603B\u884C\u6570: ${ne} | \u533A\u5757: ${Q.length}`,"\u7B56\u7565: batch-range","","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"],B=ze.join(`
687
+ - \u652F\u6301 TypeScript/JavaScript/Python/Java \u7B49\u591A\u79CD\u8BED\u8A00`,parameters:{type:"object",properties:{path:{type:"string",description:"\u6587\u4EF6\u8DEF\u5F84 (\u5FC5\u9700)"},start_line:{type:"number",description:"\u8D77\u59CB\u884C\u53F7 (1-indexed)"},end_line:{type:"number",description:"\u7ED3\u675F\u884C\u53F7"},num_lines:{type:"number",description:`\u8BFB\u53D6\u884C\u6570 (\u9ED8\u8BA4: ${$n})`},symbol:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (\u51FD\u6570\u540D\u3001\u7C7B\u540D\u3001\u53D8\u91CF\u540D\u7B49)"},symbol_kind:{type:"string",description:"\u7B26\u53F7\u7C7B\u578B: function, class, interface, method, variable, type, enum",enum:["function","class","interface","method","variable","type","enum"]},class_name:{type:"string",description:"\u6240\u5C5E\u7C7B\u540D (\u7528\u4E8E\u5B9A\u4F4D\u7C7B\u7684\u65B9\u6CD5)"},function:{type:"string",description:"\u51FD\u6570\u540D (\u5FEB\u6377\u65B9\u5F0F\uFF0C\u7B49\u540C\u4E8E symbol + symbol_kind=function)"},class:{type:"string",description:"\u7C7B\u540D (\u5FEB\u6377\u65B9\u5F0F\uFF0C\u7B49\u540C\u4E8E symbol + symbol_kind=class)"},pattern:{type:"string",description:"\u641C\u7D22\u6A21\u5F0F (\u6B63\u5219\u8868\u8FBE\u5F0F)"},match_index:{type:"number",description:"\u5339\u914D\u7B2C\u51E0\u4E2A\u7ED3\u679C (\u9ED8\u8BA4: 1)"},list_matches:{type:"boolean",description:"\u4EC5\u5217\u51FA\u5339\u914D\u884C\u6458\u8981 (\u9ED8\u8BA4: false, \u9700\u914D\u5408 pattern)"},range_start:{type:"string",description:"\u8303\u56F4\u5F00\u59CB\u6A21\u5F0F"},range_end:{type:"string",description:"\u8303\u56F4\u7ED3\u675F\u6A21\u5F0F"},ranges:{type:"array",items:{type:"object",properties:{start:{type:"number"},end:{type:"number"}},required:["start"]},description:'\u591A\u4E2A\u884C\u8303\u56F4\u6279\u91CF\u8BFB\u53D6 (e.g., [{"start":10,"end":120},{"start":300,"end":480}])'},anchor_lines:{type:"array",items:{type:"number"},description:"\u6309\u884C\u53F7\u6279\u91CF\u8BFB\u53D6 (\u4F1A\u4EE5\u884C\u53F7\u4E3A\u4E2D\u5FC3\u5C55\u5F00 num_lines \u6216 context)"},context:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 10)"},use_index:{type:"boolean",description:"\u662F\u5426\u4F7F\u7528\u7D22\u5F15 (\u9ED8\u8BA4: true, \u5982\u679C\u7D22\u5F15\u53EF\u7528)"},for_edit:{type:"boolean",description:"\u662F\u5426\u5305\u542B edit_file \u53EF\u590D\u5236\u7684\u539F\u59CB\u5185\u5BB9\u5757 (\u9ED8\u8BA4: false)"},max_output_chars:{type:"number",description:`\u6700\u5927\u8F93\u51FA\u5B57\u7B26\u6570 (\u9ED8\u8BA4: ${Gd})`},read_all:{type:"boolean",description:"\u4E00\u6B21\u6027\u8BFB\u53D6\u6574\u4E2A\u6587\u4EF6 (\u5FFD\u7565 num_lines \u9650\u5236\uFF0C\u9002\u7528\u4E8E\u5C0F\u6587\u4EF6\u5982 SKILL.md)"}},required:["path"]},async function(l){let{path:c,start_line:u,end_line:d,num_lines:p,symbol:h,symbol_kind:g,class_name:f,function:b,class:y,pattern:w,match_index:C,list_matches:k,range_start:T,range_end:_,ranges:M,anchor_lines:F,context:x,use_index:R=true,for_edit:j,max_output_chars:v,read_all:E}=l,P=e(),I=ob(P),A=j===true,O=typeof x=="number"?Math.max(0,x):ui,$=typeof v=="number"&&v>0?Math.floor(v):Gd,D=E?Fn:p||(A?nb:$n);D=Math.min(D,Fn),!p&&w&&(D=Math.max(Pi,O*2+1));let N=Array.isArray(M)&&M.length>0,L=Array.isArray(F)&&F.length>0,G=k===true;if(A&&(N||L||G))return "\u2717 for_edit=true \u6682\u4E0D\u652F\u6301 list_matches / ranges / anchor_lines\uFF0C\u8BF7\u4F7F\u7528\u5355\u6B21 readfile \u83B7\u53D6\u53EF\u7F16\u8F91\u7247\u6BB5\u3002";let z=()=>te.isAbsolute(c)?c:te.resolve(P,c),oe=async()=>{let ee=z(),fe=await ce.readFile(ee,"utf-8"),le=Ks(fe).split(`
688
+ `);return {absPath:ee,lines:le,totalLines:le.length}},ue=(ee,fe,ne)=>{let le=Math.max(1,Math.floor(ee)),Q=typeof fe=="number"?Math.floor(fe):le+D-1,Be=Math.min(ne,Math.max(Q,le));return {start:le,end:Be}},Se=ee=>{let fe=ee.filter(le=>Number.isFinite(le.start)&&Number.isFinite(le.end)).sort((le,Q)=>le.start-Q.start),ne=[];for(let le of fe){let Q=ne[ne.length-1];!Q||le.start>Q.end+1?ne.push({...le}):Q.end=Math.max(Q.end,le.end);}return ne};if(G){if(!w)return "\u2717 list_matches \u9700\u8981\u914D\u5408 pattern \u4F7F\u7528";try{let{absPath:ee,lines:fe,totalLines:ne}=await oe(),le;try{le=new RegExp(w,"gi");}catch(ae){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${ae.message}`}let Q=[];fe.forEach((ae,S)=>{le.test(ae)&&Q.push({line:S+1,text:ae}),le.lastIndex=0;});let Be=Dt(ee);if(Q.length===0){let ae=qe(fe.slice(0,Math.min(50,ne)),1);return [`\u2713 \u6587\u4EF6: ${Be}`,`\u603B\u884C\u6570: ${ne} | \u5339\u914D: 0`,"\u7B56\u7565: grep-list","",`\u672A\u627E\u5230\u5339\u914D: "${w}"`,"","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---",ae].join(`
689
+ `)}let ze=il+12,B=Math.max(5,Math.min(ib,Math.floor($/ze))),re=Q.slice(0,B),V=re.map(ae=>{let S=ae.text.length>il?`${ae.text.slice(0,il)}...`:ae.text;return `${String(ae.line).padStart(6)} \u2502 ${S}`}),pe=[`\u2713 \u6587\u4EF6: ${Be}`,`\u603B\u884C\u6570: ${ne} | \u5339\u914D: ${Q.length}`,"\u7B56\u7565: grep-list","",`--- \u5339\u914D\u6458\u8981\uFF08\u524D ${V.length}/${Q.length}\uFF09---`,...V];V.length<Q.length&&pe.push("","\u26A0\uFE0F \u6458\u8981\u5DF2\u622A\u65AD\uFF0C\u8C03\u6574 max_output_chars \u6216\u7F29\u5C0F pattern");let Re=re.slice(0,5).map(ae=>ae.line).join(", ");return pe.push("",`\u{1F4A1} \u8BFB\u53D6\u5339\u914D\u9644\u8FD1: readfile(path="${Be}", anchor_lines=[${Re}], num_lines=${Math.min(200,D)})`),pe.join(`
690
+ `)}catch(ee){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.message}`}}if(N||L)try{let{absPath:ee,lines:fe,totalLines:ne}=await oe(),le=[];if(N)for(let V of M)!V||typeof V.start!="number"||le.push(ue(V.start,V.end,ne));else if(L){let V=Math.max(1,p||O*2+1);for(let pe of F){if(typeof pe!="number"||Number.isNaN(pe))continue;let Re=Math.max(1,Math.floor(pe-Math.floor(V/2))),ae=Math.min(ne,Re+V-1);le.push({start:Re,end:ae});}}if(le.length===0)return "\u2717 ranges/anchor_lines \u4E3A\u7A7A\uFF0C\u65E0\u6CD5\u8BFB\u53D6";let Q=Se(le),ze=[`\u2713 \u6587\u4EF6: ${Dt(ee)}`,`\u603B\u884C\u6570: ${ne} | \u533A\u5757: ${Q.length}`,"\u7B56\u7565: batch-range","","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"],B=ze.join(`
691
691
  `).length,re=0;for(let[V,pe]of Q.entries()){let Re=qe(fe.slice(pe.start-1,pe.end),pe.start),S=`${`# \u533A\u5757 ${V+1}: ${pe.start}-${pe.end}`}
692
692
  ${Re}`;if(B+S.length+2>$&&re>0)break;ze.push(S,""),B+=S.length+2,re+=1;}return re<Q.length&&ze.push(`\u26A0\uFE0F \u8F93\u51FA\u5DF2\u622A\u65AD\uFF0C\u4EC5\u663E\u793A\u524D ${re} \u4E2A\u533A\u5757`),ze.join(`
693
693
  `).trimEnd()}catch(ee){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.message}`}let q;u?q={type:"line",start:u,end:d}:b?q={type:"function",name:b,className:f}:y?q={type:"class",name:y}:h?q={type:"symbol",name:h,kind:g}:w?q={type:"pattern",regex:w,matchIndex:C,context:O}:T&&_&&(q={type:"range",startPattern:T,endPattern:_});let J=ee=>{let ne=[`\u2713 \u6587\u4EF6: ${Dt(ee.path)}`,`\u603B\u884C\u6570: ${ee.totalLines} | \u663E\u793A: \u7B2C ${ee.startLine}-${ee.endLine} \u884C`,`\u7B56\u7565: ${ee.strategy}${ee.metadata?.matchedLine?` | \u5339\u914D\u884C: ${ee.metadata.matchedLine}`:""}`];if(ee.metadata?.symbol&&ne.push(`\u7B26\u53F7: ${ee.metadata.symbol.name} (${ee.metadata.symbol.kind})`),ee.truncated&&(ne.push(""),ne.push(`\u26A0\uFE0F \u5185\u5BB9\u5DF2\u622A\u65AD\uFF0C\u4F7F\u7528 start_line=${ee.endLine+1} \u7EE7\u7EED\u8BFB\u53D6`)),ne.push(""),ne.push("--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"),ne.push(ee.content),A){let Be=ee.content.split(`
694
694
  `).map(ze=>{let B=ze.match(/^\s*\d+\s*│\s?(.*)$/);return B?B[1]:ze}).join(`
695
695
  `);ne.push(""),ne.push("--- \u{1F525} COPY THIS FOR edit_file old_string (\u4E0D\u5E26\u884C\u53F7) ---"),ne.push(Be),ne.push("--- END ---");}return ne.join(`
696
- `)},ie=0,K="",xe=!p;for(;;){let ee=await I.read({path:c,locator:q,mode:"smart",autoFullThreshold:xe?zs:void 0,chunkSize:P,expandContext:O,useIndex:R});if(!ee.success)return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.error}
696
+ `)},ie=0,K="",xe=!p;for(;;){let ee=await I.read({path:c,locator:q,mode:"smart",autoFullThreshold:xe?zs:void 0,chunkSize:D,expandContext:O,useIndex:R});if(!ee.success)return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.error}
697
697
 
698
698
  \u{1F4A1} \u63D0\u793A:
699
699
  - \u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E
@@ -701,7 +701,7 @@ ${Re}`;if(B+S.length+2>$&&re>0)break;ze.push(S,""),B+=S.length+2,re+=1;}return r
701
701
 
702
702
  \u{1F4A1} \u5EFA\u8BAE:
703
703
  - \u4F7F\u7528 pattern/list_matches \u5B9A\u4F4D\uFF0C\u518D\u7528 anchor_lines/ranges \u6279\u91CF\u8BFB\u53D6
704
- - \u6216\u6307\u5B9A start_line/num_lines \u7CBE\u51C6\u8BFB\u53D6`),xe&&ee.strategy==="full"&&K.length>$){xe=false;let le=Math.max(.1,Math.min(.9,$/K.length));P=Math.max(Pi,Math.floor(P*le)),ie+=1;continue}if(p||K.length<=$||ie>=rb||P<=Pi)return K;let fe=Math.max(.1,Math.min(.9,$/K.length)),ne=Math.max(Pi,Math.floor(P*fe));if(ne>=P)return K;P=ne,ie+=1;}}},s={name:"build_index",description:`\u3010\u6784\u5EFA\u4EE3\u7801\u7D22\u5F15\u3011\u4E3A\u9879\u76EE\u6784\u5EFA AST \u7D22\u5F15\uFF0C\u63D0\u5347\u4EE3\u7801\u5BFC\u822A\u901F\u5EA6\u3002
704
+ - \u6216\u6307\u5B9A start_line/num_lines \u7CBE\u51C6\u8BFB\u53D6`),xe&&ee.strategy==="full"&&K.length>$){xe=false;let le=Math.max(.1,Math.min(.9,$/K.length));D=Math.max(Pi,Math.floor(D*le)),ie+=1;continue}if(p||K.length<=$||ie>=rb||D<=Pi)return K;let fe=Math.max(.1,Math.min(.9,$/K.length)),ne=Math.max(Pi,Math.floor(D*fe));if(ne>=D)return K;D=ne,ie+=1;}}},s={name:"build_index",description:`\u3010\u6784\u5EFA\u4EE3\u7801\u7D22\u5F15\u3011\u4E3A\u9879\u76EE\u6784\u5EFA AST \u7D22\u5F15\uFF0C\u63D0\u5347\u4EE3\u7801\u5BFC\u822A\u901F\u5EA6\u3002
705
705
 
706
706
  \u26A1 \u7279\u6027:
707
707
  - \u89E3\u6790 TypeScript/JavaScript/Python \u4EE3\u7801\u7ED3\u6784
@@ -765,7 +765,7 @@ get_definitions(query="User", path="src/auth") \u2192 \u9650\u5B9A\u76EE\u5F55`
765
765
  get_references(query="UserService")
766
766
  get_references(symbol="handleLogin", path="src/auth")
767
767
  get_references(query="FeatureFlag", file_pattern="*.ts")`,parameters:{type:"object",properties:{query:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (\u4F18\u5148)"},symbol:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (query \u7684\u522B\u540D)"},path:{type:"string",description:"\u641C\u7D22\u8DEF\u5F84 (\u76F8\u5BF9\u5DE5\u4F5C\u533A\uFF0C\u9ED8\u8BA4: \u5F53\u524D\u5DE5\u4F5C\u533A)"},file_pattern:{type:"string",description:'\u6587\u4EF6\u8FC7\u6EE4 (e.g., "*.ts", "*.{js,ts}")'},case_insensitive:{type:"boolean",description:"\u5FFD\u7565\u5927\u5C0F\u5199 (\u9ED8\u8BA4: false)"},regex:{type:"boolean",description:"\u5C06 query \u4F5C\u4E3A\u6B63\u5219 (\u9ED8\u8BA4: false)"},context_lines:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 2)"},max_matches:{type:"number",description:"\u6700\u5927\u5339\u914D\u6570 (\u9ED8\u8BA4: 200)"}}},permission:{category:"read",allowInAskMode:true},async function(l){let c=typeof l.query=="string"?l.query:typeof l.symbol=="string"?l.symbol:"";if(!c.trim())return "\u2717 \u7F3A\u5C11\u53C2\u6570: query (\u6216 symbol)";let u=e(),d=te.resolve(u,l.path||".");if(!Ud(u,d))return "\u2717 \u8DEF\u5F84\u4E0D\u5728 workspace \u5185";let p;try{p=await ce.stat(d);}catch{return "\u2717 \u8DEF\u5F84\u4E0D\u5B58\u5728"}let h=typeof l.context_lines=="number"&&l.context_lines>=0?Math.min(l.context_lines,10):2,g=typeof l.max_matches=="number"&&l.max_matches>0?Math.min(l.max_matches,1e3):200,f=!!l.case_insensitive,b=!!l.regex,y;try{let x=b?c:lb(c);y=new RegExp(x,f?"gi":"g");}catch(x){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${x.message}`}let w=[];if(p.isDirectory()){let x=l.file_pattern||"**/*";w=await on(x,{cwd:d,absolute:true,nodir:true,ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.next/**","**/coverage/**","**/__pycache__/**","**/target/**","**/vendor/**"]});}else w=[d];if(w.length===0)return "\u2713 \u672A\u627E\u5230\u53EF\u641C\u7D22\u7684\u6587\u4EF6";let C=[],k=0,T=0,_=0;for(let x of w){if(k>=g)break;try{let R=await ce.readFile(x,"utf-8");if(R.includes("\0"))continue;let j=R.split(`
768
- `),v=new Set,E=new Map;for(let L=0;L<j.length&&!(k>=g);L++){let I=j[L],A=y.test(I);if(y.lastIndex=0,A){v.add(L),k++;let O=Math.max(0,L-h),$=Math.min(j.length-1,L+h);for(let P=O;P<=$;P++){let N=E.get(P);E.set(P,{line:j[P],isMatch:N?.isMatch||P===L});}}}if(T++,v.size>0){_++;let I=Array.from(E.keys()).sort((A,O)=>A-O).map(A=>({lineNum:A+1,line:E.get(A)?.line||"",isMatch:E.get(A)?.isMatch||!1}));C.push({file:x,matches:I,matchCount:v.size});}}catch{continue}}let M=Dt(d),F=[`\u2713 \u5F15\u7528: "${c}"`,`\u25B8 \u8DEF\u5F84: ${M}`,l.file_pattern?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l.file_pattern}`:"",f?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",b?"\u25B8 \u6A21\u5F0F: \u6B63\u5219":"","",`\u6587\u4EF6: ${T} \u5DF2\u641C\u7D22, ${_} \u6709\u5339\u914D`,`\u5339\u914D: ${k}${k>=g?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(x=>x!=="");for(let x of C){let R=Dt(x.file);F.push(`
768
+ `),v=new Set,E=new Map;for(let P=0;P<j.length&&!(k>=g);P++){let I=j[P],A=y.test(I);if(y.lastIndex=0,A){v.add(P),k++;let O=Math.max(0,P-h),$=Math.min(j.length-1,P+h);for(let D=O;D<=$;D++){let N=E.get(D);E.set(D,{line:j[D],isMatch:N?.isMatch||D===P});}}}if(T++,v.size>0){_++;let I=Array.from(E.keys()).sort((A,O)=>A-O).map(A=>({lineNum:A+1,line:E.get(A)?.line||"",isMatch:E.get(A)?.isMatch||!1}));C.push({file:x,matches:I,matchCount:v.size});}}catch{continue}}let M=Dt(d),F=[`\u2713 \u5F15\u7528: "${c}"`,`\u25B8 \u8DEF\u5F84: ${M}`,l.file_pattern?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l.file_pattern}`:"",f?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",b?"\u25B8 \u6A21\u5F0F: \u6B63\u5219":"","",`\u6587\u4EF6: ${T} \u5DF2\u641C\u7D22, ${_} \u6709\u5339\u914D`,`\u5339\u914D: ${k}${k>=g?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(x=>x!=="");for(let x of C){let R=Dt(x.file);F.push(`
769
769
  \u25B8 ${R} (${x.matchCount} \u5904)`),F.push("\u2500".repeat(50));let j=-10;for(let v of x.matches){v.lineNum>j+1&&j>0&&F.push(" \u2504\u2504\u2504");let E=v.isMatch?"\u25B6":" ";F.push(`${E}${String(v.lineNum).padStart(5)} \u2502 ${v.line}`),j=v.lineNum;}}return C.length===0&&(F.push("\u672A\u627E\u5230\u5339\u914D\u5185\u5BB9"),F.push(""),F.push("\u{1F4A1} \u5EFA\u8BAE:"),F.push(" - \u68C0\u67E5\u5173\u952E\u8BCD\u62FC\u5199"),F.push(" - \u4F7F\u7528 regex=true \u8FDB\u884C\u66F4\u7CBE\u786E\u5339\u914D"),F.push(" - \u7F29\u5C0F\u6216\u6269\u5927 path/file_pattern \u8303\u56F4")),F.join(`
770
770
  `)}};return [t,s,n,r,i,{name:"index_stats",description:"\u3010\u7D22\u5F15\u7EDF\u8BA1\u3011\u67E5\u770B\u5F53\u524D\u9879\u76EE\u7684\u7D22\u5F15\u72B6\u6001\u548C\u7EDF\u8BA1\u4FE1\u606F\u3002",parameters:{type:"object",properties:{}},async function(){let l=e(),u=await or(l).getStats();if(!u.hasIndex)return `\u{1F4CA} \u7D22\u5F15\u72B6\u6001: \u672A\u6784\u5EFA
771
771
 
@@ -836,7 +836,7 @@ AI: [\u6280\u80FD\u6267\u884C\u7ED3\u679C]
836
836
  `,t=a.endsWith(e),s=a.split(/\r?\n/);return t&&s[s.length-1]===""&&s.pop(),{lines:s,lineEnding:e,hasTrailingNewline:t}}function sp(a){let e=a.trim(),t="";for(let s of e)switch(s){case "\u2010":case "\u2011":case "\u2012":case "\u2013":case "\u2014":case "\u2015":case "\u2212":t+="-";break;case "\u2018":case "\u2019":case "\u201A":case "\u201B":t+="'";break;case "\u201C":case "\u201D":case "\u201E":case "\u201F":t+='"';break;case "\xA0":case "\u2002":case "\u2003":case "\u2004":case "\u2005":case "\u2006":case "\u2007":case "\u2008":case "\u2009":case "\u200A":case "\u202F":case "\u205F":case "\u3000":t+=" ";break;default:t+=s;break}return t}function pl(a,e,t){if(e.length===0)return t;if(e.length>a.length)return null;let s=a.length-e.length;for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(a[n+i]!==e[i]){r=false;break}if(r)return n}for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(a[n+i].trimEnd()!==e[i].trimEnd()){r=false;break}if(r)return n}for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(a[n+i].trim()!==e[i].trim()){r=false;break}if(r)return n}for(let n=t;n<=s;n+=1){let r=true;for(let i=0;i<e.length;i+=1)if(sp(a[n+i])!==sp(e[i])){r=false;break}if(r)return n}return null}var Mb=2e5;function Pb(a,e){let t=a.length,s=e.length;if(t*s>Mb)return [...a.map(c=>({type:"delete",line:c})),...e.map(c=>({type:"insert",line:c}))];let r=Array.from({length:t+1},()=>new Array(s+1).fill(0));for(let c=t-1;c>=0;c-=1)for(let u=s-1;u>=0;u-=1)r[c][u]=a[c]===e[u]?r[c+1][u+1]+1:Math.max(r[c+1][u],r[c][u+1]);let i=[],o=0,l=0;for(;o<t&&l<s;){if(a[o]===e[l]){i.push({type:"equal",line:a[o]}),o+=1,l+=1;continue}r[o+1][l]>=r[o][l+1]?(i.push({type:"delete",line:a[o]}),o+=1):(i.push({type:"insert",line:e[l]}),l+=1);}for(;o<t;)i.push({type:"delete",line:a[o]}),o+=1;for(;l<s;)i.push({type:"insert",line:e[l]}),l+=1;return i}function Db(a,e){if(a.length===0&&e.length===0)return [];let t=Pb(a,e),s=[],n=0,r=0,i=0;for(;i<t.length;){if(t[i].type==="equal"){n+=1,r+=1,i+=1;continue}let o=n,l=[],c=[];for(;i<t.length&&t[i].type!=="equal";){let u=t[i];u.type==="delete"?(l.push(u.line),n+=1):(c.push(u.line),r+=1),i+=1;}s.push({oldStart:o,oldLines:l,newLines:c});}return s}var Lb={name:"edit_file",description:`Edit file by replacing a target block with a new block.
837
837
  Edits apply line-level hunks (only changed lines are replaced).
838
838
  Matches are robust (exact -> trim_end -> trim -> normalize) to avoid brittle edits.
839
- Use change_context to anchor a location and keep old_string minimal.`,parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to edit"},path:{type:"string",description:"Alias of file_path (fallback)"},filePath:{type:"string",description:"Alias of file_path (camelCase fallback)"},file:{type:"string",description:"Alias of file_path (short fallback)"},old_string:{type:"string",description:"Exact string to find and replace (must match exactly, including whitespace)"},old:{type:"string",description:"Alias of old_string (fallback)"},new_string:{type:"string",description:"New string to replace with"},new:{type:"string",description:"Alias of new_string (fallback)"},change_context:{type:"string",description:"Optional anchor (line or block) to locate the edit area (apply_patch-style @@ context)"},changeContext:{type:"string",description:"Alias of change_context (camelCase fallback)"},context:{type:"string",description:"Alias of change_context (fallback)"},replace_all:{type:"boolean",description:"Replace all occurrences (default: false, only first match)"},replaceAll:{type:"boolean",description:"Alias of replace_all (camelCase fallback)"}},required:["file_path","old_string","new_string"]},async function(a){let e=a.file_path||a.path||a.filePath||a.file,t=a.old_string??a.old,s=a.new_string??a.new,n=a.replace_all??a.replaceAll??false,r=a.change_context??a.changeContext??a.context,i=Ue(e);Le(i);if(!e)return JSON.stringify(X("edit_file","error","Missing required parameter: file_path",{error:"file_path (or path) is required"}));if(t==null)return JSON.stringify(X("edit_file","error","Missing required parameter: old_string",{error:"old_string is required"}));if(s==null)return JSON.stringify(X("edit_file","error","Missing required parameter: new_string",{error:"new_string is required"}));let l;try{l=await ce__default.readFile(i,"utf-8");}catch{return JSON.stringify(X("edit_file","error",`File not found: ${e}`,{file_path:i,error:"File not found",verify_hint:"Use write_file to create a new file, or check the file path."}))}try{let{lines:c,lineEnding:u,hasTrailingNewline:d}=Ib(l),p=t.split(/\r?\n/),h=s.split(/\r?\n/);if(p.length===1&&p[0]==="")return JSON.stringify(X("edit_file","error","old_string cannot be empty",{file_path:i,error:"old_string cannot be empty"}));let g=0;if(r){let v=r.split(/\r?\n/),E=pl(c,v,0);if(E===null)return JSON.stringify(X("edit_file","error",`change_context not found in ${te__default.basename(i)}`,{file_path:i,error:"change_context not found",verify_hint:`Use "readfile ${e}" to verify the context lines.`}));g=E+v.length;}let f=[],b=g;for(;b<=c.length;){let v=pl(c,p,b),E=p,L=h;if(v===null&&p.length>0&&p[p.length-1]===""){let I=p.slice(0,-1);I.length>0&&(v=pl(c,I,b),v!==null&&(E=I,L=h[h.length-1]===""?h.slice(0,-1):h));}if(v===null)break;f.push({start:v,oldLines:E,newLines:L}),b=v+E.length;}if(f.length===0)return JSON.stringify(X("edit_file","error",`Target block not found in ${te__default.basename(i)}`,{file_path:i,error:"old_string not found",verify_hint:`Use "readfile ${e}" and reduce old_string or provide change_context.`}));let y=n?f:[f[0]],w=c.slice(),C=[];for(let v of y.slice().reverse()){let E=c.slice(v.start,v.start+v.oldLines.length),L=Db(E,v.newLines);if(L.length!==0){for(let I of L)C.push({startLine:v.start+I.oldStart+1,oldLines:I.oldLines,newLines:I.newLines});for(let I of L.slice().reverse())w.splice(v.start+I.oldStart,I.oldLines.length,...I.newLines);}}d&&(w=[...w,""]);let k=w.join(u);if(k===l)return JSON.stringify(X("edit_file","already_done","No changes needed (content already matches)",{file_path:i,verify_hint:`Use "readfile ${e}" to verify the content if needed.`}));await ce__default.writeFile(i,k,"utf-8");let T=C.slice().sort((v,E)=>v.startLine-E.startLine),_=T[0],M=_?_.oldLines:[],F=_?_.newLines:[],x=_?_.startLine:1,R=w.length,j=!n&&f.length>1?`Found ${f.length} matches, only replaced the first one. Use replace_all=true to replace all.`:void 0;return JSON.stringify(X("edit_file","success",`Edited ${te__default.basename(i)}: ${y.length} replacement(s) at line ${x}`,{file_path:i,verify_hint:`Use "readfile ${e}" to verify the changes.`,metadata:{replacements:y.length,start_line:x,old_lines:M.length,new_lines:F.length,total_lines:R,warning:j,hunks:T.map(v=>({old_string:v.oldLines.join(`
839
+ Use change_context to anchor a location and keep old_string minimal.`,parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to edit"},path:{type:"string",description:"Alias of file_path (fallback)"},filePath:{type:"string",description:"Alias of file_path (camelCase fallback)"},file:{type:"string",description:"Alias of file_path (short fallback)"},old_string:{type:"string",description:"Exact string to find and replace (must match exactly, including whitespace)"},old:{type:"string",description:"Alias of old_string (fallback)"},new_string:{type:"string",description:"New string to replace with"},new:{type:"string",description:"Alias of new_string (fallback)"},change_context:{type:"string",description:"Optional anchor (line or block) to locate the edit area (apply_patch-style @@ context)"},changeContext:{type:"string",description:"Alias of change_context (camelCase fallback)"},context:{type:"string",description:"Alias of change_context (fallback)"},replace_all:{type:"boolean",description:"Replace all occurrences (default: false, only first match)"},replaceAll:{type:"boolean",description:"Alias of replace_all (camelCase fallback)"}},required:["file_path","old_string","new_string"]},async function(a){let e=a.file_path||a.path||a.filePath||a.file,t=a.old_string??a.old,s=a.new_string??a.new,n=a.replace_all??a.replaceAll??false,r=a.change_context??a.changeContext??a.context,i=Ue(e);Le(i);if(!e)return JSON.stringify(X("edit_file","error","Missing required parameter: file_path",{error:"file_path (or path) is required"}));if(t==null)return JSON.stringify(X("edit_file","error","Missing required parameter: old_string",{error:"old_string is required"}));if(s==null)return JSON.stringify(X("edit_file","error","Missing required parameter: new_string",{error:"new_string is required"}));let l;try{l=await ce__default.readFile(i,"utf-8");}catch{return JSON.stringify(X("edit_file","error",`File not found: ${e}`,{file_path:i,error:"File not found",verify_hint:"Use write_file to create a new file, or check the file path."}))}try{let{lines:c,lineEnding:u,hasTrailingNewline:d}=Ib(l),p=t.split(/\r?\n/),h=s.split(/\r?\n/);if(p.length===1&&p[0]==="")return JSON.stringify(X("edit_file","error","old_string cannot be empty",{file_path:i,error:"old_string cannot be empty"}));let g=0;if(r){let v=r.split(/\r?\n/),E=pl(c,v,0);if(E===null)return JSON.stringify(X("edit_file","error",`change_context not found in ${te__default.basename(i)}`,{file_path:i,error:"change_context not found",verify_hint:`Use "readfile ${e}" to verify the context lines.`}));g=E+v.length;}let f=[],b=g;for(;b<=c.length;){let v=pl(c,p,b),E=p,P=h;if(v===null&&p.length>0&&p[p.length-1]===""){let I=p.slice(0,-1);I.length>0&&(v=pl(c,I,b),v!==null&&(E=I,P=h[h.length-1]===""?h.slice(0,-1):h));}if(v===null)break;f.push({start:v,oldLines:E,newLines:P}),b=v+E.length;}if(f.length===0)return JSON.stringify(X("edit_file","error",`Target block not found in ${te__default.basename(i)}`,{file_path:i,error:"old_string not found",verify_hint:`Use "readfile ${e}" and reduce old_string or provide change_context.`}));let y=n?f:[f[0]],w=c.slice(),C=[];for(let v of y.slice().reverse()){let E=c.slice(v.start,v.start+v.oldLines.length),P=Db(E,v.newLines);if(P.length!==0){for(let I of P)C.push({startLine:v.start+I.oldStart+1,oldLines:I.oldLines,newLines:I.newLines});for(let I of P.slice().reverse())w.splice(v.start+I.oldStart,I.oldLines.length,...I.newLines);}}d&&(w=[...w,""]);let k=w.join(u);if(k===l)return JSON.stringify(X("edit_file","already_done","No changes needed (content already matches)",{file_path:i,verify_hint:`Use "readfile ${e}" to verify the content if needed.`}));await ce__default.writeFile(i,k,"utf-8");let T=C.slice().sort((v,E)=>v.startLine-E.startLine),_=T[0],M=_?_.oldLines:[],F=_?_.newLines:[],x=_?_.startLine:1,R=w.length,j=!n&&f.length>1?`Found ${f.length} matches, only replaced the first one. Use replace_all=true to replace all.`:void 0;return JSON.stringify(X("edit_file","success",`Edited ${te__default.basename(i)}: ${y.length} replacement(s) at line ${x}`,{file_path:i,verify_hint:`Use "readfile ${e}" to verify the changes.`,metadata:{replacements:y.length,start_line:x,old_lines:M.length,new_lines:F.length,total_lines:R,warning:j,hunks:T.map(v=>({old_string:v.oldLines.join(`
840
840
  `),new_string:v.newLines.join(`
841
841
  `),start_line:v.startLine,old_line_count:v.oldLines.length,new_line_count:v.newLines.length})),edit_info:{old_string:M.join(`
842
842
  `),new_string:F.join(`
@@ -1024,16 +1024,16 @@ search(mode="files", pattern="*.ts") \u2192 \u6587\u4EF6\u540D\u641C\u7D22
1024
1024
  \u8F93\u51FA\u7279\u70B9:
1025
1025
  - \u6BCF\u6761\u7ED3\u679C\u5E26 [\u6A21\u5757] \u524D\u7F00
1026
1026
  - \u663E\u793A\u6A21\u5757\u5206\u5E03\u7EDF\u8BA1
1027
- - \u63D0\u4F9B readfile \u6279\u91CF\u8BFB\u53D6\u63D0\u793A`,parameters:{type:"object",properties:{pattern:{type:"string",description:'\u641C\u7D22\u6A21\u5F0F (\u9ED8\u8BA4\u6B63\u5219)\u3002\u793A\u4F8B: "error", "\u767B\u5F55", "function\\s+\\w+"'},query:{type:"string",description:"pattern \u7684\u522B\u540D"},keywords:{type:"array",items:{type:"string"},description:"\u591A\u5173\u952E\u8BCD OR \u641C\u7D22 (\u5B57\u9762\u91CF\u5339\u914D)"},queries:{type:"array",items:{type:"object",properties:{pattern:{type:"string"},op:{type:"string",enum:["and","or","not"]},regex:{type:"boolean"},case_insensitive:{type:"boolean"}},required:["pattern"]},description:"\u9AD8\u7EA7\u591A\u67E5\u8BE2 (\u652F\u6301 and/or/not)"},op:{type:"string",enum:["and","or","not"],description:"pattern \u7684\u903B\u8F91\u64CD\u4F5C (\u9ED8\u8BA4 or)"},mode:{type:"string",enum:["content","files"],description:"\u641C\u7D22\u6A21\u5F0F: \u5185\u5BB9\u641C\u7D22\u6216\u6587\u4EF6\u540D\u641C\u7D22 (\u9ED8\u8BA4: content)"},path:{type:"string",description:"\u641C\u7D22\u8DEF\u5F84 (\u53EF\u9009\uFF0C\u9ED8\u8BA4: \u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55)"},recursive:{type:"boolean",description:"\u9012\u5F52\u5B50\u76EE\u5F55 (\u53EF\u9009\uFF0C\u76EE\u5F55\u9ED8\u8BA4 true\uFF0C\u6587\u4EF6\u9ED8\u8BA4 false)"},file_pattern:{type:"string",description:'\u6587\u4EF6\u7C7B\u578B\u8FC7\u6EE4 (e.g., "*.ts", "*.{js,jsx,ts,tsx}")'},include_hidden:{type:"boolean",description:"\u5305\u542B\u9690\u85CF\u6587\u4EF6 (\u9ED8\u8BA4: false)"},case_insensitive:{type:"boolean",description:"\u5FFD\u7565\u5927\u5C0F\u5199 (\u9ED8\u8BA4: true)"},context_lines:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 2)"},max_matches:{type:"number",description:"\u6700\u5927\u5339\u914D\u6570 (\u9ED8\u8BA4: 200)"},count_only:{type:"boolean",description:"\u4EC5\u8FD4\u56DE\u8BA1\u6570 (\u5FEB\u901F\u4E86\u89E3\u5339\u914D\u5206\u5E03)"}}},async function({pattern:a,query:e,keywords:t,queries:s,op:n,mode:r="content",path:i,recursive:o,file_pattern:l,include_hidden:c=false,case_insensitive:u=true,context_lines:d=2,max_matches:p=200,count_only:h=false},g){try{let f=Date.now();we.debug("SEARCH",`>>> searchTool.execute START, pattern=${a||e||t?.join(",")}`);let b=g?.signal,y=()=>{if(b?.aborted){let B=new Error("Operation cancelled");throw B.name="AbortError",B}},w=200,C=async()=>{await new Promise(B=>setImmediate(B));},T=Ue(i||"."),_="workspace",M=st();if(i&&te__default.isAbsolute(i))_="absolute";else if(i&&!Me__default.existsSync(T)){let B=M,re=null;for(;;){let V=te__default.resolve(B,i);if(Me__default.existsSync(V)){re=V;break}let pe=te__default.dirname(B);if(pe===B)break;B=pe;}re&&(T=re,_="ancestor");}let F=Le(T);y();let x;try{x=await ce__default.stat(T);}catch(B){return JSON.stringify(ve("search","error",`search failed: ${B.message}`,void 0,{error:B.message}))}let R=x.isDirectory(),j=o!==void 0?o:R,v=nv({pattern:a,query:e,keywords:t,queries:s,op:n,case_insensitive:u});if(y(),v.length===0)return JSON.stringify(ve("search","error","search failed: no query provided",void 0,{error:"Provide pattern/keywords/queries"}));let E=v.filter(B=>B.op!=="not"),L=v.filter(B=>B.op==="and"),I=v.filter(B=>B.op==="or"),A=v.filter(B=>B.op==="not");if(E.length===0)return JSON.stringify(ve("search","error","search failed: only NOT queries provided",void 0,{error:"At least one non-NOT query is required"}));let O=v.filter(B=>B.regex).map(B=>{try{return new RegExp(B.pattern),null}catch(re){return `${B.pattern}: ${re.message}`}}).filter(B=>!!B);if(O.length>0)return JSON.stringify(ve("search","error",`search failed: invalid regex (${O[0]})`,void 0,{error:`Invalid regex: ${O.join("; ")}`}));let $=[];I.length>0&&$.push(I.map(B=>B.pattern).join(" OR ")),L.length>0&&$.push(`AND ${L.map(B=>B.pattern).join(" + ")}`),A.length>0&&$.push(`NOT ${A.map(B=>B.pattern).join(" + ")}`);let P=$.join(" ");we.debug("SEARCH",`>>> Before isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let N=await sv();we.debug("SEARCH",`<<< After isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let D=Math.min(200,Math.max(80,d*4+40));if(we.info("SEARCH",`Strategy: ${N?"ripgrep":"fallback"}`),!N)return JSON.stringify(ve("search","error","search failed: ripgrep not available",`Ripgrep is required for search. This is unexpected since ripgrep should be bundled.
1027
+ - \u63D0\u4F9B readfile \u6279\u91CF\u8BFB\u53D6\u63D0\u793A`,parameters:{type:"object",properties:{pattern:{type:"string",description:'\u641C\u7D22\u6A21\u5F0F (\u9ED8\u8BA4\u6B63\u5219)\u3002\u793A\u4F8B: "error", "\u767B\u5F55", "function\\s+\\w+"'},query:{type:"string",description:"pattern \u7684\u522B\u540D"},keywords:{type:"array",items:{type:"string"},description:"\u591A\u5173\u952E\u8BCD OR \u641C\u7D22 (\u5B57\u9762\u91CF\u5339\u914D)"},queries:{type:"array",items:{type:"object",properties:{pattern:{type:"string"},op:{type:"string",enum:["and","or","not"]},regex:{type:"boolean"},case_insensitive:{type:"boolean"}},required:["pattern"]},description:"\u9AD8\u7EA7\u591A\u67E5\u8BE2 (\u652F\u6301 and/or/not)"},op:{type:"string",enum:["and","or","not"],description:"pattern \u7684\u903B\u8F91\u64CD\u4F5C (\u9ED8\u8BA4 or)"},mode:{type:"string",enum:["content","files"],description:"\u641C\u7D22\u6A21\u5F0F: \u5185\u5BB9\u641C\u7D22\u6216\u6587\u4EF6\u540D\u641C\u7D22 (\u9ED8\u8BA4: content)"},path:{type:"string",description:"\u641C\u7D22\u8DEF\u5F84 (\u53EF\u9009\uFF0C\u9ED8\u8BA4: \u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55)"},recursive:{type:"boolean",description:"\u9012\u5F52\u5B50\u76EE\u5F55 (\u53EF\u9009\uFF0C\u76EE\u5F55\u9ED8\u8BA4 true\uFF0C\u6587\u4EF6\u9ED8\u8BA4 false)"},file_pattern:{type:"string",description:'\u6587\u4EF6\u7C7B\u578B\u8FC7\u6EE4 (e.g., "*.ts", "*.{js,jsx,ts,tsx}")'},include_hidden:{type:"boolean",description:"\u5305\u542B\u9690\u85CF\u6587\u4EF6 (\u9ED8\u8BA4: false)"},case_insensitive:{type:"boolean",description:"\u5FFD\u7565\u5927\u5C0F\u5199 (\u9ED8\u8BA4: true)"},context_lines:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 2)"},max_matches:{type:"number",description:"\u6700\u5927\u5339\u914D\u6570 (\u9ED8\u8BA4: 200)"},count_only:{type:"boolean",description:"\u4EC5\u8FD4\u56DE\u8BA1\u6570 (\u5FEB\u901F\u4E86\u89E3\u5339\u914D\u5206\u5E03)"}}},async function({pattern:a,query:e,keywords:t,queries:s,op:n,mode:r="content",path:i,recursive:o,file_pattern:l,include_hidden:c=false,case_insensitive:u=true,context_lines:d=2,max_matches:p=200,count_only:h=false},g){try{let f=Date.now();we.debug("SEARCH",`>>> searchTool.execute START, pattern=${a||e||t?.join(",")}`);let b=g?.signal,y=()=>{if(b?.aborted){let B=new Error("Operation cancelled");throw B.name="AbortError",B}},w=200,C=async()=>{await new Promise(B=>setImmediate(B));},T=Ue(i||"."),_="workspace",M=st();if(i&&te__default.isAbsolute(i))_="absolute";else if(i&&!Me__default.existsSync(T)){let B=M,re=null;for(;;){let V=te__default.resolve(B,i);if(Me__default.existsSync(V)){re=V;break}let pe=te__default.dirname(B);if(pe===B)break;B=pe;}re&&(T=re,_="ancestor");}let F=Le(T);y();let x;try{x=await ce__default.stat(T);}catch(B){return JSON.stringify(ve("search","error",`search failed: ${B.message}`,void 0,{error:B.message}))}let R=x.isDirectory(),j=o!==void 0?o:R,v=nv({pattern:a,query:e,keywords:t,queries:s,op:n,case_insensitive:u});if(y(),v.length===0)return JSON.stringify(ve("search","error","search failed: no query provided",void 0,{error:"Provide pattern/keywords/queries"}));let E=v.filter(B=>B.op!=="not"),P=v.filter(B=>B.op==="and"),I=v.filter(B=>B.op==="or"),A=v.filter(B=>B.op==="not");if(E.length===0)return JSON.stringify(ve("search","error","search failed: only NOT queries provided",void 0,{error:"At least one non-NOT query is required"}));let O=v.filter(B=>B.regex).map(B=>{try{return new RegExp(B.pattern),null}catch(re){return `${B.pattern}: ${re.message}`}}).filter(B=>!!B);if(O.length>0)return JSON.stringify(ve("search","error",`search failed: invalid regex (${O[0]})`,void 0,{error:`Invalid regex: ${O.join("; ")}`}));let $=[];I.length>0&&$.push(I.map(B=>B.pattern).join(" OR ")),P.length>0&&$.push(`AND ${P.map(B=>B.pattern).join(" + ")}`),A.length>0&&$.push(`NOT ${A.map(B=>B.pattern).join(" + ")}`);let D=$.join(" ");we.debug("SEARCH",`>>> Before isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let N=await sv();we.debug("SEARCH",`<<< After isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let L=Math.min(200,Math.max(80,d*4+40));if(we.info("SEARCH",`Strategy: ${N?"ripgrep":"fallback"}`),!N)return JSON.stringify(ve("search","error","search failed: ripgrep not available",`Ripgrep is required for search. This is unexpected since ripgrep should be bundled.
1028
1028
  Please report this issue.`,{error:"ripgrep not available"}));if(y(),r==="files"){let B=await(async()=>{if(!R)return [Le(T)];if(N){let H=await gl();if(!H)throw new Error("ripgrep not available (this should not happen)");let se=["--files"];c&&se.push("--hidden"),!j&&R&&se.push("--max-depth","1"),l&&se.push("-g",l),ml.forEach(de=>se.push("-g",de)),se.push("--",T);let be=await We(H,se,st(),{signal:b});if(be.exitCode!==0&&be.exitCode!==1)throw new Error(be.stderr||"rg files search failed");return be.stdout.split(`
1029
- `).filter(Boolean).map(de=>{let Ae=te__default.isAbsolute(de)?te__default.resolve(de):te__default.resolve(st(),de);return Le(Ae)})}let S=l||"**/*",U=j?S:S.replace("**/","");return (await ip(U,{cwd:T,absolute:!0,dot:c,onlyFiles:!0,ignore:ml.map(H=>H.replace("!",""))})).map(H=>Le(H))})();y();let re=v.map(S=>{let U=S.regex?S.pattern:Qd(S.pattern),Z=S.caseInsensitive?"i":"";return {query:S,regex:new RegExp(U,Z)}}),V=[],pe=0;for(let S of B){y();let U=S,Z=re.map(Y=>({op:Y.query.op,hit:Y.regex.test(U)})),H=Z.some(Y=>Y.op==="or"&&Y.hit),se=Z.filter(Y=>Y.op==="and").every(Y=>Y.hit);!Z.some(Y=>Y.op==="not"&&Y.hit)&&(L.length===0||se)&&(I.length===0||H)&&V.push(S),pe++,pe%w===0&&await C();}let Re=[`\u2713 \u6587\u4EF6\u641C\u7D22: ${P}`,`\u25B8 \u8DEF\u5F84: ${F}${j?" (\u9012\u5F52)":""}${_==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",c?"\u25B8 \u5305\u542B\u9690\u85CF\u6587\u4EF6":"","",`\u627E\u5230 ${V.length} \u4E2A\u6587\u4EF6`,""].filter(S=>S!==""),ae=50;return V.slice(0,ae).forEach(S=>Re.push(` ${S}`)),V.length>ae&&Re.push(` ... \u8FD8\u6709 ${V.length-ae} \u4E2A\u6587\u4EF6`),JSON.stringify(ve("search","success",V.length>0?`search files "${P}" (${V.length} files)`:`search files "${P}" (no matches)`,Re.join(`
1029
+ `).filter(Boolean).map(de=>{let Ae=te__default.isAbsolute(de)?te__default.resolve(de):te__default.resolve(st(),de);return Le(Ae)})}let S=l||"**/*",U=j?S:S.replace("**/","");return (await ip(U,{cwd:T,absolute:!0,dot:c,onlyFiles:!0,ignore:ml.map(H=>H.replace("!",""))})).map(H=>Le(H))})();y();let re=v.map(S=>{let U=S.regex?S.pattern:Qd(S.pattern),Z=S.caseInsensitive?"i":"";return {query:S,regex:new RegExp(U,Z)}}),V=[],pe=0;for(let S of B){y();let U=S,Z=re.map(Y=>({op:Y.query.op,hit:Y.regex.test(U)})),H=Z.some(Y=>Y.op==="or"&&Y.hit),se=Z.filter(Y=>Y.op==="and").every(Y=>Y.hit);!Z.some(Y=>Y.op==="not"&&Y.hit)&&(P.length===0||se)&&(I.length===0||H)&&V.push(S),pe++,pe%w===0&&await C();}let Re=[`\u2713 \u6587\u4EF6\u641C\u7D22: ${D}`,`\u25B8 \u8DEF\u5F84: ${F}${j?" (\u9012\u5F52)":""}${_==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",c?"\u25B8 \u5305\u542B\u9690\u85CF\u6587\u4EF6":"","",`\u627E\u5230 ${V.length} \u4E2A\u6587\u4EF6`,""].filter(S=>S!==""),ae=50;return V.slice(0,ae).forEach(S=>Re.push(` ${S}`)),V.length>ae&&Re.push(` ... \u8FD8\u6709 ${V.length-ae} \u4E2A\u6587\u4EF6`),JSON.stringify(ve("search","success",V.length>0?`search files "${D}" (${V.length} files)`:`search files "${D}" (no matches)`,Re.join(`
1030
1030
  `),{metadata:{mode:"files",strategy:N?"rg":"glob",regex:v.some(S=>S.regex),case_insensitive:u,path:F,resolved_from:_,files:V,queries:v}}))}let G=new Map,z=new Map,oe=0,ue=A.map(B=>{let re=B.regex?B.pattern:Qd(B.pattern),V=B.caseInsensitive?"i":"";return new RegExp(re,V)}),Se=[];if(N){let B=await gl();if(!B)throw new Error("ripgrep not available (this should not happen)");for(let re of E){y();let V=["--json","--with-filename","--line-number","--column","-a"];V.push("-C",String(d)),re.caseInsensitive&&V.push("-i"),re.regex||V.push("-F"),c&&V.push("--hidden"),!j&&R&&V.push("--max-depth","1"),l&&V.push("-g",l),ml.forEach(H=>V.push("-g",H)),V.push("--",re.pattern,T);let pe=B,Re="",ae=0,S="",U=async H=>{let se=`${H} ${V.join(" ")}`;return Se.push(se),We(H,V,st(),{signal:b})};try{let H=await U(pe);Re=H.stdout,S=H.stderr||"",ae=H.exitCode;}catch(H){if(H?.name==="AbortError"||b?.aborted)throw H;S=H?.message||H?.stderr||String(H),ae=H?.exitCode||2;}if(ae!==0&&ae!==1&&pe!=="rg"&&tv(ae,S)){we.warn("SEARCH","Bundled ripgrep failed, retrying with system rg",{exitCode:ae,error:S,bundledPath:pe});try{let H=await U("rg");Re=H.stdout,S=H.stderr||"",ae=H.exitCode,pe="rg",(ae===0||ae===1)&&(ns="rg");}catch(H){if(H?.name==="AbortError"||b?.aborted)throw H;let se=H?.message||H?.stderr||String(H);S=`${S}
1031
1031
  Fallback rg failed: ${se}`.trim(),ae=H?.exitCode||2;}}if(ae!==0&&ae!==1){let H=S?`
1032
1032
  Error: ${S}`:"",se=`
1033
1033
  Command: ${pe} ${V.join(" ")}`;throw new Error(`ripgrep failed (exit code ${ae})${H}${se}`)}let Z=0;for(let H of Re.split(`
1034
- `)){if(y(),Z++,Z%w===0&&await C(),!H.trim())continue;let se;try{se=JSON.parse(H);}catch{continue}if(se.type==="summary"){let Os=se.data?.stats;Os&&typeof Os.searches=="number"&&(oe=Math.max(oe,Os.searches));continue}let be=se.type==="match",Y=se.type==="context";if(!be&&!Y)continue;let de=se.data,Ae=de?.path?.text,et=de?.line_number,An=de?.lines?.text,gs=Array.isArray(de?.submatches)?de.submatches[0]:void 0;if(!Ae||!et||typeof An!="string")continue;let Bc=An.replace(/\n$/,""),Ko=G.get(Ae)||new Map,En=Ko.get(et)||{line:Bc,queryIds:new Set};if(En.line=Bc,be){En.queryIds.add(re.id),En.column===void 0&&gs?.start!==void 0&&(En.column=gs.start+1);let Os=z.get(Ae)||new Set;Os.add(re.id),z.set(Ae,Os);}Ko.set(et,En),G.set(Ae,Ko);}}}let q=new Set(L.map(B=>B.id)),J=[],ie=0,K=0,xe=0,ee=[],fe=[],ne=0;for(let[B,re]of G.entries()){if(y(),ie>=p&&!h)break;ne++,ne%w===0&&await C();let V=z.get(B)||new Set,pe=!0;if(q.forEach(H=>{V.has(H)||(pe=!1);}),!pe)continue;let ae=Array.from(re.keys()).sort((H,se)=>H-se).filter(H=>{let se=re.get(H);return se?!ue.some(be=>be.test(se.line)):!1});if(ae.length===0)continue;K++,ie+=ae.length;let S=Le(B);if(ee.push({file:S,anchor_lines:ae.slice(0,20),num_lines:D}),h){J.push({file:B,matches:[],matchCount:ae.length});continue}y();let U=[];Array.from(re.keys()).sort((H,se)=>H-se).forEach(H=>{let se=re.get(H);if(!se)return;let be=ae.includes(H);if(U.push({lineNum:H,line:se.line,isMatch:be}),be&&fe.length<p){for(let Y of se.queryIds)if(fe.push({file:S,line:H,column:se.column,preview:se.line,queryId:Y}),fe.length>=p)break}}),J.push({file:B,matches:U,matchCount:ae.length});}J.sort((B,re)=>Le(B.file).localeCompare(Le(re.file)));let le=B=>{let V=Le(B).split(te__default.sep),pe=V.findIndex(Re=>["src","lib","app","core","packages"].includes(Re));return pe>=0&&pe+1<V.length?V[pe+1]:V[0]||"root"},Q=[`\u2713 \u641C\u7D22: ${P}`,`\u25B8 \u8DEF\u5F84: ${F}${j?" (\u9012\u5F52)":""}${_==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",u?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",N?"\u25B8 \u7B56\u7565: ripgrep":"\u25B8 \u7B56\u7565: fallback","","\u2501\u2501\u2501\u2501 \u7ED3\u679C\u6458\u8981 \u2501\u2501\u2501\u2501",oe>0?`\u6587\u4EF6: ${oe} \u5DF2\u641C\u7D22, ${K} \u6709\u5339\u914D`:`\u6587\u4EF6: ${K} \u6709\u5339\u914D`,`\u5339\u914D: ${ie}${ie>=p?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(B=>B!==""),Be=new Map,ze=0;for(let B of J){ze++,ze%w===0&&await C();let re=le(B.file);Be.set(re,(Be.get(re)||0)+B.matchCount);}if(Be.size>1){Q.push(""),Q.push("\u{1F4E6} \u6A21\u5757\u5206\u5E03:");let B=Array.from(Be.entries()).sort((re,V)=>V[1]-re[1]);for(let[re,V]of B.slice(0,5))Q.push(` ${re}: ${V}`);B.length>5&&Q.push(` ... \u8FD8\u6709 ${B.length-5} \u4E2A\u6A21\u5757`);}if(Q.push(""),h){Q.push("\u{1F4CB} \u6587\u4EF6\u5217\u8868:");let B=0;for(let re of J){B++,B%w===0&&await C();let V=Le(re.file),pe=le(re.file);Q.push(` [${pe}] ${V}: ${re.matchCount}`);}}else {let B=0,re=100;for(let V of J){if(y(),xe>=p){Q.push(`
1034
+ `)){if(y(),Z++,Z%w===0&&await C(),!H.trim())continue;let se;try{se=JSON.parse(H);}catch{continue}if(se.type==="summary"){let Os=se.data?.stats;Os&&typeof Os.searches=="number"&&(oe=Math.max(oe,Os.searches));continue}let be=se.type==="match",Y=se.type==="context";if(!be&&!Y)continue;let de=se.data,Ae=de?.path?.text,et=de?.line_number,An=de?.lines?.text,gs=Array.isArray(de?.submatches)?de.submatches[0]:void 0;if(!Ae||!et||typeof An!="string")continue;let Bc=An.replace(/\n$/,""),Ko=G.get(Ae)||new Map,En=Ko.get(et)||{line:Bc,queryIds:new Set};if(En.line=Bc,be){En.queryIds.add(re.id),En.column===void 0&&gs?.start!==void 0&&(En.column=gs.start+1);let Os=z.get(Ae)||new Set;Os.add(re.id),z.set(Ae,Os);}Ko.set(et,En),G.set(Ae,Ko);}}}let q=new Set(P.map(B=>B.id)),J=[],ie=0,K=0,xe=0,ee=[],fe=[],ne=0;for(let[B,re]of G.entries()){if(y(),ie>=p&&!h)break;ne++,ne%w===0&&await C();let V=z.get(B)||new Set,pe=!0;if(q.forEach(H=>{V.has(H)||(pe=!1);}),!pe)continue;let ae=Array.from(re.keys()).sort((H,se)=>H-se).filter(H=>{let se=re.get(H);return se?!ue.some(be=>be.test(se.line)):!1});if(ae.length===0)continue;K++,ie+=ae.length;let S=Le(B);if(ee.push({file:S,anchor_lines:ae.slice(0,20),num_lines:L}),h){J.push({file:B,matches:[],matchCount:ae.length});continue}y();let U=[];Array.from(re.keys()).sort((H,se)=>H-se).forEach(H=>{let se=re.get(H);if(!se)return;let be=ae.includes(H);if(U.push({lineNum:H,line:se.line,isMatch:be}),be&&fe.length<p){for(let Y of se.queryIds)if(fe.push({file:S,line:H,column:se.column,preview:se.line,queryId:Y}),fe.length>=p)break}}),J.push({file:B,matches:U,matchCount:ae.length});}J.sort((B,re)=>Le(B.file).localeCompare(Le(re.file)));let le=B=>{let V=Le(B).split(te__default.sep),pe=V.findIndex(Re=>["src","lib","app","core","packages"].includes(Re));return pe>=0&&pe+1<V.length?V[pe+1]:V[0]||"root"},Q=[`\u2713 \u641C\u7D22: ${D}`,`\u25B8 \u8DEF\u5F84: ${F}${j?" (\u9012\u5F52)":""}${_==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",u?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",N?"\u25B8 \u7B56\u7565: ripgrep":"\u25B8 \u7B56\u7565: fallback","","\u2501\u2501\u2501\u2501 \u7ED3\u679C\u6458\u8981 \u2501\u2501\u2501\u2501",oe>0?`\u6587\u4EF6: ${oe} \u5DF2\u641C\u7D22, ${K} \u6709\u5339\u914D`:`\u6587\u4EF6: ${K} \u6709\u5339\u914D`,`\u5339\u914D: ${ie}${ie>=p?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(B=>B!==""),Be=new Map,ze=0;for(let B of J){ze++,ze%w===0&&await C();let re=le(B.file);Be.set(re,(Be.get(re)||0)+B.matchCount);}if(Be.size>1){Q.push(""),Q.push("\u{1F4E6} \u6A21\u5757\u5206\u5E03:");let B=Array.from(Be.entries()).sort((re,V)=>V[1]-re[1]);for(let[re,V]of B.slice(0,5))Q.push(` ${re}: ${V}`);B.length>5&&Q.push(` ... \u8FD8\u6709 ${B.length-5} \u4E2A\u6A21\u5757`);}if(Q.push(""),h){Q.push("\u{1F4CB} \u6587\u4EF6\u5217\u8868:");let B=0;for(let re of J){B++,B%w===0&&await C();let V=Le(re.file),pe=le(re.file);Q.push(` [${pe}] ${V}: ${re.matchCount}`);}}else {let B=0,re=100;for(let V of J){if(y(),xe>=p){Q.push(`
1035
1035
  ... \u8FD8\u6709\u66F4\u591A\u5339\u914D (\u5DF2\u8FBE ${p} \u4E0A\u9650)`);break}let pe=Le(V.file),Re=le(V.file);Q.push(`
1036
- \u25B8 [${Re}] ${pe} (${V.matchCount} \u5904)`),Q.push("\u2500".repeat(50));let ae=-10;for(let S of V.matches){if(xe>=p)break;B++,B%re===0&&await C(),S.lineNum>ae+1&&ae>0&&Q.push(" \u2504\u2504\u2504");let U=S.isMatch?"\u25B6":" ";Q.push(`${U}${String(S.lineNum).padStart(5)} \u2502 ${S.line}`),ae=S.lineNum,S.isMatch&&xe++;}}}return J.length===0?(Q.push("\u672A\u627E\u5230\u5339\u914D\u5185\u5BB9"),Q.push(""),Q.push("\u{1F4A1} \u5EFA\u8BAE:"),Q.push(" - \u5C1D\u8BD5 case_insensitive: true"),Q.push(" - \u5C1D\u8BD5 recursive: true \u641C\u7D22\u5B50\u76EE\u5F55"),Q.push(" - \u4F7F\u7528 keywords \u6216 queries \u7EC4\u5408\u641C\u7D22"),Q.push(' - \u67E5\u6587\u4EF6\u540D\u8BF7\u7528 mode="files"')):ee.length>0&&(Q.push(""),Q.push("\u{1F4A1} \u6279\u91CF\u8BFB\u53D6:"),ee.slice(0,3).forEach(B=>{Q.push(` readfile(path="${B.file}", anchor_lines=[${B.anchor_lines.join(",")}], num_lines=${B.num_lines})`);})),JSON.stringify(ve("search","success",J.length>0?`search "${P}" (${ie} matches)`:`search "${P}" (no matches)`,Q.join(`
1036
+ \u25B8 [${Re}] ${pe} (${V.matchCount} \u5904)`),Q.push("\u2500".repeat(50));let ae=-10;for(let S of V.matches){if(xe>=p)break;B++,B%re===0&&await C(),S.lineNum>ae+1&&ae>0&&Q.push(" \u2504\u2504\u2504");let U=S.isMatch?"\u25B6":" ";Q.push(`${U}${String(S.lineNum).padStart(5)} \u2502 ${S.line}`),ae=S.lineNum,S.isMatch&&xe++;}}}return J.length===0?(Q.push("\u672A\u627E\u5230\u5339\u914D\u5185\u5BB9"),Q.push(""),Q.push("\u{1F4A1} \u5EFA\u8BAE:"),Q.push(" - \u5C1D\u8BD5 case_insensitive: true"),Q.push(" - \u5C1D\u8BD5 recursive: true \u641C\u7D22\u5B50\u76EE\u5F55"),Q.push(" - \u4F7F\u7528 keywords \u6216 queries \u7EC4\u5408\u641C\u7D22"),Q.push(' - \u67E5\u6587\u4EF6\u540D\u8BF7\u7528 mode="files"')):ee.length>0&&(Q.push(""),Q.push("\u{1F4A1} \u6279\u91CF\u8BFB\u53D6:"),ee.slice(0,3).forEach(B=>{Q.push(` readfile(path="${B.file}", anchor_lines=[${B.anchor_lines.join(",")}], num_lines=${B.num_lines})`);})),JSON.stringify(ve("search","success",J.length>0?`search "${D}" (${ie} matches)`:`search "${D}" (no matches)`,Q.join(`
1037
1037
  `),{metadata:{mode:"content",strategy:N?"rg":"fallback",regex:v.some(B=>B.regex),case_insensitive:u,path:F,resolved_from:_,queries:v,matches:fe,read_hints:ee,files_with_matches:K,command:Se.length>0?Se[0]:void 0}}))}catch(f){return JSON.stringify(ve("search","error",`search failed: ${f.message}`,void 0,{error:f.message}))}}},iv={name:Oi.name,description:Oi.description,parameters:Oi.parameters,permission:{category:"read",allowInAskMode:true},async function(a){return zd(a)}},ov={name:"use_skill",description:`Execute a registered skill to get specialized instructions for a task.
1038
1038
 
1039
1039
  Skills are pre-defined instruction sets for common tasks like:
@@ -1484,9 +1484,9 @@ Available operations: All tools (auto-approved).`}shouldAutoApprove(){return tr
1484
1484
 
1485
1485
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1486
1486
 
1487
- `;return l+d+c}var Vi=class{llmProvider;providerName;model;tools;memory;config;agentName;agentDescription;instructions;contextInjection;userData;plannerMode;inputGuardrails=[];outputGuardrails=[];toolInputGuardrails=[];toolOutputGuardrails=[];structuredOutput;structuredValidator;maxInputTokensOverride;maxInputTokens;minHistoryMessages;parallelExecutor;unifiedCompressor;compressionMode;toolMetricsHistory=[];workspacePath;disableSystemPrompt;enableFGTS;runContext;permissionManager;modeStrategy;currentMode;loopDetector;enablePlanMode;constructor(e){if(this.llmProvider=e.llmProvider,this.providerName=e.providerName,this.model=e.model,this.tools=e.tools,this.memory=e.memory,this.config=e.config,this.agentName=e.agentName||"DefaultAgent",this.agentDescription=e.agentDescription||"",this.instructions=e.instructions,this.contextInjection=e.contextInjection,this.userData=e.userData,this.plannerMode=e.plannerMode??false,this.structuredOutput=e.structuredOutput,this.maxInputTokensOverride=e.maxInputTokensOverride,this.maxInputTokens=this.computeMaxInputTokens(e.contextWindow,e.tailTokenBudget,this.maxInputTokensOverride),this.minHistoryMessages=Math.max(1,e.minHistoryMessages??6),e.structuredOutput&&(this.structuredValidator=new Wi(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new qi,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new zi({debug:process.env.CLI_DEBUG==="1",minRecentMessages:this.minHistoryMessages,enableLLMCompression:true}),this.disableSystemPrompt=e.disableSystemPrompt??false,this.enableFGTS=e.enableFGTS??false,this.unifiedCompressor.setLLMProvider(this.llmProvider,this.model),e.contextWindow&&this.unifiedCompressor.setContextWindow(e.contextWindow),this.currentMode=e.config.mode??"agent",this.modeStrategy=_l(this.currentMode),this.permissionManager=e.permissionManager??new ls({defaultPermission:"ask"}),this.loopDetector=Ep(),this.enablePlanMode=e.enablePlanMode??true,e.approvalHandler){let t=e.approvalHandler;this.permissionManager.setApprovalHandler(async s=>({approved:await t({id:"",name:s.toolName,args:s.args}),remember:false}));}}setApprovalHandler(e){if(!e){this.permissionManager.setApprovalHandler(void 0);return}this.permissionManager.setApprovalHandler(async t=>({approved:await e({id:"",name:t.toolName,args:t.args}),remember:false}));}setMode(e){this.currentMode=e,this.modeStrategy=_l(e),m.info("Runner",`Mode switched to: ${e}`);}getMode(){return this.currentMode}getPermissionManager(){return this.permissionManager}computeMaxInputTokens(e,t,s){if(s&&s>0)return s;let r=e&&e>0?e:19e4,i=.7,o=Math.floor(r*i),l=Math.min(t??Ip,Math.floor(r*.1)),c=Math.max(2e3,o-l);if(process.env.CLI_DEBUG==="1"||process.env.CLI_DEBUG_CONSOLE==="1"){let u=`[Context] maxInputTokens=${c} (contextWindow=${r}, override=${s}, tailBudget=${t??Ip}, safety=${i})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Bv){for await(let i of e)yield i;return}let s=e[Symbol.asyncIterator](),n=t?new Promise((i,o)=>{t.aborted?o(Ki()):t.addEventListener("abort",()=>o(Ki()),{once:true});}):null,r=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw Ki()}let i=r?jv:Fv,o=null,l=new Promise((c,u)=>{o=setTimeout(()=>{u($v(r?"idle":"first_chunk",i));},i);});try{let c=await Promise.race(n?[s.next(),l,n]:[s.next(),l]);if(o&&clearTimeout(o),c.done)return;r=!0,yield c.value;}catch(c){if(o&&clearTimeout(o),s.return)try{await s.return();}catch{}throw c?.code==="STREAM_TIMEOUT"&&m.warn("RUNNER",`[watchdog] ${c.message}`),c}}}async applyContextWindow(e=0){if(!this.maxInputTokens)return null;let t=this.memory.getMessagesForLLM(),s=await this.unifiedCompressor.compressHistory(t,this.maxInputTokens,{iteration:e,enableLLMCompression:true});if(s.stats.droppedMessages>0||s.stats.llmCompressedMessages>0){this.memory.setMessages(s.messages);let n=this.compressionMode==="async"?"Async":"Sync",r=(s.originalTokens/1e3).toFixed(1),i=(s.compressedTokens/1e3).toFixed(1),o=(s.savedTokens/1e3).toFixed(1),l=s.originalCount,c=s.compressedCount;m.info("Context",`[${n}] \u538B\u7F29\u5B8C\u6210: ${l}\u6761/${r}K \u2192 ${c}\u6761/${i}K (\u8282\u7701 ${o}K, \u4E22\u5F03${s.stats.droppedMessages}\u6761, LLM\u538B\u7F29${s.stats.llmCompressedMessages}\u6761)`),s.debugInfo&&s.debugInfo.forEach(u=>m.debug("Context",u));}return s}setCompressionMode(e){this.compressionMode=e,m.info("Context",`Compression mode set to: ${e}`);}getCompressionMode(){return this.compressionMode}async getInstructions(e){if(typeof this.instructions=="string")return this.instructions;let t={name:this.agentName,description:this.agentDescription};return await this.instructions(e,t)}async getContextInjection(e){if(!this.contextInjection)return null;let s=(typeof this.contextInjection=="string"?this.contextInjection:await this.contextInjection(e,{name:this.agentName,description:this.agentDescription}))?.trim();return s||null}shouldIncludeLastRun(e){let t=e.trim().toLowerCase();return t?/上次|之前|前面|上一步|上轮|继续|回顾|resume|continue|previous|last time/.test(t):false}createRunContext(e,t=0){return {task:e,timestamp:Date.now(),currentTime:new Date,iteration:t,userData:this.userData,systemStatus:void 0}}setUserData(e){this.userData={...this.userData,...e};}async*run(e,t,s){this.runContext={task:e,timestamp:Date.now(),currentTime:new Date,iteration:0,userData:this.userData},this.loopDetector.reset(),process.env.CLI_DEBUG==="1"&&(m.debug("MK",` hasSignal: ${!!s}`),m.debug("RUNNER","========================================"),m.debug("RUNNER","=== runner.run ENTRY ==="),m.debug("RUNNER",` task: "${e?.substring(0,50)}..."`),m.debug("RUNNER",` hasImages: ${!!t&&t.length>0}`),m.debug("RUNNER",` hasSignal: ${!!s}`)),ge.agentStart(e),yield {type:"agent_updated_stream_event",new_agent:{name:this.agentName}};let n=this.createRunContext(e,0),r=this.memory.hasConversationMessages?.()??this.memory.getMessagesForLLM().some(I=>I.role==="user"||I.role==="assistant"),i=!r||this.shouldIncludeLastRun(e);n.userData={...n.userData??{},hasConversation:r,includeLastRun:i},this.inputGuardrails.length>0&&(yield {type:"raw_response_event",data:{type:"input_guardrails.check_start",count:this.inputGuardrails.length},event_type:"input_guardrails.check_start"},await Rs.runInputGuardrails(this.inputGuardrails,n,this.agentName,e),yield {type:"raw_response_event",data:{type:"input_guardrails.check_passed"},event_type:"input_guardrails.check_passed"});let o=await this.getInstructions(n),l=await this.getContextInjection(n);process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] dynamicInstructions length:",o?.length||0),console.log("[RUNNER] dynamicInstructions START:",o?.substring(0,200)),console.log("[RUNNER] dynamicInstructions END:",o?.substring(o.length-500)),console.log("[RUNNER] contains \u534F\u4F5C\u6A21\u5F0F:",o?.includes("\u534F\u4F5C\u6A21\u5F0F")),console.log("[RUNNER] contains delegate_task:",o?.includes("delegate_task")));let c=this.memory.getMessagesForLLM(),u=c.some(I=>I.role==="system");if(process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] hasSystemPrompt:",u,"existingMessages count:",c.length),console.log("[RUNNER] disableSystemPrompt:",this.disableSystemPrompt)),this.disableSystemPrompt)u&&this.memory.clear(),o&&this.memory.add({role:"system",content:o});else if(!u){let I=this.modeStrategy.getSystemPrompt();this.memory.add({role:"system",content:I}),this.memory.add({role:"system",content:o}),this.structuredValidator&&this.memory.add({role:"system",content:this.structuredValidator.buildSystemPrompt()});try{let A=await al(this.workspacePath);A&&this.memory.add({role:"system",content:A});}catch{}}if(l?this.memory.upsertSystemTagged?this.memory.upsertSystemTagged("context_injection",l):u||this.memory.add({role:"system",content:l}):this.memory.removeSystemTagged?.("context_injection"),t&&t.length>0){let I=[{type:"text",text:e},...t.map(A=>({type:"image_url",image_url:{url:A,detail:"auto"}}))];this.memory.add({role:"user",content:I});}else this.memory.add({role:"user",content:e});let d=Date.now(),p=0,h="",g=0,f={totalTokens:0,promptTokens:0,completionTokens:0},b=false,y=0,w=null,C=new Map,k=0,T=0,_=[],M=this.isExecutionOrientedTask(e),F=0,x=Kt.streamMaxRetries,R=false,j=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:gp,v=j===0||j===1/0,E=Mp(this.config.maxToolCalls,hp),L=Mp(this.config.maxRuntimeMs,fp);for(;v||p<j;){if(s?.aborted){w="interrupted",b=true,yield {type:"error",error:"Task interrupted by user."};break}if(L!==null&&Date.now()-d>=L){w="runtime_limit",b=true,yield {type:"error",error:`Reached max runtime (${nt(L)}). Please summarize progress and ask whether to continue.`};break}if(E!==null&&g>=E){w="tool_call_limit",b=true,yield {type:"error",error:`Reached max tool calls (${E}). Please summarize progress and ask whether to continue.`};break}p++;let I=null;if(this.maxInputTokens){let O=tt(this.memory.getMessagesForLLM()),$=this.maxInputTokens*.97;O>$&&(I=await this.applyContextWindow(p));}I&&(I.stats.droppedMessages>0||I.stats.llmCompressedMessages>0)&&(yield {type:"context_compaction",status:"completed",originalMessages:I.originalCount,keptMessages:I.messages.length,droppedMessages:I.stats.droppedMessages,compressedMessages:I.stats.llmCompressedMessages,originalTokens:I.originalTokens,finalTokens:I.compressedTokens,budgetTokens:this.maxInputTokens||0,useLLM:I.stats.llmCompressedMessages>0,timestamp:Date.now()});let A=this.memory.checkContextHealth();if((A.warnings.length>0||A.shouldCleanup)&&(yield {type:"raw_response_event",data:{type:"context_health",totalTokens:A.totalTokens,toolResultTokens:A.toolResultTokens,toolResultRatio:A.toolResultRatio,messageCount:A.messageCount,toolMessageCount:A.toolMessageCount,warnings:A.warnings,shouldCompress:A.shouldCompress,shouldCleanup:A.shouldCleanup,byType:A.byType},event_type:"context_health"},A.shouldCleanup&&A.byType.ephemeral.count>5)){let O=this.memory.cleanupEphemeral();O>0&&m.info("Runner",`Cleaned ${O} ephemeral messages`);}m.debug("Runner",this.memory.getTokenSummary()),ge.agentIteration(p,"thinking"),yield {type:"iteration_start",iteration:p};try{yield {type:"raw_response_event",data:{type:"response.created",response:{id:`resp_${Date.now()}`,model:this.model}},event_type:"response.created"};let O=this.memory.getMessagesForLLM();if(m.info("LLM",`Request: model=${this.model}, messages=${O.length}, tools=${this.tools.length}`),m.debug("LLM","Request messages",{messageCount:O.length,lastMessage:O[O.length-1]?.content?.toString().substring(0,200)}),process.env.CLI_DEBUG==="1"){let q=O.filter(J=>J.role==="system");console.log("[RUNNER] System messages count:",q.length);for(let J=0;J<q.length;J++){let ie=q[J].content,K=typeof ie=="string"?ie:JSON.stringify(ie);console.log(`[RUNNER] System[${J}] length:`,K?.length||0),console.log(`[RUNNER] System[${J}] contains \u534F\u4F5C\u6A21\u5F0F:`,K?.includes("\u534F\u4F5C\u6A21\u5F0F")||!1),console.log(`[RUNNER] System[${J}] contains delegate_task:`,K?.includes("delegate_task")||!1),console.log(`[RUNNER] System[${J}] preview:`,K?.substring(0,300)||"");}}let $=this.modeStrategy.filterTools(this.tools);process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`Mode: ${this.currentMode}, Available tools: ${$.length}/${this.tools.length}`);let P=this.llmProvider.chatStreamed(this.memory.getMessagesForLLM(),{model:this.model,tools:$,temperature:this.config.temperature,structuredOutput:this.structuredOutput,maxInputTokens:this.maxInputTokens,disableSystemPrompt:this.disableSystemPrompt,enableFGTS:this.enableFGTS,signal:s}),N="",D="",G=[],z=[],oe="",ue={prompt_tokens:0,completion_tokens:0,total_tokens:0};for await(let q of this.withStreamWatchdog(P,s)){if(q.type==="stream_retry"){R=!0,yield q;continue}if(q.type==="stream_recovered"){yield {type:"stream_recovered",attempt:q.attempt,maxRetries:q.maxRetries};continue}yield {type:"raw_response_event",data:q,event_type:q.choices?.[0]?.delta?"response.delta":"response.chunk"};let J=q.choices?.[0]?.delta;if(q.usage){ue={prompt_tokens:q.usage.prompt_tokens||ue.prompt_tokens,completion_tokens:q.usage.completion_tokens||ue.completion_tokens,total_tokens:q.usage.total_tokens||ue.total_tokens,cached_tokens:q.usage.cached_tokens,cache_read_input_tokens:q.usage.cache_read_input_tokens,cache_creation_input_tokens:q.usage.cache_creation_input_tokens,prompt_tokens_details:q.usage.prompt_tokens_details},f={promptTokens:ue.prompt_tokens,completionTokens:ue.completion_tokens,totalTokens:ue.total_tokens};let ie=!!q.choices?.[0]?.finish_reason;yield {type:"token_usage",usage:ue,is_final:ie};}if(J){if(J.reasoning_content&&(D+=J.reasoning_content,yield {type:"reasoning_delta",delta:J.reasoning_content}),J.reasoning_complete&&(yield {type:"reasoning_complete"}),J.content&&(N+=J.content,h=N,yield {type:"text_delta",delta:J.content}),J.tool_calls)for(let ie of J.tool_calls){let K=ie.index;z[K]||(z[K]={id:ie.id||`call_${Math.floor(Date.now())}_${K}`,type:"function",function:{name:"",arguments:""}}),ie.id&&(z[K].id=ie.id),ie.function?.name&&(z[K].function.name=ie.function.name),ie.function?.arguments&&(z[K].function.arguments+=ie.function.arguments,yield {type:"tool_call_delta",id:z[K].id,name:z[K].function.name,arguments_delta:ie.function.arguments}),ie.thoughtSignature&&(z[K].thoughtSignature=ie.thoughtSignature);}q.choices?.[0]?.finish_reason&&(oe=q.choices[0].finish_reason),q.thinking_blocks&&Array.isArray(q.thinking_blocks)&&(G=q.thinking_blocks.map(ie=>({type:ie.type,thinking:ie.thinking,signature:ie.signature,data:ie.data})));}}N&&(yield {type:"text_done"}),process.env.CLI_DEBUG_CONSOLE==="1"&&process.env.NEOX_UI_MODE==="1"&&console.log("[Runner] \u{1F3AF} Emitting response.completed event (after LLM response)"),yield {type:"raw_response_event",data:{type:"response.completed"},event_type:"response.completed"};let Se={role:"assistant",content:(N||"").trimEnd()};if(D&&(Se.reasoning_content=D),G.length>0&&(Se.thinking_blocks=G),z.length>0&&(Se.tool_calls=z.map(q=>({...q,function:{...q.function,arguments:q.function.arguments}}))),this.memory.add(Se),process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Stream ended. toolCalls.length=${z.length}, fullContent.length=${N.length}`),z.length>0){let q=/\[omitted\s+\w+:\s*\d+\s*lines?,\s*\d+\s*chars?\]/i;for(let S of z){let U=S.function.arguments||"";if(q.test(U)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${S.function.name}`),console.error(`[Runner] Arguments preview: ${U.substring(0,500)}`),yield {type:"raw_response_event",data:{type:"error.placeholder_detected",message:"Model generated placeholder string instead of actual content. This usually happens when the model sees truncated data in conversation history.",tool:S.function.name},event_type:"error.placeholder_detected"},yield {type:"error",error:'Error: Model attempted to write placeholder text ("[omitted ...]") instead of actual content. This happens when conversation history contains truncated data. Please start a new conversation.'},b=!0;break}}if(b)break;if(E!==null&&g+z.length>E){w="tool_call_limit",b=!0,yield {type:"error",error:`Tool call budget exceeded (max ${E}, requested ${z.length}). Please summarize progress and ask whether to continue.`};break}if(z.length>1){let S=z.map(Z=>Z.function.name),U=[...new Set(S)];U.length===1&&S.length>1?m.info("RUNNER",`\u{1F504} Parallel calls: ${S.length}x ${U[0]} (different parameters)`):m.info("RUNNER",`\u{1F504} Parallel calls: ${S.join(", ")}`);}let J=new Map;for(let S of z)J.set(S.id,fn(S.function.arguments));for(let S of z){g++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:S.id,name:S.function.name,arguments:S.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:S.id,name:S.function.name};let Z=J.get(S.id),H=Z?.ok??!1;H?Z?.repaired&&m.warn("RUNNER","Tool arguments repaired from non-standard JSON",{tool:S.function.name,callId:S.id}):ge.toolError(S.function.name,`Invalid JSON arguments (${Z?.reason||"parse failed"}): ${S.function.arguments.substring(0,200)}...`),yield {type:"tool_call_done",id:S.id,name:S.function.name,arguments:S.function.arguments,success:H},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:S.id,name:S.function.name,arguments:S.function.arguments},event_type:"response.function_call_arguments.done"};}let ie=new Set,K=null,xe=z.length>1;process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`Processing ${z.length} tool call(s)`,{isParallel:xe,tools:z.map(S=>S.function.name)});for(let S of z){let U=J.get(S.id);if(!U?.ok){let de=`Invalid JSON arguments for tool "${S.function.name}": ${U?.reason||"parse failed"}. Return strict JSON object arguments.`;yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:de,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:de,success:!1},this.memory.addToolResult(S.id,S.function.name,de),this.loopDetector.updateLastStatus("error"),ie.add(S.id);continue}let Z=U.args,H=this.loopDetector.detect(S.function.name,Z);if(this.loopDetector.record(S.function.name,Z),H===0)continue;let se=this.loopDetector.generateIntervention(H,S.function.name,Z);if(this.memory.add({role:"system",content:se.message}),H===2&&nu(S.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:se.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:se.message,success:!1},this.memory.addToolResult(S.id,S.function.name,se.message),this.loopDetector.updateLastStatus("error"),ie.add(S.id),se.shouldTerminate){K=se;break}}if(K&&(yield {type:"error",error:K.message},b=!0),b)break;let ee=ie.size>0?z.filter(S=>!ie.has(S.id)):z,fe=new Set(this.modeStrategy.filterTools(this.tools).map(S=>S.name)),ne=S=>S.replace(/["\s/>]+$/g,"").trim(),le=[];for(let S of ee){let U=ne(S.function.name);if(fe.has(U)||fe.has(S.function.name)){le.push(S);continue}let Z=`Tool "${S.function.name}" is not allowed in ${this.currentMode} mode`;ge.toolError(S.function.name,Z),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:Z,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:Z,success:!1},this.memory.addToolResult(S.id,S.function.name,Z),m.info("PERMISSION",`Tool blocked by mode: ${S.function.name} - ${Z}`);}if(le.length===0)continue;let Q=le.map(S=>({id:S.id,type:"function",function:{name:S.function.name,arguments:(()=>{let U=J.get(S.id);return U?.ok?JSON.stringify(U.args):S.function.arguments})()}})),Be=!1;if(process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Before permission check. shouldAutoApprove=${this.modeStrategy.shouldAutoApprove()}, parallelToolCalls=${Q.length}`),!this.modeStrategy.shouldAutoApprove()){let S=new Set;try{for(let U of le)try{let Z=J.get(U.id);if(!Z?.ok)continue;let H=Z.args,se=this.tools.find(Y=>Y.name===U.function.name);if(!se){m.warn("RUNNER",`Tool not found: ${U.function.name}`);continue}let be=await Pp(s,async()=>this.permissionManager.checkPermission(se,H));if(!be.allowed){S.add(U.id);let Y=be.reason||`Tool "${U.function.name}" was denied`;ge.toolError(U.function.name,Y),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:U.id,name:U.function.name,output:Y,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:U.id,name:U.function.name,output:Y,success:!1};let Ae=JSON.stringify({type:"ephemeral",status:"error",tool:U.function.name,summary:"Tool execution denied by user",error:Y,final:!0});this.memory.addToolResult(U.id,U.function.name,Ae),m.info("PERMISSION",`Tool denied: ${U.function.name} - ${Y}`),Be=!0;}}catch(Z){if(Z?.name==="AbortError"||Z?.code==="ERR_CANCELED")throw Z;ge.toolError(U.function.name,Z?.message||"permission check failed");}}catch(U){if(U?.name==="AbortError"||U?.code==="ERR_CANCELED"){m.info("RUNNER","Interrupt detected during permission check"),b=!0;break}throw U}if(le=le.filter(U=>!S.has(U.id)),Q=Q.filter(U=>!S.has(U.id)),Be){m.info("RUNNER","User denied tool - terminating current turn");break}if(Q.length===0)continue}if(process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} After permission check. parallelToolCalls=${Q.length}, userDeniedTool=${Be}`),this.toolInputGuardrails.length>0){let S=new Set;try{for(let U of le)try{let Z=J.get(U.id);if(!Z?.ok)continue;let H=Z.args,se={tool_name:U.function.name,tool_input:H,tool_call_id:U.id},be=this.tools.find(de=>de.name===U.function.name);if(!be)continue;this.runContext.iteration=p;let Y=await Pp(s,async()=>Rs.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:se,agent_name:this.agentName,tool:be}));if(!Y.should_execute){S.add(U.id);let de=Y.rejection_message||`Tool ${U.function.name} was blocked by guardrail`;ge.toolError(U.function.name,`Blocked by guardrail: ${de}`),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:U.id,name:U.function.name,output:de,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:U.id,name:U.function.name,output:de,success:!1},this.memory.addToolResult(U.id,U.function.name,de),bl(this.runContext,U.function.name,H,!1);}}catch(Z){if(Z?.name==="AbortError"||Z?.code==="ERR_CANCELED")throw Z;if(Z instanceof yt){ge.toolError(U.function.name,`Guardrail tripwire triggered: ${Z.message}`),yield {type:"error",error:`Guardrail tripwire triggered for ${U.function.name}: ${Z.message}`},b=!0;break}ge.toolError(U.function.name,`Guardrail check failed: ${Z?.message}`);}}catch(U){if(U?.name==="AbortError"||U?.code==="ERR_CANCELED"){m.info("RUNNER","Interrupt detected during guardrails check"),b=!0;break}throw U}if(b)break;if(le=le.filter(U=>!S.has(U.id)),Q=Q.filter(U=>!S.has(U.id)),Q.length===0)continue}process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${Q.length}`);let ze=await this.parallelExecutor.execute(Q,this.tools,S=>{if(ge.toolCall(S.name,{}),S.success){let Z=typeof S.output=="string"?S.output.length:JSON.stringify(S.output).length;ge.toolResult(S.name,!0,Z,S.executionTime||0);}else ge.toolError(S.name,S.output);let U={type:"tool_call_output_item",id:S.id,name:S.name,output:S.output,success:S.success,timestamp:Date.now()};},s),B=0,re=0,V=0,pe=!1;for(let S of ze.results){if(this.toolMetricsHistory.push({name:S.name,duration:S.executionTime||0,success:S.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.name,output:S.output,success:S.success,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.name,output:S.output,success:S.success},(S.name==="update_plan"||S.name==="call_tool")&&S.success)try{m.info("PLAN_UPDATE","\u{1F525} Detected plan-related tool call",{resultId:S.id,toolName:S.name,toolCallsCount:z.length});let Y=z.find(de=>de.id===S.id);if(Y){m.info("PLAN_UPDATE","\u{1F525} Found original call",{callId:Y.id,argsLength:Y.function.arguments?.length});let de=fn(Y.function.arguments||"{}");if(!de.ok)throw new Error(de.reason||"Invalid update_plan arguments");let Ae=de.args,et=null;if(S.name==="update_plan"?et=Ae:S.name==="call_tool"&&Ae?.name==="update_plan"&&(et=Ae.args),!et||!Array.isArray(et.plan))m.debug("PLAN_UPDATE","Skip non-update_plan call_tool",{resultId:S.id,toolName:S.name,callToolName:Ae?.name});else {let An=!0;if(typeof S.output=="string")try{let gs=JSON.parse(S.output);gs&&typeof gs=="object"&&"success"in gs&&(An=gs.success!==!1);}catch{}An?(m.info("PLAN_UPDATE","\u{1F525} Parsed plan args",{hasExplanation:!!et.explanation,planSteps:et.plan?.length}),yield {type:"plan_update",explanation:et.explanation,plan:et.plan,timestamp:Date.now()},m.info("PLAN_UPDATE","\u2705 Emitted plan_update event")):m.warn("PLAN_UPDATE","Skip failed update_plan output",{resultId:S.id});}}else m.warn("PLAN_UPDATE","\u274C Could not find original tool call",{resultId:S.id,availableIds:z.map(de=>de.id)});}catch(Y){m.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:Y});}let Z=typeof S.output=="string"?Dp(S.output):Dp(JSON.stringify(S.output));Z=this.enrichToolResult(Z,S.name,S.executionTime||0);let H=z.find(Y=>Y.id===S.id),se={};if(H){let Y=fn(H.function.arguments||"{}");Y.ok&&(se=Y.args);}if(this.toolOutputGuardrails.length>0)try{let Y=this.tools.find(de=>de.name===S.name);if(Y){let de={tool_name:S.name,tool_input:se,tool_call_id:S.id},Ae=await Rs.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:de,agent_name:this.agentName,tool:Y,output:S.output});Ae.should_use_output||(Z=Ae.replacement_message||"[Output blocked by guardrail]",ge.toolError(S.name,"Output blocked by guardrail"));}}catch(Y){Y instanceof yt&&ge.toolError(S.name,`Output guardrail tripwire triggered: ${Y.message}`);}if(!S.success&&typeof S.output=="string"){let Y=S.output.toLowerCase();if(Y.includes("operation cancelled")||Y.includes("command interrupted")||Y.includes("request aborted")){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Detected cancellation in tool output, breaking loop"),m.info("RUNNER","\u68C0\u6D4B\u5230\u5DE5\u5177\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u6267\u884C\u5FAA\u73AF"),b=!0;break}}bl(this.runContext,S.name,se,S.success),m.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${S.name}`,{toolName:S.name,success:S.success,rawLength:typeof S.output=="string"?S.output.length:JSON.stringify(S.output).length,truncatedLength:Z.length,outputPreview:Z.substring(0,500)}),this.memory.addToolResult(S.id,S.name,Z);let be=S.success?"success":"error";try{let Y=typeof S.output=="string"?S.output:JSON.stringify(S.output),de=JSON.parse(Y);de.status==="already_done"?be="already_done":de.status==="success"?be="success":de.status==="error"&&(be="error");}catch{}if(this.loopDetector.updateLastStatus(be),_.push({iteration:p,name:S.name,status:be,executionTime:S.executionTime||0}),_.length>24&&_.shift(),be==="error"?re++:be==="already_done"?(V++,this.isVerificationTool(S.name)&&(pe=!0)):(B++,this.isVerificationTool(S.name)&&(pe=!0)),be==="error"){let Y=(C.get(S.name)||0)+1;if(C.set(S.name,Y),S.name==="edit_file"&&(Y===2||Y===3)){let de=typeof S.output=="string"?S.output:JSON.stringify(S.output),Ae=S.name,et=Ap(Ae,de);this.memory.add({role:"system",content:et});}}else C.set(S.name,0);}if(p>0&&p%5===0){let S=this.buildPerformanceHint();S&&(this.memory.add({role:"system",content:S}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",S));}let Re=B+V>0;if(k=re>0&&!Re?k+1:0,process.env.CLI_DEBUG==="1"&&m.debug("LOOP_GATE","Iteration quality",{iteration:p,executionTask:M,success:B,alreadyDone:V,error:re,lowProgressStreak:k,verificationSuccess:pe}),M&&k>=2&&(this.memory.add({role:"system",content:this.buildLowProgressReplanPrompt(k)}),T++,k=0,yield {type:"raw_response_event",data:{type:"loop.progress_gate",iteration:p,reason:"low_progress",nudgeCount:T},event_type:"loop.progress_gate"}),process.env.CLI_DEBUG_CONSOLE==="1"&&ze.stats&&(yield {type:"raw_response_event",data:{type:"parallel_execution.stats",stats:ze.stats},event_type:"parallel_execution.stats"}),s?.aborted){b=!0;break}continue}else {if(this.plannerMode&&y<2&&this.shouldAutoContinuePlan(N)){y++;let J=this.buildPlanFollowupPrompt();yield {type:"raw_response_event",data:{type:"plan.auto_continue",plan_text:N,followup_prompt:J,count:y},event_type:"plan.auto_continue"},this.memory.add({role:"user",content:J});continue}if(N&&(yield {type:"run_item_stream_event",name:"message_output_created",item:{type:"message_output_item",content:N,role:"assistant",timestamp:Date.now()}}),process.env.CLI_DEBUG==="1"&&(m.info("RUNNER","=== Loop Exit: No Tool Calls ==="),m.info("RUNNER",`Finish Reason: ${oe}`),m.info("RUNNER",`Content Length: ${N.length}`),m.info("RUNNER",`Content Preview: ${N.slice(0,300)}`),m.info("RUNNER",`Tool Calls Count: ${z.length}`),m.info("RUNNER",`Iteration: ${p}`)),this.structuredValidator){let J=this.structuredValidator.validate(N);if(J.ok)h=J.normalized||N,yield {type:"raw_response_event",data:{type:"structured_output.accepted",schema:this.structuredOutput?.name,normalized_text:h,parsed:J.parsed},event_type:"structured_output.accepted"};else {yield {type:"raw_response_event",data:{type:"structured_output.retry",schema:this.structuredOutput?.name,reason:J.reason,message:J.message,errors:J.errors},event_type:"structured_output.retry"},this.memory.add({role:"system",content:this.structuredValidator.buildRetryPrompt(J)}),h="";continue}}else h=N;this.outputGuardrails.length>0&&h&&(yield {type:"raw_response_event",data:{type:"output_guardrails.check_start",count:this.outputGuardrails.length},event_type:"output_guardrails.check_start"},await Rs.runOutputGuardrails(this.outputGuardrails,n,this.agentName,h),yield {type:"raw_response_event",data:{type:"output_guardrails.check_passed"},event_type:"output_guardrails.check_passed"});let q=this.evaluateCompletionEvidence(M,g,_);if(!q.ok){T++,this.memory.add({role:"system",content:this.buildEvidenceRequiredPrompt(q.reason)}),process.env.CLI_DEBUG==="1"&&m.debug("LOOP_GATE","Completion blocked: missing evidence",{iteration:p,reason:q.reason,nudgeCount:T}),yield {type:"raw_response_event",data:{type:"loop.completion_gate",iteration:p,reason:q.reason,nudgeCount:T},event_type:"loop.completion_gate"};continue}break}}catch(O){if(O?.type==="stream_retry"){R=true,yield O;continue}let $=O instanceof Ce?O:ft(O);if(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Error classified:",{category:$.category,code:$.code,retryable:$.retryable,message:$.message}),$.category==="canceled"){w="interrupted",b=true,yield {type:"error",error:"Task interrupted by user."};break}if($.retryable&&F<x&&!R){F++;let G=hr($.category,F,$.retryAfter),z=$.category==="retryable_rate_limit",oe=$.code==="STREAM_TIMEOUT",ue=$.category==="retryable_network"||$.category==="retryable_stream";m.warn("RUNNER",`Retrying after ${nt(G)} (attempt ${F}/${x}): ${$.message}`),yield {type:"raw_response_event",data:{type:"runner.stream_retry",error:$.message,errorCode:$.code,attempt:F,maxRetries:x,delayMs:G,isRateLimit:z,isStreamTimeout:oe,isNetworkError:ue},event_type:"runner.stream_retry"},await gn(G),p--;continue}let P=Gi($),N=$.message;P&&!N.includes(P)&&(N=`${N}
1487
+ `;return l+d+c}var Vi=class{llmProvider;providerName;model;tools;memory;config;agentName;agentDescription;instructions;contextInjection;userData;plannerMode;inputGuardrails=[];outputGuardrails=[];toolInputGuardrails=[];toolOutputGuardrails=[];structuredOutput;structuredValidator;maxInputTokensOverride;maxInputTokens;minHistoryMessages;parallelExecutor;unifiedCompressor;compressionMode;toolMetricsHistory=[];workspacePath;disableSystemPrompt;enableFGTS;runContext;permissionManager;modeStrategy;currentMode;loopDetector;enablePlanMode;constructor(e){if(this.llmProvider=e.llmProvider,this.providerName=e.providerName,this.model=e.model,this.tools=e.tools,this.memory=e.memory,this.config=e.config,this.agentName=e.agentName||"DefaultAgent",this.agentDescription=e.agentDescription||"",this.instructions=e.instructions,this.contextInjection=e.contextInjection,this.userData=e.userData,this.plannerMode=e.plannerMode??false,this.structuredOutput=e.structuredOutput,this.maxInputTokensOverride=e.maxInputTokensOverride,this.maxInputTokens=this.computeMaxInputTokens(e.contextWindow,e.tailTokenBudget,this.maxInputTokensOverride),this.minHistoryMessages=Math.max(1,e.minHistoryMessages??6),e.structuredOutput&&(this.structuredValidator=new Wi(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new qi,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new zi({debug:process.env.CLI_DEBUG==="1",minRecentMessages:this.minHistoryMessages,enableLLMCompression:true}),this.disableSystemPrompt=e.disableSystemPrompt??false,this.enableFGTS=e.enableFGTS??false,this.unifiedCompressor.setLLMProvider(this.llmProvider,this.model),e.contextWindow&&this.unifiedCompressor.setContextWindow(e.contextWindow),this.currentMode=e.config.mode??"agent",this.modeStrategy=_l(this.currentMode),this.permissionManager=e.permissionManager??new ls({defaultPermission:"ask"}),this.loopDetector=Ep(),this.enablePlanMode=e.enablePlanMode??true,e.approvalHandler){let t=e.approvalHandler;this.permissionManager.setApprovalHandler(async s=>({approved:await t({id:"",name:s.toolName,args:s.args}),remember:false}));}}setApprovalHandler(e){if(!e){this.permissionManager.setApprovalHandler(void 0);return}this.permissionManager.setApprovalHandler(async t=>({approved:await e({id:"",name:t.toolName,args:t.args}),remember:false}));}setMode(e){this.currentMode=e,this.modeStrategy=_l(e),m.info("Runner",`Mode switched to: ${e}`);}getMode(){return this.currentMode}getPermissionManager(){return this.permissionManager}computeMaxInputTokens(e,t,s){if(s&&s>0)return s;let r=e&&e>0?e:19e4,i=.7,o=Math.floor(r*i),l=Math.min(t??Ip,Math.floor(r*.1)),c=Math.max(2e3,o-l);if(process.env.CLI_DEBUG==="1"||process.env.CLI_DEBUG_CONSOLE==="1"){let u=`[Context] maxInputTokens=${c} (contextWindow=${r}, override=${s}, tailBudget=${t??Ip}, safety=${i})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Bv){for await(let i of e)yield i;return}let s=e[Symbol.asyncIterator](),n=t?new Promise((i,o)=>{t.aborted?o(Ki()):t.addEventListener("abort",()=>o(Ki()),{once:true});}):null,r=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw Ki()}let i=r?jv:Fv,o=null,l=new Promise((c,u)=>{o=setTimeout(()=>{u($v(r?"idle":"first_chunk",i));},i);});try{let c=await Promise.race(n?[s.next(),l,n]:[s.next(),l]);if(o&&clearTimeout(o),c.done)return;r=!0,yield c.value;}catch(c){if(o&&clearTimeout(o),s.return)try{await s.return();}catch{}throw c?.code==="STREAM_TIMEOUT"&&m.warn("RUNNER",`[watchdog] ${c.message}`),c}}}async applyContextWindow(e=0){if(!this.maxInputTokens)return null;let t=this.memory.getMessagesForLLM(),s=await this.unifiedCompressor.compressHistory(t,this.maxInputTokens,{iteration:e,enableLLMCompression:true});if(s.stats.droppedMessages>0||s.stats.llmCompressedMessages>0){this.memory.setMessages(s.messages);let n=this.compressionMode==="async"?"Async":"Sync",r=(s.originalTokens/1e3).toFixed(1),i=(s.compressedTokens/1e3).toFixed(1),o=(s.savedTokens/1e3).toFixed(1),l=s.originalCount,c=s.compressedCount;m.info("Context",`[${n}] \u538B\u7F29\u5B8C\u6210: ${l}\u6761/${r}K \u2192 ${c}\u6761/${i}K (\u8282\u7701 ${o}K, \u4E22\u5F03${s.stats.droppedMessages}\u6761, LLM\u538B\u7F29${s.stats.llmCompressedMessages}\u6761)`),s.debugInfo&&s.debugInfo.forEach(u=>m.debug("Context",u));}return s}setCompressionMode(e){this.compressionMode=e,m.info("Context",`Compression mode set to: ${e}`);}getCompressionMode(){return this.compressionMode}async getInstructions(e){if(typeof this.instructions=="string")return this.instructions;let t={name:this.agentName,description:this.agentDescription};return await this.instructions(e,t)}async getContextInjection(e){if(!this.contextInjection)return null;let s=(typeof this.contextInjection=="string"?this.contextInjection:await this.contextInjection(e,{name:this.agentName,description:this.agentDescription}))?.trim();return s||null}shouldIncludeLastRun(e){let t=e.trim().toLowerCase();return t?/上次|之前|前面|上一步|上轮|继续|回顾|resume|continue|previous|last time/.test(t):false}createRunContext(e,t=0){return {task:e,timestamp:Date.now(),currentTime:new Date,iteration:t,userData:this.userData,systemStatus:void 0}}setUserData(e){this.userData={...this.userData,...e};}async*run(e,t,s){this.runContext={task:e,timestamp:Date.now(),currentTime:new Date,iteration:0,userData:this.userData},this.loopDetector.reset(),process.env.CLI_DEBUG==="1"&&(m.debug("MK",` hasSignal: ${!!s}`),m.debug("RUNNER","========================================"),m.debug("RUNNER","=== runner.run ENTRY ==="),m.debug("RUNNER",` task: "${e?.substring(0,50)}..."`),m.debug("RUNNER",` hasImages: ${!!t&&t.length>0}`),m.debug("RUNNER",` hasSignal: ${!!s}`)),ge.agentStart(e),yield {type:"agent_updated_stream_event",new_agent:{name:this.agentName}};let n=this.createRunContext(e,0),r=this.memory.hasConversationMessages?.()??this.memory.getMessagesForLLM().some(I=>I.role==="user"||I.role==="assistant"),i=!r||this.shouldIncludeLastRun(e);n.userData={...n.userData??{},hasConversation:r,includeLastRun:i},this.inputGuardrails.length>0&&(yield {type:"raw_response_event",data:{type:"input_guardrails.check_start",count:this.inputGuardrails.length},event_type:"input_guardrails.check_start"},await Rs.runInputGuardrails(this.inputGuardrails,n,this.agentName,e),yield {type:"raw_response_event",data:{type:"input_guardrails.check_passed"},event_type:"input_guardrails.check_passed"});let o=await this.getInstructions(n),l=await this.getContextInjection(n);process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] dynamicInstructions length:",o?.length||0),console.log("[RUNNER] dynamicInstructions START:",o?.substring(0,200)),console.log("[RUNNER] dynamicInstructions END:",o?.substring(o.length-500)),console.log("[RUNNER] contains \u534F\u4F5C\u6A21\u5F0F:",o?.includes("\u534F\u4F5C\u6A21\u5F0F")),console.log("[RUNNER] contains delegate_task:",o?.includes("delegate_task")));let c=this.memory.getMessagesForLLM(),u=c.some(I=>I.role==="system");if(process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] hasSystemPrompt:",u,"existingMessages count:",c.length),console.log("[RUNNER] disableSystemPrompt:",this.disableSystemPrompt)),this.disableSystemPrompt)u&&this.memory.clear(),o&&this.memory.add({role:"system",content:o});else if(!u){let I=this.modeStrategy.getSystemPrompt();this.memory.add({role:"system",content:I}),this.memory.add({role:"system",content:o}),this.structuredValidator&&this.memory.add({role:"system",content:this.structuredValidator.buildSystemPrompt()});try{let A=await al(this.workspacePath);A&&this.memory.add({role:"system",content:A});}catch{}}if(l?this.memory.upsertSystemTagged?this.memory.upsertSystemTagged("context_injection",l):u||this.memory.add({role:"system",content:l}):this.memory.removeSystemTagged?.("context_injection"),t&&t.length>0){let I=[{type:"text",text:e},...t.map(A=>({type:"image_url",image_url:{url:A,detail:"auto"}}))];this.memory.add({role:"user",content:I});}else this.memory.add({role:"user",content:e});let d=Date.now(),p=0,h="",g=0,f={totalTokens:0,promptTokens:0,completionTokens:0},b=false,y=0,w=null,C=new Map,k=0,T=0,_=[],M=this.isExecutionOrientedTask(e),F=0,x=Kt.streamMaxRetries,R=false,j=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:gp,v=j===0||j===1/0,E=Mp(this.config.maxToolCalls,hp),P=Mp(this.config.maxRuntimeMs,fp);for(;v||p<j;){if(s?.aborted){w="interrupted",b=true,yield {type:"error",error:"Task interrupted by user."};break}if(P!==null&&Date.now()-d>=P){w="runtime_limit",b=true,yield {type:"error",error:`Reached max runtime (${nt(P)}). Please summarize progress and ask whether to continue.`};break}if(E!==null&&g>=E){w="tool_call_limit",b=true,yield {type:"error",error:`Reached max tool calls (${E}). Please summarize progress and ask whether to continue.`};break}p++;let I=null;if(this.maxInputTokens){let O=tt(this.memory.getMessagesForLLM()),$=this.maxInputTokens*.97;O>$&&(I=await this.applyContextWindow(p));}I&&(I.stats.droppedMessages>0||I.stats.llmCompressedMessages>0)&&(yield {type:"context_compaction",status:"completed",originalMessages:I.originalCount,keptMessages:I.messages.length,droppedMessages:I.stats.droppedMessages,compressedMessages:I.stats.llmCompressedMessages,originalTokens:I.originalTokens,finalTokens:I.compressedTokens,budgetTokens:this.maxInputTokens||0,useLLM:I.stats.llmCompressedMessages>0,timestamp:Date.now()});let A=this.memory.checkContextHealth();if((A.warnings.length>0||A.shouldCleanup)&&(yield {type:"raw_response_event",data:{type:"context_health",totalTokens:A.totalTokens,toolResultTokens:A.toolResultTokens,toolResultRatio:A.toolResultRatio,messageCount:A.messageCount,toolMessageCount:A.toolMessageCount,warnings:A.warnings,shouldCompress:A.shouldCompress,shouldCleanup:A.shouldCleanup,byType:A.byType},event_type:"context_health"},A.shouldCleanup&&A.byType.ephemeral.count>5)){let O=this.memory.cleanupEphemeral();O>0&&m.info("Runner",`Cleaned ${O} ephemeral messages`);}m.debug("Runner",this.memory.getTokenSummary()),ge.agentIteration(p,"thinking"),yield {type:"iteration_start",iteration:p};try{yield {type:"raw_response_event",data:{type:"response.created",response:{id:`resp_${Date.now()}`,model:this.model}},event_type:"response.created"};let O=this.memory.getMessagesForLLM();if(m.info("LLM",`Request: model=${this.model}, messages=${O.length}, tools=${this.tools.length}`),m.debug("LLM","Request messages",{messageCount:O.length,lastMessage:O[O.length-1]?.content?.toString().substring(0,200)}),process.env.CLI_DEBUG==="1"){let q=O.filter(J=>J.role==="system");console.log("[RUNNER] System messages count:",q.length);for(let J=0;J<q.length;J++){let ie=q[J].content,K=typeof ie=="string"?ie:JSON.stringify(ie);console.log(`[RUNNER] System[${J}] length:`,K?.length||0),console.log(`[RUNNER] System[${J}] contains \u534F\u4F5C\u6A21\u5F0F:`,K?.includes("\u534F\u4F5C\u6A21\u5F0F")||!1),console.log(`[RUNNER] System[${J}] contains delegate_task:`,K?.includes("delegate_task")||!1),console.log(`[RUNNER] System[${J}] preview:`,K?.substring(0,300)||"");}}let $=this.modeStrategy.filterTools(this.tools);process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`Mode: ${this.currentMode}, Available tools: ${$.length}/${this.tools.length}`);let D=this.llmProvider.chatStreamed(this.memory.getMessagesForLLM(),{model:this.model,tools:$,temperature:this.config.temperature,structuredOutput:this.structuredOutput,maxInputTokens:this.maxInputTokens,disableSystemPrompt:this.disableSystemPrompt,enableFGTS:this.enableFGTS,signal:s}),N="",L="",G=[],z=[],oe="",ue={prompt_tokens:0,completion_tokens:0,total_tokens:0};for await(let q of this.withStreamWatchdog(D,s)){if(q.type==="stream_retry"){R=!0,yield q;continue}if(q.type==="stream_recovered"){yield {type:"stream_recovered",attempt:q.attempt,maxRetries:q.maxRetries};continue}yield {type:"raw_response_event",data:q,event_type:q.choices?.[0]?.delta?"response.delta":"response.chunk"};let J=q.choices?.[0]?.delta;if(q.usage){ue={prompt_tokens:q.usage.prompt_tokens||ue.prompt_tokens,completion_tokens:q.usage.completion_tokens||ue.completion_tokens,total_tokens:q.usage.total_tokens||ue.total_tokens,cached_tokens:q.usage.cached_tokens,cache_read_input_tokens:q.usage.cache_read_input_tokens,cache_creation_input_tokens:q.usage.cache_creation_input_tokens,prompt_tokens_details:q.usage.prompt_tokens_details},f={promptTokens:ue.prompt_tokens,completionTokens:ue.completion_tokens,totalTokens:ue.total_tokens};let ie=!!q.choices?.[0]?.finish_reason;yield {type:"token_usage",usage:ue,is_final:ie};}if(J){if(J.reasoning_content&&(L+=J.reasoning_content,yield {type:"reasoning_delta",delta:J.reasoning_content}),J.reasoning_complete&&(yield {type:"reasoning_complete"}),J.content&&(N+=J.content,h=N,yield {type:"text_delta",delta:J.content}),J.tool_calls)for(let ie of J.tool_calls){let K=ie.index;z[K]||(z[K]={id:ie.id||`call_${Math.floor(Date.now())}_${K}`,type:"function",function:{name:"",arguments:""}}),ie.id&&(z[K].id=ie.id),ie.function?.name&&(z[K].function.name=ie.function.name),ie.function?.arguments&&(z[K].function.arguments+=ie.function.arguments,yield {type:"tool_call_delta",id:z[K].id,name:z[K].function.name,arguments_delta:ie.function.arguments}),ie.thoughtSignature&&(z[K].thoughtSignature=ie.thoughtSignature);}q.choices?.[0]?.finish_reason&&(oe=q.choices[0].finish_reason),q.thinking_blocks&&Array.isArray(q.thinking_blocks)&&(G=q.thinking_blocks.map(ie=>({type:ie.type,thinking:ie.thinking,signature:ie.signature,data:ie.data})));}}N&&(yield {type:"text_done"}),process.env.CLI_DEBUG_CONSOLE==="1"&&process.env.NEOX_UI_MODE==="1"&&console.log("[Runner] \u{1F3AF} Emitting response.completed event (after LLM response)"),yield {type:"raw_response_event",data:{type:"response.completed"},event_type:"response.completed"};let Se={role:"assistant",content:(N||"").trimEnd()};if(L&&(Se.reasoning_content=L),G.length>0&&(Se.thinking_blocks=G),z.length>0&&(Se.tool_calls=z.map(q=>({...q,function:{...q.function,arguments:q.function.arguments}}))),this.memory.add(Se),process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Stream ended. toolCalls.length=${z.length}, fullContent.length=${N.length}`),z.length>0){let q=/\[omitted\s+\w+:\s*\d+\s*lines?,\s*\d+\s*chars?\]/i;for(let S of z){let U=S.function.arguments||"";if(q.test(U)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${S.function.name}`),console.error(`[Runner] Arguments preview: ${U.substring(0,500)}`),yield {type:"raw_response_event",data:{type:"error.placeholder_detected",message:"Model generated placeholder string instead of actual content. This usually happens when the model sees truncated data in conversation history.",tool:S.function.name},event_type:"error.placeholder_detected"},yield {type:"error",error:'Error: Model attempted to write placeholder text ("[omitted ...]") instead of actual content. This happens when conversation history contains truncated data. Please start a new conversation.'},b=!0;break}}if(b)break;if(E!==null&&g+z.length>E){w="tool_call_limit",b=!0,yield {type:"error",error:`Tool call budget exceeded (max ${E}, requested ${z.length}). Please summarize progress and ask whether to continue.`};break}if(z.length>1){let S=z.map(Z=>Z.function.name),U=[...new Set(S)];U.length===1&&S.length>1?m.info("RUNNER",`\u{1F504} Parallel calls: ${S.length}x ${U[0]} (different parameters)`):m.info("RUNNER",`\u{1F504} Parallel calls: ${S.join(", ")}`);}let J=new Map;for(let S of z)J.set(S.id,fn(S.function.arguments));for(let S of z){g++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:S.id,name:S.function.name,arguments:S.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:S.id,name:S.function.name};let Z=J.get(S.id),H=Z?.ok??!1;H?Z?.repaired&&m.warn("RUNNER","Tool arguments repaired from non-standard JSON",{tool:S.function.name,callId:S.id}):ge.toolError(S.function.name,`Invalid JSON arguments (${Z?.reason||"parse failed"}): ${S.function.arguments.substring(0,200)}...`),yield {type:"tool_call_done",id:S.id,name:S.function.name,arguments:S.function.arguments,success:H},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:S.id,name:S.function.name,arguments:S.function.arguments},event_type:"response.function_call_arguments.done"};}let ie=new Set,K=null,xe=z.length>1;process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`Processing ${z.length} tool call(s)`,{isParallel:xe,tools:z.map(S=>S.function.name)});for(let S of z){let U=J.get(S.id);if(!U?.ok){let de=`Invalid JSON arguments for tool "${S.function.name}": ${U?.reason||"parse failed"}. Return strict JSON object arguments.`;yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:de,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:de,success:!1},this.memory.addToolResult(S.id,S.function.name,de),this.loopDetector.updateLastStatus("error"),ie.add(S.id);continue}let Z=U.args,H=this.loopDetector.detect(S.function.name,Z);if(this.loopDetector.record(S.function.name,Z),H===0)continue;let se=this.loopDetector.generateIntervention(H,S.function.name,Z);if(this.memory.add({role:"system",content:se.message}),H===2&&nu(S.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:se.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:se.message,success:!1},this.memory.addToolResult(S.id,S.function.name,se.message),this.loopDetector.updateLastStatus("error"),ie.add(S.id),se.shouldTerminate){K=se;break}}if(K&&(yield {type:"error",error:K.message},b=!0),b)break;let ee=ie.size>0?z.filter(S=>!ie.has(S.id)):z,fe=new Set(this.modeStrategy.filterTools(this.tools).map(S=>S.name)),ne=S=>S.replace(/["\s/>]+$/g,"").trim(),le=[];for(let S of ee){let U=ne(S.function.name);if(fe.has(U)||fe.has(S.function.name)){le.push(S);continue}let Z=`Tool "${S.function.name}" is not allowed in ${this.currentMode} mode`;ge.toolError(S.function.name,Z),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:Z,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.function.name,output:Z,success:!1},this.memory.addToolResult(S.id,S.function.name,Z),m.info("PERMISSION",`Tool blocked by mode: ${S.function.name} - ${Z}`);}if(le.length===0)continue;let Q=le.map(S=>({id:S.id,type:"function",function:{name:S.function.name,arguments:(()=>{let U=J.get(S.id);return U?.ok?JSON.stringify(U.args):S.function.arguments})()}})),Be=!1;if(process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Before permission check. shouldAutoApprove=${this.modeStrategy.shouldAutoApprove()}, parallelToolCalls=${Q.length}`),!this.modeStrategy.shouldAutoApprove()){let S=new Set;try{for(let U of le)try{let Z=J.get(U.id);if(!Z?.ok)continue;let H=Z.args,se=this.tools.find(Y=>Y.name===U.function.name);if(!se){m.warn("RUNNER",`Tool not found: ${U.function.name}`);continue}let be=await Pp(s,async()=>this.permissionManager.checkPermission(se,H));if(!be.allowed){S.add(U.id);let Y=be.reason||`Tool "${U.function.name}" was denied`;ge.toolError(U.function.name,Y),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:U.id,name:U.function.name,output:Y,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:U.id,name:U.function.name,output:Y,success:!1};let Ae=JSON.stringify({type:"ephemeral",status:"error",tool:U.function.name,summary:"Tool execution denied by user",error:Y,final:!0});this.memory.addToolResult(U.id,U.function.name,Ae),m.info("PERMISSION",`Tool denied: ${U.function.name} - ${Y}`),Be=!0;}}catch(Z){if(Z?.name==="AbortError"||Z?.code==="ERR_CANCELED")throw Z;ge.toolError(U.function.name,Z?.message||"permission check failed");}}catch(U){if(U?.name==="AbortError"||U?.code==="ERR_CANCELED"){m.info("RUNNER","Interrupt detected during permission check"),b=!0;break}throw U}if(le=le.filter(U=>!S.has(U.id)),Q=Q.filter(U=>!S.has(U.id)),Be){m.info("RUNNER","User denied tool - terminating current turn");break}if(Q.length===0)continue}if(process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} After permission check. parallelToolCalls=${Q.length}, userDeniedTool=${Be}`),this.toolInputGuardrails.length>0){let S=new Set;try{for(let U of le)try{let Z=J.get(U.id);if(!Z?.ok)continue;let H=Z.args,se={tool_name:U.function.name,tool_input:H,tool_call_id:U.id},be=this.tools.find(de=>de.name===U.function.name);if(!be)continue;this.runContext.iteration=p;let Y=await Pp(s,async()=>Rs.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:se,agent_name:this.agentName,tool:be}));if(!Y.should_execute){S.add(U.id);let de=Y.rejection_message||`Tool ${U.function.name} was blocked by guardrail`;ge.toolError(U.function.name,`Blocked by guardrail: ${de}`),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:U.id,name:U.function.name,output:de,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:U.id,name:U.function.name,output:de,success:!1},this.memory.addToolResult(U.id,U.function.name,de),bl(this.runContext,U.function.name,H,!1);}}catch(Z){if(Z?.name==="AbortError"||Z?.code==="ERR_CANCELED")throw Z;if(Z instanceof yt){ge.toolError(U.function.name,`Guardrail tripwire triggered: ${Z.message}`),yield {type:"error",error:`Guardrail tripwire triggered for ${U.function.name}: ${Z.message}`},b=!0;break}ge.toolError(U.function.name,`Guardrail check failed: ${Z?.message}`);}}catch(U){if(U?.name==="AbortError"||U?.code==="ERR_CANCELED"){m.info("RUNNER","Interrupt detected during guardrails check"),b=!0;break}throw U}if(b)break;if(le=le.filter(U=>!S.has(U.id)),Q=Q.filter(U=>!S.has(U.id)),Q.length===0)continue}process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${Q.length}`);let ze=await this.parallelExecutor.execute(Q,this.tools,S=>{if(ge.toolCall(S.name,{}),S.success){let Z=typeof S.output=="string"?S.output.length:JSON.stringify(S.output).length;ge.toolResult(S.name,!0,Z,S.executionTime||0);}else ge.toolError(S.name,S.output);let U={type:"tool_call_output_item",id:S.id,name:S.name,output:S.output,success:S.success,timestamp:Date.now()};},s),B=0,re=0,V=0,pe=!1;for(let S of ze.results){if(this.toolMetricsHistory.push({name:S.name,duration:S.executionTime||0,success:S.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.name,output:S.output,success:S.success,timestamp:Date.now()}},yield {type:"tool_output",id:S.id,name:S.name,output:S.output,success:S.success},(S.name==="update_plan"||S.name==="call_tool")&&S.success)try{m.info("PLAN_UPDATE","\u{1F525} Detected plan-related tool call",{resultId:S.id,toolName:S.name,toolCallsCount:z.length});let Y=z.find(de=>de.id===S.id);if(Y){m.info("PLAN_UPDATE","\u{1F525} Found original call",{callId:Y.id,argsLength:Y.function.arguments?.length});let de=fn(Y.function.arguments||"{}");if(!de.ok)throw new Error(de.reason||"Invalid update_plan arguments");let Ae=de.args,et=null;if(S.name==="update_plan"?et=Ae:S.name==="call_tool"&&Ae?.name==="update_plan"&&(et=Ae.args),!et||!Array.isArray(et.plan))m.debug("PLAN_UPDATE","Skip non-update_plan call_tool",{resultId:S.id,toolName:S.name,callToolName:Ae?.name});else {let An=!0;if(typeof S.output=="string")try{let gs=JSON.parse(S.output);gs&&typeof gs=="object"&&"success"in gs&&(An=gs.success!==!1);}catch{}An?(m.info("PLAN_UPDATE","\u{1F525} Parsed plan args",{hasExplanation:!!et.explanation,planSteps:et.plan?.length}),yield {type:"plan_update",explanation:et.explanation,plan:et.plan,timestamp:Date.now()},m.info("PLAN_UPDATE","\u2705 Emitted plan_update event")):m.warn("PLAN_UPDATE","Skip failed update_plan output",{resultId:S.id});}}else m.warn("PLAN_UPDATE","\u274C Could not find original tool call",{resultId:S.id,availableIds:z.map(de=>de.id)});}catch(Y){m.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:Y});}let Z=typeof S.output=="string"?Dp(S.output):Dp(JSON.stringify(S.output));Z=this.enrichToolResult(Z,S.name,S.executionTime||0);let H=z.find(Y=>Y.id===S.id),se={};if(H){let Y=fn(H.function.arguments||"{}");Y.ok&&(se=Y.args);}if(this.toolOutputGuardrails.length>0)try{let Y=this.tools.find(de=>de.name===S.name);if(Y){let de={tool_name:S.name,tool_input:se,tool_call_id:S.id},Ae=await Rs.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:de,agent_name:this.agentName,tool:Y,output:S.output});Ae.should_use_output||(Z=Ae.replacement_message||"[Output blocked by guardrail]",ge.toolError(S.name,"Output blocked by guardrail"));}}catch(Y){Y instanceof yt&&ge.toolError(S.name,`Output guardrail tripwire triggered: ${Y.message}`);}if(!S.success&&typeof S.output=="string"){let Y=S.output.toLowerCase();if(Y.includes("operation cancelled")||Y.includes("command interrupted")||Y.includes("request aborted")){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Detected cancellation in tool output, breaking loop"),m.info("RUNNER","\u68C0\u6D4B\u5230\u5DE5\u5177\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u6267\u884C\u5FAA\u73AF"),b=!0;break}}bl(this.runContext,S.name,se,S.success),m.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${S.name}`,{toolName:S.name,success:S.success,rawLength:typeof S.output=="string"?S.output.length:JSON.stringify(S.output).length,truncatedLength:Z.length,outputPreview:Z.substring(0,500)}),this.memory.addToolResult(S.id,S.name,Z);let be=S.success?"success":"error";try{let Y=typeof S.output=="string"?S.output:JSON.stringify(S.output),de=JSON.parse(Y);de.status==="already_done"?be="already_done":de.status==="success"?be="success":de.status==="error"&&(be="error");}catch{}if(this.loopDetector.updateLastStatus(be),_.push({iteration:p,name:S.name,status:be,executionTime:S.executionTime||0}),_.length>24&&_.shift(),be==="error"?re++:be==="already_done"?(V++,this.isVerificationTool(S.name)&&(pe=!0)):(B++,this.isVerificationTool(S.name)&&(pe=!0)),be==="error"){let Y=(C.get(S.name)||0)+1;if(C.set(S.name,Y),S.name==="edit_file"&&(Y===2||Y===3)){let de=typeof S.output=="string"?S.output:JSON.stringify(S.output),Ae=S.name,et=Ap(Ae,de);this.memory.add({role:"system",content:et});}}else C.set(S.name,0);}if(p>0&&p%5===0){let S=this.buildPerformanceHint();S&&(this.memory.add({role:"system",content:S}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",S));}let Re=B+V>0;if(k=re>0&&!Re?k+1:0,process.env.CLI_DEBUG==="1"&&m.debug("LOOP_GATE","Iteration quality",{iteration:p,executionTask:M,success:B,alreadyDone:V,error:re,lowProgressStreak:k,verificationSuccess:pe}),M&&k>=2&&(this.memory.add({role:"system",content:this.buildLowProgressReplanPrompt(k)}),T++,k=0,yield {type:"raw_response_event",data:{type:"loop.progress_gate",iteration:p,reason:"low_progress",nudgeCount:T},event_type:"loop.progress_gate"}),process.env.CLI_DEBUG_CONSOLE==="1"&&ze.stats&&(yield {type:"raw_response_event",data:{type:"parallel_execution.stats",stats:ze.stats},event_type:"parallel_execution.stats"}),s?.aborted){b=!0;break}continue}else {if(this.plannerMode&&y<2&&this.shouldAutoContinuePlan(N)){y++;let J=this.buildPlanFollowupPrompt();yield {type:"raw_response_event",data:{type:"plan.auto_continue",plan_text:N,followup_prompt:J,count:y},event_type:"plan.auto_continue"},this.memory.add({role:"user",content:J});continue}if(N&&(yield {type:"run_item_stream_event",name:"message_output_created",item:{type:"message_output_item",content:N,role:"assistant",timestamp:Date.now()}}),process.env.CLI_DEBUG==="1"&&(m.info("RUNNER","=== Loop Exit: No Tool Calls ==="),m.info("RUNNER",`Finish Reason: ${oe}`),m.info("RUNNER",`Content Length: ${N.length}`),m.info("RUNNER",`Content Preview: ${N.slice(0,300)}`),m.info("RUNNER",`Tool Calls Count: ${z.length}`),m.info("RUNNER",`Iteration: ${p}`)),this.structuredValidator){let J=this.structuredValidator.validate(N);if(J.ok)h=J.normalized||N,yield {type:"raw_response_event",data:{type:"structured_output.accepted",schema:this.structuredOutput?.name,normalized_text:h,parsed:J.parsed},event_type:"structured_output.accepted"};else {yield {type:"raw_response_event",data:{type:"structured_output.retry",schema:this.structuredOutput?.name,reason:J.reason,message:J.message,errors:J.errors},event_type:"structured_output.retry"},this.memory.add({role:"system",content:this.structuredValidator.buildRetryPrompt(J)}),h="";continue}}else h=N;this.outputGuardrails.length>0&&h&&(yield {type:"raw_response_event",data:{type:"output_guardrails.check_start",count:this.outputGuardrails.length},event_type:"output_guardrails.check_start"},await Rs.runOutputGuardrails(this.outputGuardrails,n,this.agentName,h),yield {type:"raw_response_event",data:{type:"output_guardrails.check_passed"},event_type:"output_guardrails.check_passed"});let q=this.evaluateCompletionEvidence(M,g,_);if(!q.ok){T++,this.memory.add({role:"system",content:this.buildEvidenceRequiredPrompt(q.reason)}),process.env.CLI_DEBUG==="1"&&m.debug("LOOP_GATE","Completion blocked: missing evidence",{iteration:p,reason:q.reason,nudgeCount:T}),yield {type:"raw_response_event",data:{type:"loop.completion_gate",iteration:p,reason:q.reason,nudgeCount:T},event_type:"loop.completion_gate"};continue}break}}catch(O){if(O?.type==="stream_retry"){R=true,yield O;continue}let $=O instanceof Ce?O:ft(O);if(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Error classified:",{category:$.category,code:$.code,retryable:$.retryable,message:$.message}),$.category==="canceled"){w="interrupted",b=true,yield {type:"error",error:"Task interrupted by user."};break}if($.retryable&&F<x&&!R){F++;let G=hr($.category,F,$.retryAfter),z=$.category==="retryable_rate_limit",oe=$.code==="STREAM_TIMEOUT",ue=$.category==="retryable_network"||$.category==="retryable_stream";m.warn("RUNNER",`Retrying after ${nt(G)} (attempt ${F}/${x}): ${$.message}`),yield {type:"raw_response_event",data:{type:"runner.stream_retry",error:$.message,errorCode:$.code,attempt:F,maxRetries:x,delayMs:G,isRateLimit:z,isStreamTimeout:oe,isNetworkError:ue},event_type:"runner.stream_retry"},await gn(G),p--;continue}let D=Gi($),N=$.message;D&&!N.includes(D)&&(N=`${N}
1488
1488
 
1489
- \u{1F4A1} Suggestion: ${P}`),b=true;let D=Sp(N,{providerName:this.providerName});ge.agentError(D),yield {type:"raw_response_event",data:{type:"error.classified",category:$.category,code:$.code,message:$.message,retryable:$.retryable,suggestion:P,context:$.context},event_type:"error.classified"},yield {type:"error",error:D};break}}!b&&!v&&p>=j&&!h&&(w=w||"iteration_limit",b=true,yield {type:"error",error:`Reached max iterations (${j}). Please summarize progress and ask whether to continue.`}),b||(ge.agentComplete(p,g,f),m.info("LLM",`Complete: iterations=${p}, toolCalls=${g}, tokens=${f.totalTokens} (prompt=${f.promptTokens}, completion=${f.completionTokens})`)),process.env.CLI_DEBUG==="1"&&(m.debug("RUNNER","=== runner.run COMPLETING ==="),m.debug("RUNNER",` iterations: ${p}`),m.debug("RUNNER",` toolCalls: ${g}`),m.debug("RUNNER",` encounteredError: ${b}`),w&&m.debug("RUNNER",` stoppedBy: ${w}`)),yield {type:"run_done"},process.env.CLI_DEBUG==="1"&&m.debug("RUNNER","=== runner.run END (run_done yielded) ===");}shouldAutoContinuePlan(e){if(!this.plannerMode)return false;let t=(e||"").trim();if(t.length<40)return false;let s=t.toLowerCase();return ["planned steps","plan:","execution plan","\u884C\u52A8\u8BA1\u5212","\u8BA1\u5212\uFF1A","\u8BA1\u5212\u5982\u4E0B","\u65B9\u6848\uFF1A","\u6B65\u9AA4\u8BA1\u5212"].some(o=>s.includes(o))?(t.match(/(^|\n)\s*[-*•]\s+/g)||[]).length+(t.match(/(^|\n)\s*\d+\.\s+/g)||[]).length>=2:false}buildPlanFollowupPrompt(){return "Plan approved. Continue executing the plan step by step and start working immediately."}isExecutionOrientedTask(e){let t=(e||"").toLowerCase();return t.trim()?/(修复|修改|实现|编写|重构|新增|删除|运行|测试|构建|验证|fix|implement|write|edit|refactor|run|test|build|validate|debug)/i.test(t):false}isVerificationTool(e){let t=(e||"").toLowerCase();return t.includes("read")||t.includes("search")||t.includes("grep")||t.includes("test")||t.includes("lint")||t.includes("build")||t.includes("check")||t.includes("execute_shell")||t==="bash"}isMutationTool(e){let t=(e||"").toLowerCase();return t.includes("write")||t.includes("edit")||t.includes("create")||t.includes("delete")||t.includes("rename")}evaluateCompletionEvidence(e,t,s){if(this.currentMode==="auto")return {ok:true,reason:"assistant_mode"};if(!e)return {ok:true,reason:"non_execution_task"};if(t===0)return {ok:false,reason:"no_tool_execution"};let r=s.slice(-10).filter(l=>l.status==="success"||l.status==="already_done");return r.length===0?{ok:false,reason:"no_successful_tool_result"}:r.some(l=>this.isVerificationTool(l.name))?{ok:true,reason:"verified"}:r.some(l=>this.isMutationTool(l.name))?{ok:false,reason:"missing_validation_after_mutation"}:{ok:true,reason:"sufficient_success"}}buildLowProgressReplanPrompt(e){return ["[LOOP OPTIMIZER NOTICE]",`You had ${e} low-progress iterations (mostly failed tool calls).`,"Pause and re-plan before next tool call.","Required:","1) Briefly state root cause of previous failures.","2) Choose a different tool/argument strategy.","3) Run one verification step to confirm progress."].join(`
1489
+ \u{1F4A1} Suggestion: ${D}`),b=true;let L=Sp(N,{providerName:this.providerName});ge.agentError(L),yield {type:"raw_response_event",data:{type:"error.classified",category:$.category,code:$.code,message:$.message,retryable:$.retryable,suggestion:D,context:$.context},event_type:"error.classified"},yield {type:"error",error:L};break}}!b&&!v&&p>=j&&!h&&(w=w||"iteration_limit",b=true,yield {type:"error",error:`Reached max iterations (${j}). Please summarize progress and ask whether to continue.`}),b||(ge.agentComplete(p,g,f),m.info("LLM",`Complete: iterations=${p}, toolCalls=${g}, tokens=${f.totalTokens} (prompt=${f.promptTokens}, completion=${f.completionTokens})`)),process.env.CLI_DEBUG==="1"&&(m.debug("RUNNER","=== runner.run COMPLETING ==="),m.debug("RUNNER",` iterations: ${p}`),m.debug("RUNNER",` toolCalls: ${g}`),m.debug("RUNNER",` encounteredError: ${b}`),w&&m.debug("RUNNER",` stoppedBy: ${w}`)),yield {type:"run_done"},process.env.CLI_DEBUG==="1"&&m.debug("RUNNER","=== runner.run END (run_done yielded) ===");}shouldAutoContinuePlan(e){if(!this.plannerMode)return false;let t=(e||"").trim();if(t.length<40)return false;let s=t.toLowerCase();return ["planned steps","plan:","execution plan","\u884C\u52A8\u8BA1\u5212","\u8BA1\u5212\uFF1A","\u8BA1\u5212\u5982\u4E0B","\u65B9\u6848\uFF1A","\u6B65\u9AA4\u8BA1\u5212"].some(o=>s.includes(o))?(t.match(/(^|\n)\s*[-*•]\s+/g)||[]).length+(t.match(/(^|\n)\s*\d+\.\s+/g)||[]).length>=2:false}buildPlanFollowupPrompt(){return "Plan approved. Continue executing the plan step by step and start working immediately."}isExecutionOrientedTask(e){let t=(e||"").toLowerCase();return t.trim()?/(修复|修改|实现|编写|重构|新增|删除|运行|测试|构建|验证|fix|implement|write|edit|refactor|run|test|build|validate|debug)/i.test(t):false}isVerificationTool(e){let t=(e||"").toLowerCase();return t.includes("read")||t.includes("search")||t.includes("grep")||t.includes("test")||t.includes("lint")||t.includes("build")||t.includes("check")||t.includes("execute_shell")||t==="bash"}isMutationTool(e){let t=(e||"").toLowerCase();return t.includes("write")||t.includes("edit")||t.includes("create")||t.includes("delete")||t.includes("rename")}evaluateCompletionEvidence(e,t,s){if(this.currentMode==="auto")return {ok:true,reason:"assistant_mode"};if(!e)return {ok:true,reason:"non_execution_task"};if(t===0)return {ok:false,reason:"no_tool_execution"};let r=s.slice(-10).filter(l=>l.status==="success"||l.status==="already_done");return r.length===0?{ok:false,reason:"no_successful_tool_result"}:r.some(l=>this.isVerificationTool(l.name))?{ok:true,reason:"verified"}:r.some(l=>this.isMutationTool(l.name))?{ok:false,reason:"missing_validation_after_mutation"}:{ok:true,reason:"sufficient_success"}}buildLowProgressReplanPrompt(e){return ["[LOOP OPTIMIZER NOTICE]",`You had ${e} low-progress iterations (mostly failed tool calls).`,"Pause and re-plan before next tool call.","Required:","1) Briefly state root cause of previous failures.","2) Choose a different tool/argument strategy.","3) Run one verification step to confirm progress."].join(`
1490
1490
  `)}buildEvidenceRequiredPrompt(e){return ["[COMPLETION GATE]",`Cannot conclude task yet: ${e}.`,"Before final answer, provide concrete execution evidence:","- If code/files changed, verify via read/test/build/lint/check command.","- If command already ran, quote key output signals.","Then continue and finish only after evidence is present."].join(`
1491
1491
  `)}enrichToolResult(e,t,s){if(s<1e3)return e;let n=s>=1e3?`${(s/1e3).toFixed(1)}s`:`${s}ms`;return `\u23F1\uFE0F [${t} took ${n}]
1492
1492
 
@@ -1695,8 +1695,8 @@ Tool results are returned via tool_result messages.`}supportsExtendedThinking(e)
1695
1695
 
1696
1696
  `;return l+d+c}function Gp(a,e=2e3){let t=a&&typeof a.toJSON=="function"?a.toJSON():a,s="";try{s=JSON.stringify(t??{},null,2);}catch{s=String(t??"");}return s?s.length>e?`${s.slice(0,e)}
1697
1697
  ...[truncated ${s.length-e} chars]`:s:"No headers"}var Al="You are Claude Code, Anthropic's official CLI for Claude.",aw=["claude-code-20250219","interleaved-thinking-2025-05-14"],eo="2023-06-01",to=64,lw=1024;var Up=18e4,Wp=6e4,zp={readfile:"Read",write_file:"Write",edit_file:"Edit",glob_search:"Glob",glob:"Glob",search:"Grep",execute_shell:"Bash",bash:"Bash",shell:"Bash",todo_write:"TodoWrite",task:"Task",web_fetch:"WebFetch",web_search:"WebSearch",notebook_edit:"NotebookEdit",ask_user:"AskUserQuestion"},El={Read:"readfile",Write:"write_file",Edit:"edit_file",Glob:"glob_search",Grep:"search",Bash:"execute_shell",TodoWrite:"todo_write",Task:"task",WebFetch:"web_fetch",WebSearch:"web_search",NotebookEdit:"notebook_edit",AskUserQuestion:"ask_user"},bn=class{client;defaultModel;maxTokens;retryConfig;baseUrl;authToken;isProxyMode;claudeCodeUserId;betaFeatures;systemPromptPrefix;sanitizeToolsForProxy;disableCaching;thinkingConfig=null;constructor(e){this.authToken=e.authToken,this.baseUrl=(e.baseUrl||"https://api.anthropic.com").replace(/\/+$/,"");let t=this.baseUrl.includes("api.anthropic.com");this.isProxyMode=e.forceClaudeCodeMode||!t;let s=typeof e.userId=="string"?e.userId.trim():"";this.claudeCodeUserId=s?this.sanitizeUserId(s):this.generateSafeUserId(),this.betaFeatures=e.betaFeatures||aw,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?Al:null),this.sanitizeToolsForProxy=false,this.disableCaching=e.disableCaching||false,this.client=Xv.create({baseURL:this.baseUrl,headers:this.buildHeaders(),timeout:3e5,validateStatus:()=>true}),this.defaultModel=e.defaultModel||"claude-sonnet-4-5-20250929",this.maxTokens=e.maxTokens||32e3;let n=dn("anthropic",this.baseUrl);this.retryConfig=is(void 0,{...n,...e.retry}),this.debugLog("Initialized",{baseUrl:this.baseUrl,isProxyMode:this.isProxyMode,defaultModel:this.defaultModel,betaFeatures:this.betaFeatures});}setThinking(e){this.thinkingConfig=e,this.debugLog("Thinking config updated",{config:e});}setUserId(e){let t=e?.trim?.()||"";t&&(this.claudeCodeUserId=this.sanitizeUserId(t));}isCacheControlError(e){let t="";try{let s=e.response?.data;if(typeof s=="string")t=s.toLowerCase();else if(s&&typeof s=="object"){let n={error:s.error,message:s.message,type:s.type,code:s.code};t=JSON.stringify(n).toLowerCase();}else t=String(e.message||"").toLowerCase();}catch{t=String(e.message||"").toLowerCase();}return t.includes("cache_control")||t.includes("ttl=")||t.includes("ephemeral")||t.includes("cache")&&t.includes("block")}async chat(e,t={}){let s={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},n=this.retryConfig.requestMaxRetries,r=null,i=s.disableCaching||false;for(let o=0;o<=n;o++){let l={...s,...i?{disableCaching:true}:{}},c=this.buildPayload(e,l);o===0&&this.logRequest(t.model||this.defaultModel,c);try{let u=Date.now(),d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",p=await this.client.post(d,c,{responseType:"stream",signal:t.signal});if(p.status!==200){let f="";for await(let C of p.data)f+=C.toString();let b=`${this.baseUrl}${d}`,y=Ft(b,this.buildHeaders(),c,!1);m.error("CURL","=== [chat] API Error - Full Request CURL ==="),m.error("CURL",y),m.error("CURL",`=== Error Headers: ${Gp(p.headers)} ===`),m.error("CURL",`=== Error Response: ${f.substring(0,1e3)} ===`);let w=new Error(`Anthropic API error: ${p.status}`);w.response={status:p.status,headers:p.headers,data:f};try{let C=JSON.parse(f);w.response.data=C,C.error?.message?w.message=`Anthropic API error: ${p.status} - ${C.error.message}`:C.message&&(w.message=`Anthropic API error: ${p.status} - ${C.message}`),this.debugLog("API Error Details",C);}catch{this.debugLog("API Error (non-JSON)",{status:p.status,dataLength:f.length});}throw w}let h=await this.collectStreamResponse(p.data),g=Date.now()-u;return ge.llmResponse("anthropic",g,h.usage,h.choices[0]),this.debugLog("Response",{duration:`${g}ms`,usage:h.usage}),h}catch(u){await this.normalizeAxiosStreamError(u),r=u;let d=ft(u);if(d.code==="PROXY_UPSTREAM_FAILED"){let b=JSON.stringify(c||{}).length,y=Array.isArray(e)?e.length:0,w=Array.isArray(e)?e.reduce((C,k)=>k?.content?typeof k.content=="string"?C+k.content.length:Array.isArray(k.content)?C+k.content.map(T=>typeof T.text=="string"?T.text.length:0).reduce((T,_)=>T+_,0):C:C,0):0;m.warn("Anthropic","Upstream request failed (PROXY_UPSTREAM_FAILED)",{attempt:`${o+1}/${n+1}`,payloadSize:b,msgCount:y,promptChars:w,status:u.response?.status});}if(this.debugLog("Error",{message:u.message,category:d.category,code:d.code,attempt:`${o+1}/${n+1}`}),ge.llmError("anthropic",u),this.isCacheControlError(u)&&!i){i=true,this.disableCaching=true,this.debugLog("Cache control not supported, disabling caching for retry",{errorMessage:u.message,attempt:o+1}),m.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(!d.retryable||o===n)throw d;let p=Bi(u.response?.headers),h=hr(d.category,o+1,p||d.retryAfter),g=d.category==="retryable_rate_limit",f=g?`\u23F3 API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${nt(h)} \u540E\u91CD\u8BD5...`:`Retrying in ${nt(h)}...`;this.debugLog("Retrying",{delay:nt(h),attempt:o+1,isRateLimit:g,serverDelay:p?nt(p):"none",retryMsg:f});try{await As(h,s.signal);}catch(b){throw b?.name==="AbortError"&&this.debugLog("Chat retry interrupted by user"),b}}}throw r||new Error("Unknown error during retry")}async collectStreamResponse(e){let t="",s="",n=[],r="",i=null,o="";for await(let c of e){let u=c.toString();t+=u;let d=t.split(`
1698
- `);t=d.pop()||"";for(let p of d){let h=p.trim();if(!h||!h.startsWith("data: "))continue;let g=h.slice(6);if(g!=="[DONE]")try{let f=JSON.parse(g);if(process.env.CLI_DEBUG==="1"){let b=JSON.stringify(f).substring(0,80);m.debug("SSE",`${f.type.padEnd(20)} ${b}${JSON.stringify(f).length>80?"...":""}`);}switch(f.type){case "message_start":o=f.message?.id||"",i=f.message?.usage;break;case "content_block_start":if(f.content_block?.type==="tool_use"){let b=f.content_block,y=this.isProxyMode?El[b.name]||this.fromClaudeCodeToolName(b.name):b.name;n.push({id:b.id,type:"function",function:{name:y,arguments:""}});}break;case "content_block_delta":f.delta?.type==="text_delta"?s+=f.delta.text||"":f.delta?.type==="input_json_delta"?n.length>0&&(n[n.length-1].function.arguments+=f.delta.partial_json||""):f.delta?.type==="thinking_delta"&&(r+=f.delta.thinking||"");break;case "message_delta":f.usage&&(i={...i,...f.usage});break}}catch(f){process.env.CLI_DEBUG==="1"&&m.warn("Anthropic",`Stream parse error: ${f}, data: ${g.substring(0,200)}`);}}}let l=this.buildUsageFromRaw(i);return {id:o,choices:[{message:{role:"assistant",content:s||"",tool_calls:n.length>0?n:void 0,...r?{reasoning_content:r}:{}},finish_reason:n.length>0?"tool_calls":"stop"}],usage:l}}async*chatStreamed(e,t={}){let s={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},n=this.retryConfig.streamMaxRetries,r=0,i=s.disableCaching||false,o=true;for(;;){let l={...s,...i?{disableCaching:true}:{}},c=this.buildPayload(e,l);c.stream=true,o&&(this.logRequest(t.model||this.defaultModel,c,true),o=false);try{let u=Date.now(),d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",p=await this.client.post(d,c,{responseType:"stream",signal:t.signal});if(this.debugLog("Stream started",{status:p.status}),p.status!==200){let v="";for await(let A of p.data)v+=A.toString();let E=`${this.baseUrl}${d}`,L=Ft(E,this.buildHeaders(),c,!1);m.error("CURL","=== [chatStreamed] API Error - Full Request CURL ==="),m.error("CURL",L),m.error("CURL",`=== Error Headers: ${Gp(p.headers)} ===`),m.error("CURL",`=== Error Response: ${v.substring(0,1e3)} ===`);let I=new Error(`Anthropic API error: ${p.status}`);I.response={status:p.status,headers:p.headers,data:v};try{let A=JSON.parse(v);I.response.data=A,A.error?.message?I.message=`Anthropic API error: ${p.status} - ${A.error.message}`:A.message&&(I.message=`Anthropic API error: ${p.status} - ${A.message}`),this.debugLog("API Error Details (stream)",A);}catch{this.debugLog("API Error (non-JSON, stream)",{status:p.status,dataLength:v.length});}throw I}let h="",g=[],f=0,b=!1,y=null,w=!1,C=Date.now(),k=0,T=0,_=null,M=null,F=[],x=null;for await(let v of this.createTimeoutStream(p.data,t.signal)){C=Date.now();let E=v.toString();h+=E;let L=h.split(/\n\n+/);h=L.pop()||"";for(let I of L){let A=I.split(`
1699
- `),O="";for(let $ of A){let P=$.trim();if(P&&!P.startsWith("event:"))if(P.startsWith("data:")){let N=P.slice(5);N.startsWith(" ")&&(N=N.slice(1)),O+=N;}else O+=P;}if(!(!O||O==="[DONE]"))try{let $=O.trim(),P=JSON.parse($);if(process.env.CLI_DEBUG==="1"){let G=JSON.stringify(P).substring(0,80);m.debug("SSE",`${P.type.padEnd(20)} ${G}${JSON.stringify(P).length>80?"...":""}`);}let N=Date.now(),D=this.handleStreamEvent(P,g,f,b,y);if(process.env.CLI_DEBUG==="1"){let G=Date.now()-N;G>50&&m.warn("SSE",`\u26A0\uFE0F Slow event handling: ${P.type} took ${G}ms`);}if(D.yield){let G=Date.now();if(yield D.yield,process.env.CLI_DEBUG==="1"){let z=Date.now()-G;z>100&&m.warn("SSE",`\u26A0\uFE0F Slow yield consumer: ${P.type} yield took ${z}ms`);}}if(D.roleSent!==void 0&&(b=D.roleSent),D.incrementToolIndex&&f++,D.usage&&(y=D.usage),D.error)throw new Error(D.error);D.contentBlockStart&&(T++,D.blockType&&(M=D.blockType)),D.contentBlockStop&&(k++,M==="thinking"&&(yield {choices:[{delta:{reasoning_complete:!0},index:0}]}),M=null),D.messageStop&&(w=!0),D.stopReason&&(_=D.stopReason),P.type==="content_block_start"?P.content_block?.type==="thinking"?x={type:"thinking",thinking:"",signature:""}:P.content_block?.type==="redacted_thinking"&&F.push({type:"redacted_thinking",data:P.content_block.data}):P.type==="content_block_delta"?x&&(P.delta?.type==="thinking_delta"?x.thinking+=P.delta.thinking||"":P.delta?.type==="signature_delta"&&(x.signature+=P.delta.signature||"")):P.type==="content_block_stop"&&x&&(F.push({type:x.type,thinking:x.thinking,signature:x.signature}),x=null);}catch{}}}let R=Date.now()-u;if(this.debugLog("Stream completion check",{messageStopReceived:w,stopReason:_,contentBlocksStarted:T,contentBlocksCompleted:k,toolCallsCount:g.length,duration:`${R}ms`}),!w&&!_){let v=new Error(`Stream incomplete: message_stop not received (blocks: ${T} started, ${k} completed)`);throw v.code="STREAM_INCOMPLETE",v.isNetworkInterrupt=!0,this.debugLog("Stream incomplete detected",{messageStopReceived:w,stopReason:_,contentBlocksStarted:T,contentBlocksCompleted:k,toolCallsCount:g.length,duration:`${R}ms`}),v}if(T!==k)if(_==="max_tokens")this.debugLog("Content blocks mismatch due to max_tokens (expected, not an error)",{contentBlocksStarted:T,contentBlocksCompleted:k,stopReason:_}),m.warn("Anthropic","\u26A0\uFE0F Response truncated due to max_tokens limit. Consider increasing max_tokens or breaking down the task.");else {let v=new Error(`Stream incomplete: content blocks mismatch (${T} started, ${k} completed)`);throw v.code="STREAM_INCOMPLETE",v.isNetworkInterrupt=!0,this.debugLog("Content blocks mismatch",{contentBlocksStarted:T,contentBlocksCompleted:k,stopReason:_}),v}if(g.length>0&&_!=="max_tokens")for(let v of g){let E=v.function?.arguments||"";if(E&&E.trim())try{JSON.parse(E);}catch{let L=new Error(`Stream incomplete: tool arguments truncated for ${v.function?.name}`);throw L.code="STREAM_INCOMPLETE",L.isNetworkInterrupt=!0,L.toolName=v.function?.name,this.debugLog("Tool arguments truncated",{toolName:v.function?.name,argsLength:E.length,argsPreview:E.substring(0,100)}),L}}else if(_==="max_tokens"&&g.length>0){let v=g[g.length-1],E=v?.function?.arguments||"";try{JSON.parse(E);}catch{this.debugLog("Tool arguments truncated due to max_tokens (expected)",{toolName:v?.function?.name,argsLength:E.length}),m.warn("Anthropic",`\u26A0\uFE0F Tool call ${v?.function?.name} arguments truncated due to max_tokens. The tool call will be incomplete.`);}}this.debugLog("finalUsage before build",y);let j=this.buildUsageFromRaw(y);this.debugLog("usage after build",j),!b&&g.length===0&&m.warn("Anthropic",`\u26A0\uFE0F Stream completed with no content! duration: ${R}ms, usage: ${JSON.stringify(y)}`),ge.llmResponse("anthropic-stream",R,j||{},{}),this.debugLog("Stream complete",{duration:`${R}ms`}),yield {choices:[{delta:{},finish_reason:"stop",index:0}],...j?{usage:j}:{},...F.length>0?{thinking_blocks:F}:{}};return}catch(u){await this.normalizeAxiosStreamError(u);let d=ft(u);this.debugLog("Stream error",{message:u.message,category:d.category,retryable:d.retryable});let p=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",h=`${this.baseUrl}${p}`,g=Ft(h,this.buildHeaders(),c,false);if(m.error("CURL","=== [chatStreamed catch] Stream Error - Full Request CURL ==="),m.error("CURL",g),m.error("CURL",`=== Error: ${d.message} ===`),ge.llmError("anthropic-stream",u),this.isCacheControlError(u)&&!i){i=true,this.disableCaching=true,this.debugLog("Cache control not supported, disabling caching for retry",{errorMessage:u.message,attempt:r+1}),m.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(d.retryable&&r<n){r++;let f=Bi(u.response?.headers),b=hr(d.category,r,f||d.retryAfter),y=d.category==="retryable_rate_limit",w=d.category==="retryable_stream";this.debugLog("Stream retrying",{delay:nt(b),attempt:`${r}/${n}`,isRateLimit:y,isStreamIncomplete:w}),yield {type:"stream_retry",error:d.message,errorCode:d.code,attempt:r,maxRetries:n,delayMs:b,isRateLimit:y,isNetworkError:w};try{await As(b,t.signal);}catch(C){throw C?.name==="AbortError"&&this.debugLog("Stream retry interrupted by user"),C}this.debugLog("Stream retry starting",{attempt:r}),yield {type:"stream_recovered",attempt:r,maxRetries:n};continue}throw d}}}buildPayload(e,t){let s=t.model||this.defaultModel,{system:n,anthropicMessages:r}=this.convertMessages(e,t),i=r,o=[];if(t.disableCaching?(o.push({type:"text",text:Al}),n&&o.push({type:"text",text:`
1698
+ `);t=d.pop()||"";for(let p of d){let h=p.trim();if(!h||!h.startsWith("data: "))continue;let g=h.slice(6);if(g!=="[DONE]")try{let f=JSON.parse(g);if(process.env.CLI_DEBUG==="1"){let b=JSON.stringify(f).substring(0,80);m.debug("SSE",`${f.type.padEnd(20)} ${b}${JSON.stringify(f).length>80?"...":""}`);}switch(f.type){case "message_start":o=f.message?.id||"",i=f.message?.usage;break;case "content_block_start":if(f.content_block?.type==="tool_use"){let b=f.content_block,y=this.isProxyMode?El[b.name]||this.fromClaudeCodeToolName(b.name):b.name;n.push({id:b.id,type:"function",function:{name:y,arguments:""}});}break;case "content_block_delta":f.delta?.type==="text_delta"?s+=f.delta.text||"":f.delta?.type==="input_json_delta"?n.length>0&&(n[n.length-1].function.arguments+=f.delta.partial_json||""):f.delta?.type==="thinking_delta"&&(r+=f.delta.thinking||"");break;case "message_delta":f.usage&&(i={...i,...f.usage});break}}catch(f){process.env.CLI_DEBUG==="1"&&m.warn("Anthropic",`Stream parse error: ${f}, data: ${g.substring(0,200)}`);}}}let l=this.buildUsageFromRaw(i);return {id:o,choices:[{message:{role:"assistant",content:s||"",tool_calls:n.length>0?n:void 0,...r?{reasoning_content:r}:{}},finish_reason:n.length>0?"tool_calls":"stop"}],usage:l}}async*chatStreamed(e,t={}){let s={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},n=this.retryConfig.streamMaxRetries,r=0,i=s.disableCaching||false,o=true;for(;;){let l={...s,...i?{disableCaching:true}:{}},c=this.buildPayload(e,l);c.stream=true,o&&(this.logRequest(t.model||this.defaultModel,c,true),o=false);try{let u=Date.now(),d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",p=await this.client.post(d,c,{responseType:"stream",signal:t.signal});if(this.debugLog("Stream started",{status:p.status}),p.status!==200){let v="";for await(let A of p.data)v+=A.toString();let E=`${this.baseUrl}${d}`,P=Ft(E,this.buildHeaders(),c,!1);m.error("CURL","=== [chatStreamed] API Error - Full Request CURL ==="),m.error("CURL",P),m.error("CURL",`=== Error Headers: ${Gp(p.headers)} ===`),m.error("CURL",`=== Error Response: ${v.substring(0,1e3)} ===`);let I=new Error(`Anthropic API error: ${p.status}`);I.response={status:p.status,headers:p.headers,data:v};try{let A=JSON.parse(v);I.response.data=A,A.error?.message?I.message=`Anthropic API error: ${p.status} - ${A.error.message}`:A.message&&(I.message=`Anthropic API error: ${p.status} - ${A.message}`),this.debugLog("API Error Details (stream)",A);}catch{this.debugLog("API Error (non-JSON, stream)",{status:p.status,dataLength:v.length});}throw I}let h="",g=[],f=0,b=!1,y=null,w=!1,C=Date.now(),k=0,T=0,_=null,M=null,F=[],x=null;for await(let v of this.createTimeoutStream(p.data,t.signal)){C=Date.now();let E=v.toString();h+=E;let P=h.split(/\n\n+/);h=P.pop()||"";for(let I of P){let A=I.split(`
1699
+ `),O="";for(let $ of A){let D=$.trim();if(D&&!D.startsWith("event:"))if(D.startsWith("data:")){let N=D.slice(5);N.startsWith(" ")&&(N=N.slice(1)),O+=N;}else O+=D;}if(!(!O||O==="[DONE]"))try{let $=O.trim(),D=JSON.parse($);if(process.env.CLI_DEBUG==="1"){let G=JSON.stringify(D).substring(0,80);m.debug("SSE",`${D.type.padEnd(20)} ${G}${JSON.stringify(D).length>80?"...":""}`);}let N=Date.now(),L=this.handleStreamEvent(D,g,f,b,y);if(process.env.CLI_DEBUG==="1"){let G=Date.now()-N;G>50&&m.warn("SSE",`\u26A0\uFE0F Slow event handling: ${D.type} took ${G}ms`);}if(L.yield){let G=Date.now();if(yield L.yield,process.env.CLI_DEBUG==="1"){let z=Date.now()-G;z>100&&m.warn("SSE",`\u26A0\uFE0F Slow yield consumer: ${D.type} yield took ${z}ms`);}}if(L.roleSent!==void 0&&(b=L.roleSent),L.incrementToolIndex&&f++,L.usage&&(y=L.usage),L.error)throw new Error(L.error);L.contentBlockStart&&(T++,L.blockType&&(M=L.blockType)),L.contentBlockStop&&(k++,M==="thinking"&&(yield {choices:[{delta:{reasoning_complete:!0},index:0}]}),M=null),L.messageStop&&(w=!0),L.stopReason&&(_=L.stopReason),D.type==="content_block_start"?D.content_block?.type==="thinking"?x={type:"thinking",thinking:"",signature:""}:D.content_block?.type==="redacted_thinking"&&F.push({type:"redacted_thinking",data:D.content_block.data}):D.type==="content_block_delta"?x&&(D.delta?.type==="thinking_delta"?x.thinking+=D.delta.thinking||"":D.delta?.type==="signature_delta"&&(x.signature+=D.delta.signature||"")):D.type==="content_block_stop"&&x&&(F.push({type:x.type,thinking:x.thinking,signature:x.signature}),x=null);}catch{}}}let R=Date.now()-u;if(this.debugLog("Stream completion check",{messageStopReceived:w,stopReason:_,contentBlocksStarted:T,contentBlocksCompleted:k,toolCallsCount:g.length,duration:`${R}ms`}),!w&&!_){let v=new Error(`Stream incomplete: message_stop not received (blocks: ${T} started, ${k} completed)`);throw v.code="STREAM_INCOMPLETE",v.isNetworkInterrupt=!0,this.debugLog("Stream incomplete detected",{messageStopReceived:w,stopReason:_,contentBlocksStarted:T,contentBlocksCompleted:k,toolCallsCount:g.length,duration:`${R}ms`}),v}if(T!==k)if(_==="max_tokens")this.debugLog("Content blocks mismatch due to max_tokens (expected, not an error)",{contentBlocksStarted:T,contentBlocksCompleted:k,stopReason:_}),m.warn("Anthropic","\u26A0\uFE0F Response truncated due to max_tokens limit. Consider increasing max_tokens or breaking down the task.");else {let v=new Error(`Stream incomplete: content blocks mismatch (${T} started, ${k} completed)`);throw v.code="STREAM_INCOMPLETE",v.isNetworkInterrupt=!0,this.debugLog("Content blocks mismatch",{contentBlocksStarted:T,contentBlocksCompleted:k,stopReason:_}),v}if(g.length>0&&_!=="max_tokens")for(let v of g){let E=v.function?.arguments||"";if(E&&E.trim())try{JSON.parse(E);}catch{let P=new Error(`Stream incomplete: tool arguments truncated for ${v.function?.name}`);throw P.code="STREAM_INCOMPLETE",P.isNetworkInterrupt=!0,P.toolName=v.function?.name,this.debugLog("Tool arguments truncated",{toolName:v.function?.name,argsLength:E.length,argsPreview:E.substring(0,100)}),P}}else if(_==="max_tokens"&&g.length>0){let v=g[g.length-1],E=v?.function?.arguments||"";try{JSON.parse(E);}catch{this.debugLog("Tool arguments truncated due to max_tokens (expected)",{toolName:v?.function?.name,argsLength:E.length}),m.warn("Anthropic",`\u26A0\uFE0F Tool call ${v?.function?.name} arguments truncated due to max_tokens. The tool call will be incomplete.`);}}this.debugLog("finalUsage before build",y);let j=this.buildUsageFromRaw(y);this.debugLog("usage after build",j),!b&&g.length===0&&m.warn("Anthropic",`\u26A0\uFE0F Stream completed with no content! duration: ${R}ms, usage: ${JSON.stringify(y)}`),ge.llmResponse("anthropic-stream",R,j||{},{}),this.debugLog("Stream complete",{duration:`${R}ms`}),yield {choices:[{delta:{},finish_reason:"stop",index:0}],...j?{usage:j}:{},...F.length>0?{thinking_blocks:F}:{}};return}catch(u){await this.normalizeAxiosStreamError(u);let d=ft(u);this.debugLog("Stream error",{message:u.message,category:d.category,retryable:d.retryable});let p=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",h=`${this.baseUrl}${p}`,g=Ft(h,this.buildHeaders(),c,false);if(m.error("CURL","=== [chatStreamed catch] Stream Error - Full Request CURL ==="),m.error("CURL",g),m.error("CURL",`=== Error: ${d.message} ===`),ge.llmError("anthropic-stream",u),this.isCacheControlError(u)&&!i){i=true,this.disableCaching=true,this.debugLog("Cache control not supported, disabling caching for retry",{errorMessage:u.message,attempt:r+1}),m.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(d.retryable&&r<n){r++;let f=Bi(u.response?.headers),b=hr(d.category,r,f||d.retryAfter),y=d.category==="retryable_rate_limit",w=d.category==="retryable_stream";this.debugLog("Stream retrying",{delay:nt(b),attempt:`${r}/${n}`,isRateLimit:y,isStreamIncomplete:w}),yield {type:"stream_retry",error:d.message,errorCode:d.code,attempt:r,maxRetries:n,delayMs:b,isRateLimit:y,isNetworkError:w};try{await As(b,t.signal);}catch(C){throw C?.name==="AbortError"&&this.debugLog("Stream retry interrupted by user"),C}this.debugLog("Stream retry starting",{attempt:r}),yield {type:"stream_recovered",attempt:r,maxRetries:n};continue}throw d}}}buildPayload(e,t){let s=t.model||this.defaultModel,{system:n,anthropicMessages:r}=this.convertMessages(e,t),i=r,o=[];if(t.disableCaching?(o.push({type:"text",text:Al}),n&&o.push({type:"text",text:`
1700
1700
  `+n})):(o.push({type:"text",text:Al,cache_control:{type:"ephemeral"}}),n&&o.push({type:"text",text:`
1701
1701
  `+n,cache_control:{type:"ephemeral"}})),process.env.CLI_DEBUG==="1"&&n){let c=["## \u9879\u76EE\u8BB0\u5FC6","## \u4E0A\u6B21\u4EFB\u52A1\u6458\u8981","## Project Memory","## Last Run Summary"],u=c.some(h=>n.includes(h)),d=c.reduce((h,g)=>h>=0?h:n.indexOf(g),-1),p=d>=0?n.slice(d,d+300):void 0;m.info("MEMORY_INJECT","Anthropic system memory check",{hasMemory:u,systemLength:n.length,snippet:p});}let l={model:this.normalizeModelName(s),system:o,metadata:this.buildMetadata(t.metadata),max_tokens:this.maxTokens};return (!t.thinking?.type||t.thinking.type==="disabled")&&(l.temperature=t.temperature??.7),l.stream=true,l.messages=i,t.tools?.length&&(l.tools=this.buildToolsPayload(t.tools,t)),t.webSearch?.enabled&&(l.tools=l.tools||[],l.tools.push(this.buildWebSearchTool(t.webSearch))),l.tools?.length>0&&this.ensureLastToolCacheControl(l.tools,t),this.shouldEnableThinking(s,t)&&(l.thinking=this.buildThinkingPayload(t),delete l.temperature,l.temperature=1),this.checkRequestBudget(l),l}checkRequestBudget(e){let s=JSON.stringify(e).length;if(s>Sr){if(this.debugLog("Request body exceeds limit",{bodySize:s,limit:Sr,messageCount:e.messages?.length||0}),e.messages){let r=[...e.messages.map((i,o)=>({index:o,role:i.role,contentSize:JSON.stringify(i.content||"").length}))].sort((i,o)=>o.contentSize-i.contentSize);this.debugLog("Largest messages in request",{top5:r.slice(0,5)});}console.warn(`[Anthropic] \u26A0\uFE0F Request body size (${(s/1024/1024).toFixed(2)}MB) exceeds ${(Sr/1024/1024).toFixed(1)}MB limit. Request may fail.`);}else s>iw&&this.debugLog("Request body approaching limit",{bodySize:s,limit:Sr,percentage:(s/Sr*100).toFixed(1)+"%"});}mergeSystemIntoMessages(e,t){let s=[...t],n=s.findIndex(r=>r.role==="user");if(n>=0){let r=s[n],i={type:"text",text:`<system_context>
1702
1702
  ${e}
@@ -1809,9 +1809,9 @@ ${e.join(`
1809
1809
 
1810
1810
  Provide a comprehensive summary:`}function Tr(a){let t=me(a.content).length,s=a.tool_calls?JSON.stringify(a.tool_calls).length:0;return Math.ceil((t+s)/4)}function Pl(a,e){return a.length<=e?a:a.slice(0,e-1).trimEnd()+"\u2026"}function xw(a){return a.replace(/\s+/g," ").trim()}function Ml(a,e){if(a.length===0)return {summary:"",lines:0};let t=[];for(let n of a){if(t.length>=bw)break;let r=n.role==="assistant"?"Assistant":n.role==="user"?"User":n.role,i=me(n.content),l=(i?xw(i):"")||(n.tool_calls?.length?`Tool calls: ${n.tool_calls.map(c=>c.function.name).join(", ")}`:"No textual content");t.push(`- [${r}] ${Pl(l,vw)}`);}return {summary:`${e}
1811
1811
  ${t.join(`
1812
- `)}`,lines:t.length}}async function Dl(a){let{session:e,profile:t,llmProvider:s,model:n,onProgress:r,timeout:i=6e4,signal:o}=a,l=a.tailTokenBudget??t.tailTokenBudget??2e4;if(!l||l<=0)return null;r?.("analyzing","Analyzing conversation history...");let c=await e.getTimeline(),u=c.map((D,G)=>({entry:D,index:G})).filter(({entry:D})=>D.item.type==="message");if(u.length===0)return null;u.filter(({entry:D})=>D.item.data.role==="system");let p=u.filter(({entry:D})=>D.item.data.role!=="system");if(p.length===0)return null;let h=0,g=p.length;for(let D=p.length-1;D>=0;D--){let G=p[D].entry.item.data;if(h+=Tr(G),h>=l){g=D;break}}if(g>=p.length){if(p.length<=2)return null;g=Math.floor(p.length/2);}let f=p.slice(0,g).map(({entry:D})=>D.item.data);if(f.length===0)return null;let b={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let D of f){let G=Tr(D);D.role==="user"?b.userTokens+=G:D.role==="assistant"?b.assistantTokens+=G:D.role==="tool"&&(b.toolTokens+=G),b.totalTokens+=G;}let y=p.slice(g).map(({entry:D})=>D.item.data),w={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let D of y){let G=Tr(D);D.role==="user"?w.userTokens+=G:D.role==="assistant"?w.assistantTokens+=G:D.role==="tool"&&(w.toolTokens+=G),w.totalTokens+=G;}let C=b.totalTokens;r?.("summarizing",`Summarizing ${f.length} messages with AI...`);let k=kw(f),T=k==="zh"?Cw:ww,_=Sw(f),M,F;try{let D=new AbortController,G=setTimeout(()=>D.abort(),i),z=o?AbortSignal.any([o,D.signal]):D.signal;try{let oe=await s.chat([{role:"system",content:T},{role:"user",content:_}],{model:n,temperature:.3,signal:z});clearTimeout(G),M=me(oe.choices[0]?.message?.content)||"",F=oe.usage?.total_tokens;}catch(oe){throw clearTimeout(G),oe?.name==="AbortError"||oe?.code==="ABORT_ERR"?console.warn("[SmartCompact] LLM call timed out or was cancelled, falling back to lightweight"):console.error("[SmartCompact] LLM call failed:",oe.message),oe}if(!M.trim()){console.warn("[SmartCompact] LLM returned empty summary, falling back to lightweight");let{summary:oe}=Ml(f,Il);M=oe;}}catch(D){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",D.message);let{summary:G}=Ml(f,Il);M=G;}r?.("saving","Saving compacted history...");let R=`${k==="zh"?"# \u5BF9\u8BDD\u5386\u53F2\u6458\u8981\uFF08AI \u751F\u6210\uFF09":"# Conversation Summary (AI Generated)"}
1812
+ `)}`,lines:t.length}}async function Dl(a){let{session:e,profile:t,llmProvider:s,model:n,onProgress:r,timeout:i=6e4,signal:o}=a,l=a.tailTokenBudget??t.tailTokenBudget??2e4;if(!l||l<=0)return null;r?.("analyzing","Analyzing conversation history...");let c=await e.getTimeline(),u=c.map((L,G)=>({entry:L,index:G})).filter(({entry:L})=>L.item.type==="message");if(u.length===0)return null;u.filter(({entry:L})=>L.item.data.role==="system");let p=u.filter(({entry:L})=>L.item.data.role!=="system");if(p.length===0)return null;let h=0,g=p.length;for(let L=p.length-1;L>=0;L--){let G=p[L].entry.item.data;if(h+=Tr(G),h>=l){g=L;break}}if(g>=p.length){if(p.length<=2)return null;g=Math.floor(p.length/2);}let f=p.slice(0,g).map(({entry:L})=>L.item.data);if(f.length===0)return null;let b={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let L of f){let G=Tr(L);L.role==="user"?b.userTokens+=G:L.role==="assistant"?b.assistantTokens+=G:L.role==="tool"&&(b.toolTokens+=G),b.totalTokens+=G;}let y=p.slice(g).map(({entry:L})=>L.item.data),w={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let L of y){let G=Tr(L);L.role==="user"?w.userTokens+=G:L.role==="assistant"?w.assistantTokens+=G:L.role==="tool"&&(w.toolTokens+=G),w.totalTokens+=G;}let C=b.totalTokens;r?.("summarizing",`Summarizing ${f.length} messages with AI...`);let k=kw(f),T=k==="zh"?Cw:ww,_=Sw(f),M,F;try{let L=new AbortController,G=setTimeout(()=>L.abort(),i),z=o?AbortSignal.any([o,L.signal]):L.signal;try{let oe=await s.chat([{role:"system",content:T},{role:"user",content:_}],{model:n,temperature:.3,signal:z});clearTimeout(G),M=me(oe.choices[0]?.message?.content)||"",F=oe.usage?.total_tokens;}catch(oe){throw clearTimeout(G),oe?.name==="AbortError"||oe?.code==="ABORT_ERR"?console.warn("[SmartCompact] LLM call timed out or was cancelled, falling back to lightweight"):console.error("[SmartCompact] LLM call failed:",oe.message),oe}if(!M.trim()){console.warn("[SmartCompact] LLM returned empty summary, falling back to lightweight");let{summary:oe}=Ml(f,Il);M=oe;}}catch(L){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",L.message);let{summary:G}=Ml(f,Il);M=G;}r?.("saving","Saving compacted history...");let R=`${k==="zh"?"# \u5BF9\u8BDD\u5386\u53F2\u6458\u8981\uFF08AI \u751F\u6210\uFF09":"# Conversation Summary (AI Generated)"}
1813
1813
 
1814
- ${M}`,j=u.length-f.length,v=u[0]?.entry.timestamp??Date.now(),E={item:{type:"message",data:{role:"user",content:R,name:"SmartCompactSummary"}},timestamp:v,seq:0},L={item:{type:"compacted",data:{summary:Pl(M,2e3),originalCount:f.length,compactedAt:new Date().toISOString(),method:"smart",llmTokensUsed:F}},timestamp:v,seq:0},I=[],A=false,O=new Set(p.slice(0,g).map(({entry:D})=>D));for(let D of c){if(D.item.type!=="message"){I.push({...D});continue}if(D.item.data.role==="system"){I.push({...D});continue}O.has(D)?A||(I.push({...E}),I.push({...L}),A=true):I.push({...D});}if(!A)return null;let $=I.map((D,G)=>({item:D.item,timestamp:D.timestamp??Date.now(),seq:G}));await e.replaceTimeline($);let P=Tr({content:R}),N={before:b,after:{userTokens:w.userTokens,assistantTokens:w.assistantTokens,toolTokens:w.toolTokens,summaryTokens:P,totalTokens:w.totalTokens+P},saved:{userTokens:b.userTokens,assistantTokens:b.assistantTokens,toolTokens:b.toolTokens,totalTokens:b.totalTokens-P}};return {removedMessages:f.length,keptMessages:j,summaryText:R,estimatedTokensSaved:C,llmTokensUsed:F,detailedStats:N}}async function Vp(a){let{session:e,profile:t}=a,s=a.tailTokenBudget??t.tailTokenBudget??2e4;if(!s||s<=0)return null;let n=await e.getTimeline(),r=n.map((T,_)=>({entry:T,index:_})).filter(({entry:T})=>T.item.type==="message");if(r.length===0)return null;r.filter(({entry:T})=>T.item.data.role==="system");let o=r.filter(({entry:T})=>T.item.data.role!=="system");if(o.length===0)return null;let l=0,c=o.length;for(let T=o.length-1;T>=0;T--){let _=o[T].entry.item.data;if(l+=Tr(_),l>=s){c=T;break}}if(c>=o.length){if(o.length<=2)return null;c=Math.floor(o.length/2);}let u=o.slice(0,c).map(({entry:T})=>T.item.data);if(u.length===0)return null;let{summary:d,lines:p}=Ml(u,a.summaryHeader??Il);if(!d.trim())return null;let h=o.length-u.length,g=o[0]?.entry.timestamp??Date.now(),f={item:{type:"message",data:{role:"user",content:d,name:"CompatSummary"}},timestamp:g,seq:0},b={item:{type:"compacted",data:{summary:Pl(d,2e3),originalCount:u.length,compactedAt:new Date().toISOString()}},timestamp:g,seq:0},y=[],w=false,C=new Set(o.slice(0,c).map(({entry:T})=>T));for(let T of n){if(T.item.type!=="message"){y.push({...T});continue}if(T.item.data.role==="system"){y.push({...T});continue}C.has(T)?w||(y.push({...f}),y.push({...b}),w=true):y.push({...T});}if(!w)return null;let k=y.map((T,_)=>({item:T.item,timestamp:T.timestamp??Date.now(),seq:_}));return await e.replaceTimeline(k),{removedMessages:u.length,keptMessages:h,summaryText:d,summaryLines:p}}function Yp(a){if(!a.startsWith("mcp__"))return null;let e=a.split("__");if(e.length<3)return null;let t=e[1],s=e.slice(2).join("__");return !t||!s?null:{serverId:t,toolName:s}}var lo=class{extractFromAssistantMessage(e,t){if(!e||e.length===0)return;let s=[/I(?:'ll| will) (\w+.*?) to (.*?)(?:\.|$)/i,/Let me (\w+.*?) to (.*?)(?:\.|$)/i,/(?:I'm|I am) going to (\w+.*?) to (.*?)(?:\.|$)/i,/(?:I'm|I am) (\w+ing.*?) to (.*?)(?:\.|$)/i,/To (.*?)[,,] I(?:'ll| will) (\w+.*?)(?:\.|$)/i,/(?:First|Now|Next|Then)[,,] (?:I'll |I will |let me )?(\w+.*?)(?:\.|$)/i,/(?:我将|我会|让我)([^。,,]+)(?:来|以便|用于)([^。,,]+)/,/(?:首先|现在|接下来|然后)[,,](?:我将|我会|让我)?([^。,,]+)/];for(let i of s){let o=e.match(i);if(o){let l=o[2]||o[1];if(l&&l.length>0&&l.length<200)return l.trim()}}let n=t.toLowerCase(),r=e.split(/[.。!!??]/);for(let i of r)if(i.toLowerCase().includes(n)||i.toLowerCase().includes("read")||i.toLowerCase().includes("search")||i.toLowerCase().includes("file")){let o=i.trim();if(o.length>10&&o.length<200)return o}}extractActionFromToolName(e){return {readfile:"read",write_file:"write",create_file:"create",edit_file:"edit",Edit:"edit",search:"search",list_directory:"list",LS:"list",Glob:"find",find_files:"find",Execute:"execute",execute:"execute"}[e]||e.toLowerCase()}},co=class{generateEquivalentCommand(e,t){switch(e){case "search":return this.generateSearchCommand(t);case "Glob":case "find_files":return this.generateFindCommand(t);case "Execute":case "execute":return this.generateExecuteCommand(t);case "readfile":return this.generateReadCommand(t);case "list_directory":case "LS":return this.generateLsCommand(t);case "write_file":case "create_file":return this.generateWriteCommand(t);default:return}}generateSearchCommand(e){let t="rg";e.case_insensitive&&(t+=" -i"),e.line_numbers&&(t+=" -n"),e.context_lines?t+=` -C ${e.context_lines}`:e.context?t+=` -C ${e.context}`:(e.context_before&&(t+=` -B ${e.context_before}`),e.context_after&&(t+=` -A ${e.context_after}`));let s=e.pattern||"";t+=` "${this.escapeShellArg(s)}"`;let n=e.path||e.directory||".";return t+=` ${this.escapeShellPath(n)}`,e.type&&(t+=` --type=${e.type}`),e.file_pattern?t+=` -g "${this.escapeShellArg(e.file_pattern)}"`:e.glob_pattern&&(t+=` -g "${this.escapeShellArg(e.glob_pattern)}"`),t}generateFindCommand(e){let t="find",s=e.folder||e.path||".";if(t+=` ${this.escapeShellPath(s)}`,e.patterns&&Array.isArray(e.patterns)&&e.patterns.length>0)if(e.patterns.length===1)t+=` -name "${this.escapeShellArg(e.patterns[0])}"`;else {let n=e.patterns.map(r=>`-name "${this.escapeShellArg(r)}"`).join(" -o ");t+=` \\( ${n} \\)`;}return e.excludePatterns&&Array.isArray(e.excludePatterns)&&e.excludePatterns.forEach(n=>{t+=` ! -path "${this.escapeShellArg(n)}"`;}),e.maxDepth&&(t+=` -maxdepth ${e.maxDepth}`),e.type==="f"?t+=" -type f":e.type==="d"&&(t+=" -type d"),t}generateExecuteCommand(e){return e.command||""}generateReadCommand(e){let t=e.path||e.file_path||e.filename||"";if(e.start_line&&e.num_lines){let s=e.start_line+e.num_lines-1;return `sed -n '${e.start_line},${s}p' ${this.escapeShellPath(t)}`}return e.num_lines&&!e.start_line?`head -n ${e.num_lines} ${this.escapeShellPath(t)}`:`cat ${this.escapeShellPath(t)}`}generateLsCommand(e){let t="ls";(e.all||e.show_hidden)&&(t+=" -a"),(e.long||e.detailed)&&(t+=" -l"),t.includes("-")||(t+=" -la");let s=e.path||e.directory||e.directory_path||".";return t+=` ${this.escapeShellPath(s)}`,t}generateWriteCommand(e){let t=e.path||e.file_path||e.filename||"",s=e.content||"";return s.length<100&&!s.includes(`
1814
+ ${M}`,j=u.length-f.length,v=u[0]?.entry.timestamp??Date.now(),E={item:{type:"message",data:{role:"user",content:R,name:"SmartCompactSummary"}},timestamp:v,seq:0},P={item:{type:"compacted",data:{summary:Pl(M,2e3),originalCount:f.length,compactedAt:new Date().toISOString(),method:"smart",llmTokensUsed:F}},timestamp:v,seq:0},I=[],A=false,O=new Set(p.slice(0,g).map(({entry:L})=>L));for(let L of c){if(L.item.type!=="message"){I.push({...L});continue}if(L.item.data.role==="system"){I.push({...L});continue}O.has(L)?A||(I.push({...E}),I.push({...P}),A=true):I.push({...L});}if(!A)return null;let $=I.map((L,G)=>({item:L.item,timestamp:L.timestamp??Date.now(),seq:G}));await e.replaceTimeline($);let D=Tr({content:R}),N={before:b,after:{userTokens:w.userTokens,assistantTokens:w.assistantTokens,toolTokens:w.toolTokens,summaryTokens:D,totalTokens:w.totalTokens+D},saved:{userTokens:b.userTokens,assistantTokens:b.assistantTokens,toolTokens:b.toolTokens,totalTokens:b.totalTokens-D}};return {removedMessages:f.length,keptMessages:j,summaryText:R,estimatedTokensSaved:C,llmTokensUsed:F,detailedStats:N}}async function Vp(a){let{session:e,profile:t}=a,s=a.tailTokenBudget??t.tailTokenBudget??2e4;if(!s||s<=0)return null;let n=await e.getTimeline(),r=n.map((T,_)=>({entry:T,index:_})).filter(({entry:T})=>T.item.type==="message");if(r.length===0)return null;r.filter(({entry:T})=>T.item.data.role==="system");let o=r.filter(({entry:T})=>T.item.data.role!=="system");if(o.length===0)return null;let l=0,c=o.length;for(let T=o.length-1;T>=0;T--){let _=o[T].entry.item.data;if(l+=Tr(_),l>=s){c=T;break}}if(c>=o.length){if(o.length<=2)return null;c=Math.floor(o.length/2);}let u=o.slice(0,c).map(({entry:T})=>T.item.data);if(u.length===0)return null;let{summary:d,lines:p}=Ml(u,a.summaryHeader??Il);if(!d.trim())return null;let h=o.length-u.length,g=o[0]?.entry.timestamp??Date.now(),f={item:{type:"message",data:{role:"user",content:d,name:"CompatSummary"}},timestamp:g,seq:0},b={item:{type:"compacted",data:{summary:Pl(d,2e3),originalCount:u.length,compactedAt:new Date().toISOString()}},timestamp:g,seq:0},y=[],w=false,C=new Set(o.slice(0,c).map(({entry:T})=>T));for(let T of n){if(T.item.type!=="message"){y.push({...T});continue}if(T.item.data.role==="system"){y.push({...T});continue}C.has(T)?w||(y.push({...f}),y.push({...b}),w=true):y.push({...T});}if(!w)return null;let k=y.map((T,_)=>({item:T.item,timestamp:T.timestamp??Date.now(),seq:_}));return await e.replaceTimeline(k),{removedMessages:u.length,keptMessages:h,summaryText:d,summaryLines:p}}function Yp(a){if(!a.startsWith("mcp__"))return null;let e=a.split("__");if(e.length<3)return null;let t=e[1],s=e.slice(2).join("__");return !t||!s?null:{serverId:t,toolName:s}}var lo=class{extractFromAssistantMessage(e,t){if(!e||e.length===0)return;let s=[/I(?:'ll| will) (\w+.*?) to (.*?)(?:\.|$)/i,/Let me (\w+.*?) to (.*?)(?:\.|$)/i,/(?:I'm|I am) going to (\w+.*?) to (.*?)(?:\.|$)/i,/(?:I'm|I am) (\w+ing.*?) to (.*?)(?:\.|$)/i,/To (.*?)[,,] I(?:'ll| will) (\w+.*?)(?:\.|$)/i,/(?:First|Now|Next|Then)[,,] (?:I'll |I will |let me )?(\w+.*?)(?:\.|$)/i,/(?:我将|我会|让我)([^。,,]+)(?:来|以便|用于)([^。,,]+)/,/(?:首先|现在|接下来|然后)[,,](?:我将|我会|让我)?([^。,,]+)/];for(let i of s){let o=e.match(i);if(o){let l=o[2]||o[1];if(l&&l.length>0&&l.length<200)return l.trim()}}let n=t.toLowerCase(),r=e.split(/[.。!!??]/);for(let i of r)if(i.toLowerCase().includes(n)||i.toLowerCase().includes("read")||i.toLowerCase().includes("search")||i.toLowerCase().includes("file")){let o=i.trim();if(o.length>10&&o.length<200)return o}}extractActionFromToolName(e){return {readfile:"read",write_file:"write",create_file:"create",edit_file:"edit",Edit:"edit",search:"search",list_directory:"list",LS:"list",Glob:"find",find_files:"find",Execute:"execute",execute:"execute"}[e]||e.toLowerCase()}},co=class{generateEquivalentCommand(e,t){switch(e){case "search":return this.generateSearchCommand(t);case "Glob":case "find_files":return this.generateFindCommand(t);case "Execute":case "execute":return this.generateExecuteCommand(t);case "readfile":return this.generateReadCommand(t);case "list_directory":case "LS":return this.generateLsCommand(t);case "write_file":case "create_file":return this.generateWriteCommand(t);default:return}}generateSearchCommand(e){let t="rg";e.case_insensitive&&(t+=" -i"),e.line_numbers&&(t+=" -n"),e.context_lines?t+=` -C ${e.context_lines}`:e.context?t+=` -C ${e.context}`:(e.context_before&&(t+=` -B ${e.context_before}`),e.context_after&&(t+=` -A ${e.context_after}`));let s=e.pattern||"";t+=` "${this.escapeShellArg(s)}"`;let n=e.path||e.directory||".";return t+=` ${this.escapeShellPath(n)}`,e.type&&(t+=` --type=${e.type}`),e.file_pattern?t+=` -g "${this.escapeShellArg(e.file_pattern)}"`:e.glob_pattern&&(t+=` -g "${this.escapeShellArg(e.glob_pattern)}"`),t}generateFindCommand(e){let t="find",s=e.folder||e.path||".";if(t+=` ${this.escapeShellPath(s)}`,e.patterns&&Array.isArray(e.patterns)&&e.patterns.length>0)if(e.patterns.length===1)t+=` -name "${this.escapeShellArg(e.patterns[0])}"`;else {let n=e.patterns.map(r=>`-name "${this.escapeShellArg(r)}"`).join(" -o ");t+=` \\( ${n} \\)`;}return e.excludePatterns&&Array.isArray(e.excludePatterns)&&e.excludePatterns.forEach(n=>{t+=` ! -path "${this.escapeShellArg(n)}"`;}),e.maxDepth&&(t+=` -maxdepth ${e.maxDepth}`),e.type==="f"?t+=" -type f":e.type==="d"&&(t+=" -type d"),t}generateExecuteCommand(e){return e.command||""}generateReadCommand(e){let t=e.path||e.file_path||e.filename||"";if(e.start_line&&e.num_lines){let s=e.start_line+e.num_lines-1;return `sed -n '${e.start_line},${s}p' ${this.escapeShellPath(t)}`}return e.num_lines&&!e.start_line?`head -n ${e.num_lines} ${this.escapeShellPath(t)}`:`cat ${this.escapeShellPath(t)}`}generateLsCommand(e){let t="ls";(e.all||e.show_hidden)&&(t+=" -a"),(e.long||e.detailed)&&(t+=" -l"),t.includes("-")||(t+=" -la");let s=e.path||e.directory||e.directory_path||".";return t+=` ${this.escapeShellPath(s)}`,t}generateWriteCommand(e){let t=e.path||e.file_path||e.filename||"",s=e.content||"";return s.length<100&&!s.includes(`
1815
1815
  `)?`echo "${this.escapeShellArg(s)}" > ${this.escapeShellPath(t)}`:`# Use editor to create ${t}`}escapeShellArg(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}escapeShellPath(e){return /[\s()[\]{}$`!*?<>|&;]/.test(e)?`"${this.escapeShellArg(e)}"`:e}};function Ds(a,e){let t=["path","file_path","filePath","filename","directory","folder","dir","file","output_path","input_path"];for(let s of t)if(e[s]&&typeof e[s]=="string")return e[s];switch(a){case "Execute":case "execute":if(e.command&&typeof e.command=="string"){let n=e.command,r=n.match(/(?:^|\s)([./~][\w/.-]+\.\w+)(?:\s|$)/);return r?r[1]:n.substring(0,50)+(n.length>50?"...":"")}break;case "search":return e.path||e.directory||".";case "Glob":case "find_files":let s=e.folder||e.path||".";return e.patterns&&Array.isArray(e.patterns)?`${s} (${e.patterns.join(", ")})`:s;case "read_multiple_files":if(e.files&&Array.isArray(e.files))return e.files.length>1?`${e.files.length} files`:e.files[0];break}}function Xp(a,e){let t=Yp(a);if(t)return `MCP ${t.serverId}/${t.toolName}`;switch(a){case "readfile":let s=Ds(a,e);return s?`Reading ${s}`:"Reading file";case "write_file":case "create_file":let n=Ds(a,e);return n?`Writing ${n}`:"Writing file";case "edit_file":case "Edit":let r=Ds(a,e);return r?`Editing ${r}`:"Editing file";case "search":let i=e.pattern||e.query;return i?`Searching for "${i}"`:"Searching code";case "list_directory":case "LS":return `Listing ${Ds(a,e)||"."}`;case "Glob":case "find_files":return e.patterns&&Array.isArray(e.patterns)?`Finding files: ${e.patterns.join(", ")}`:"Finding files";case "Execute":case "execute":let l=e.command||"";return l.length>60?`Running: ${l.substring(0,60)}...`:`Running: ${l}`;case "read_multiple_files":return e.files&&Array.isArray(e.files)?`Reading ${e.files.length} files`:"Reading multiple files";default:return `Executing ${a}`}}var uo=class{batchTimeWindow;activeBatches=new Map;pendingCalls=new Map;batchableTools=new Set(["readfile","write_file","create_file","list_directory","LS","Glob","find_files","read_multiple_files"]);constructor(e=200){this.batchTimeWindow=e;}detectBatch(e,t,s,n,r){if(!this.isBatchable(t))return {type:"single",merge:false};let i=this.pendingCalls.get(t)||[];if(i.length===0)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:r,args:n}]),{type:"single",merge:false};let o=i[i.length-1];if(r-o.startTime>this.batchTimeWindow)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:r,args:n}]),{type:"single",merge:false};if(i.some(u=>u.targetPath===s))return {type:"single",merge:false};if(i.length===1){let u=this.createBatch(o,e,s,r);return i.push({toolId:e,toolName:t,targetPath:s,startTime:r,args:n}),{type:"batch",merge:false,batchId:u,shouldCreateBatch:true}}else {let u=this.findActiveBatch(t);return u?(i.push({toolId:e,toolName:t,targetPath:s,startTime:r,args:n}),this.updateBatch(u,s,r),{type:"batch",merge:true,batchId:u}):(this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:r,args:n}]),{type:"single",merge:false})}}recordCompletion(e,t){let s=this.findActiveBatch(e);if(s){let n=this.activeBatches.get(s);n&&(n.completed++,n.completed>=n.total&&this.completeBatch(s));}}getBatchInfo(e){return this.activeBatches.get(e)}isBatchable(e){return this.batchableTools.has(e)}createBatch(e,t,s,n){let r=`batch-${e.toolName}-${n}`;return this.activeBatches.set(r,{batchId:r,toolName:e.toolName,targets:[e.targetPath,s],startTime:e.startTime,lastCallTime:n,completed:0,total:2}),r}updateBatch(e,t,s){let n=this.activeBatches.get(e);n&&(n.targets.push(t),n.total++,n.lastCallTime=s);}findActiveBatch(e){for(let[t,s]of this.activeBatches.entries())if(s.toolName===e)return t}completeBatch(e){this.activeBatches.delete(e);let t=this.activeBatches.get(e);t&&this.pendingCalls.delete(t.toolName);}cleanupExpiredBatches(e){let t=this.batchTimeWindow*5,s=[];this.activeBatches.forEach((r,i)=>{e-r.lastCallTime>t&&s.push(i);}),s.forEach(r=>this.completeBatch(r));let n=[];this.pendingCalls.forEach((r,i)=>{if(r.length>0){let o=r[r.length-1];e-o.startTime>t&&n.push(i);}}),n.forEach(r=>this.pendingCalls.delete(r));}reset(){this.activeBatches.clear(),this.pendingCalls.clear();}getStats(){let e=[];return this.activeBatches.forEach((t,s)=>{e.push({batchId:s,toolName:t.toolName,total:t.total,completed:t.completed});}),{activeBatches:this.activeBatches.size,pendingCalls:this.pendingCalls.size,batches:e}}};W();var Tw={default:["Thinking...","Processing...","Analyzing...","Pondering...","Contemplating..."]};var po={};function _w(a,e,t=true){po[e]||(po[e]=0);let s=po[e]%a.length,n=a[s];return t&&(po[e]=(s+1)%a.length),n}function Qp(){let a=Tw.default;return _w(a,"default")}function Zp(a){if(!a||a.trim().length===0)return null;let e=a.trim();if(!e.endsWith("}")){let l=e+"}";try{return JSON.parse(l),console.log("[JsonRepair] Fixed by adding closing }"),l}catch{}}let t=e.replace(/,\s*$/,"");if(!t.endsWith("}")){let l=t+"}";try{return JSON.parse(l),console.log("[JsonRepair] Fixed by removing trailing comma and adding }"),l}catch{}}if(e.lastIndexOf('"')>0){let l=0,c=false;for(let u=0;u<e.length;u++){if(c){c=false;continue}if(e[u]==="\\"){c=true;continue}e[u]==='"'&&l++;}if(l%2===1){let u=e+'"}';try{return JSON.parse(u),console.log("[JsonRepair] Fixed by closing unclosed string"),u}catch{}}}let n=0,r=0,i=false,o=false;for(let l of e){if(o){o=false;continue}if(l==="\\"){o=true;continue}if(l==='"'){i=!i;continue}i||(l==="{"?n++:l==="}"?n--:l==="["?r++:l==="]"&&r--);}for(i&&(e+='"');r>0;)e+="]",r--;for(;n>0;)e+="}",n--;try{return JSON.parse(e),console.log("[JsonRepair] Fixed by force-closing structures"),e}catch{return null}}function em(a,e){if(!e||e.trim().length===0)return {isTruncated:false};if(!e.trim().endsWith("}"))return {isTruncated:true,reason:"JSON structure incomplete - missing closing brace"};if(a==="write_file"||a==="edit_file"){if(!e.includes('"content"')&&!e.includes('"new_string"'))return {isTruncated:true,reason:"File content field is missing - likely truncated during streaming"};let s=e.match(/"content"\s*:\s*"([^]*)/);if(s){let n=s[1],r=0,i=false;for(let o of n){if(i){i=false;continue}if(o==="\\"){i=true;continue}if(o==='"'){r++;break}}if(r===0)return {isTruncated:true,reason:"Content string is unclosed - truncated during streaming"}}}return {isTruncated:false}}function tm(a,e,t){let s=mp(a,e,t),n=Gi(s);return {success:false,error:s.code,code:s.code,category:s.category,message:s.message,suggestion:n,retryable:s.retryable,receivedArgs:e?.substring(0,500)}}var mo=class{state="idle";lastStatusKey="";lastStatusAt=0;shouldEmit(e){if(e.type==="status"){let t=e.timestamp??Date.now(),s=`${e.status}:${e.message}`;if(s===this.lastStatusKey&&t-this.lastStatusAt<200)return false;this.lastStatusKey=s,this.lastStatusAt=t;}return this.transition(e),true}getState(){return this.state}transition(e){switch(e.type){case "thinking":case "reasoning":case "reasoning_complete":case "text":this.state="thinking";return;case "tool_call_start":this.state="tool_running";return;case "tool_call_end":case "tool_output":this.state="thinking";return;case "status":e.status==="tool_call"?this.state="tool_running":e.status==="thinking"?this.state="thinking":e.status==="complete"?this.state="completed":e.status==="error"&&(this.state="error");return;case "run_result":this.state="completed";return;case "error":case "error_classified":this.state="error";return;default:return}}};var nm=12e3,go=class{runner;memory;sessionManager;sessionSync;session;sessionEnabled;memoryPressure;compatProfile;workDir;model;systemPrompt;sandboxSetter;llmProvider;sessionSeed;sessionTotalInputTokens=0;sessionTotalOutputTokens=0;lastMemoryPressureState="unknown";autoCompactionInProgress=false;isRunning=false;shouldInterrupt=false;abortController=null;interruptResolver=null;interruptPromise=null;compressionMode="sync";eventEmitter=new EventEmitter;eventSequence=0;hostStateMachine=new mo;descriptionExtractor=new lo;commandGenerator=new co;lastAssistantMessage="";batchDetector=new uo;toolCallIdCounter=0;recentToolCalls=new Map;currentTaskMetadata;pendingInjectedMessages=[];constructor(e){this.runner=e.runner,this.memory=e.memory,this.sessionManager=e.sessionManager,this.sessionSync=e.sessionSync,this.session=e.session,this.sessionEnabled=e.sessionEnabled??true,this.workDir=te__default.resolve(e.workDir),this.model=e.model,this.systemPrompt=e.systemPrompt,this.memoryPressure=e.memoryPressure,this.compatProfile=e.compatProfile,this.sandboxSetter=e.setSandboxMode,this.llmProvider=e.llmProvider,this.sessionSeed=randomBytes(16).toString("hex"),this.syncWorkspaceEnv(),this.applyAnthropicSessionUserId();}on(e){return this.eventEmitter.on("event",e),()=>this.eventEmitter.off("event",e)}setWorkDir(e){this.workDir=te__default.resolve(e),this.syncWorkspaceEnv();}setSession(e,t){this.session=e||void 0,this.sessionSync=t,this.applyAnthropicSessionUserId();}applyAnthropicSessionUserId(){let t=this.llmProvider?.getProvider?.();if(!t||typeof t.setUserId!="function")return;let s=this.session?.sessionId,n=Mu(s,this.sessionSeed);t.setUserId(n);}interrupt(){this.shouldInterrupt=true,this.abortController&&this.abortController.abort(),this.interruptResolver&&this.interruptResolver();}createInterruptPromise(){return this.interruptPromise?this.interruptPromise:(this.interruptPromise=new Promise(e=>{this.interruptResolver=()=>e({interrupted:true});}),this.interruptPromise)}clearInterruptPromise(){this.interruptResolver=null,this.interruptPromise=null;}buildToolOutputSummary(e,t,s,n,r,i){if(!i)return;let o=s,l="",c="",u=s.trim();if(u.startsWith("{")&&u.endsWith("}"))try{let g=JSON.parse(u);g&&typeof g=="object"&&(typeof g.message=="string"&&(c=g.message),typeof g.summary=="string"&&(l=g.summary),typeof g.type=="string"&&typeof g.content=="string"&&(o=g.content));}catch{}let d=r||t?.path||t?.file_path||t?.filePath||"",p=(g,f=60)=>g.length>f?g.slice(0,f-1)+"\u2026":g,h=o?o.split(`
1816
1816
  `).length:0;switch(e){case "show_tree":case "smart_tree":case "list_directory":case "ls":{let g=t?.directory||d||".",f=(s.match(/\//g)||[]).length,b=h>1?h-1:0;return `${p(g)} \u2014 ${b} entries${f?`, ${f} dirs`:""}`}case "git_status":{let g=(o.match(/^\s*M /gm)||[]).length,f=(o.match(/^\s*A /gm)||[]).length,b=(o.match(/^\s*D /gm)||[]).length,y=(o.match(/^\?\? /gm)||[]).length,w=[];return g&&w.push(`${g} modified`),f&&w.push(`${f} added`),b&&w.push(`${b} deleted`),y&&w.push(`${y} untracked`),w.length?w.join(", "):l||"clean"}case "git_log":{let g=(o.match(/^commit /gm)||[]).length||Math.min(h,10);return l||`${g} commits`}case "git_diff":{let g=(o.match(/^\+[^+]/gm)||[]).length,f=(o.match(/^-[^-]/gm)||[]).length;return l||`+${g} -${f} lines`}case "git_commit":return p(l||o.trim().split(`
1817
1817
  `)[0]||"committed");case "git_blame":return l||`${h} lines`;case "git_branch":case "git_branch_list":{let g=o.split(`
@@ -1840,10 +1840,10 @@ ${s}`),s.trim()}extractImageUrls(e){return e?.attachments?.length?e.attachments.
1840
1840
  \u2514\u2500 \u8282\u7701\uFF1A`,b+=`
1841
1841
  User: ${k(C.userTokens)} \u2022 Assistant: ${k(C.assistantTokens)} \u2022 Tool: ${k(C.toolTokens)}`,b+=`
1842
1842
  \u51C0\u8282\u7701: ${k(C.totalTokens)}`;}this.emitCompacting("\u2713 \u667A\u80FD\u538B\u7F29\u5B8C\u6210",b),this.emitEvent({type:"status",status:"complete",message:"Compaction complete"});}else {this.emitCompacting("\u25B8 \u6B63\u5728\u81EA\u52A8\u538B\u7F29\u5386\u53F2",`\u5F53\u524D\u4E0A\u4E0B\u6587: ${o}\uFF0C\u4E3A\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF0C\u5C06\u603B\u7ED3\u8F83\u65E7\u7684\u6D88\u606F\u3002`),this.emitEvent({type:"status",status:"compacting",message:"\u25B8 Auto-compacting history..."});let l=await Vp({session:i,profile:this.compatProfile});if(!l){this.emitCompacting("\u2139\uFE0F \u65E0\u9700\u538B\u7F29","\u5BF9\u8BDD\u5386\u53F2\u8F83\u77ED\uFF0C\u6240\u6709\u6D88\u606F\u90FD\u5728\u4FDD\u7559\u9884\u7B97\u5185\uFF0820K tokens\uFF09"),this.emitEvent({type:"status",status:"complete",message:"No compaction needed"});return}await this.sessionSync.loadHistory();let c="";if(this.memoryPressure){this.memoryPressure.reset();let h=this.memoryPressure.setPromptEstimateFromMessages(this.sessionSync.getMemory().getMessagesForLLM());if(this.handleMemorySnapshot(h,!0),h.profile.contextWindow){let g=Math.round(h.tokensUsed/h.profile.contextWindow*100);c=`
1843
- \u5F53\u524D\u4E0A\u4E0B\u6587: ${h.tokensUsed.toLocaleString()} / ${h.profile.contextWindow.toLocaleString()} tokens (${g}%)`;}}let d=(await i.getTimeline()).filter(h=>h.item.type==="message"),p=Fs(this.memory.getAll());this.emitEvent({type:"context_compaction",status:"completed",originalMessages:n,keptMessages:d.length,droppedMessages:l.removedMessages,compressedMessages:0,originalTokens:r.totalTokens,finalTokens:p.totalTokens,budgetTokens:t.profile.contextWindow||0,useLLM:!1,timestamp:Date.now()}),this.emitCompacting("\u2713 \u81EA\u52A8\u538B\u7F29\u5B8C\u6210",`\u6458\u8981 ${l.summaryLines} \u884C\uFF0C\u79FB\u9664 ${l.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${l.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\u3002${c}`),this.emitEvent({type:"status",status:"complete",message:"Compaction complete"});}}catch(i){let o=i?.message||String(i);this.emitLog("error","\u81EA\u52A8\u538B\u7F29\u5931\u8D25",`\u9519\u8BEF\u8BE6\u60C5: ${o}`),process.env.CLI_DEBUG==="1"&&m.error("[COMPACTION] Failed:",i);}finally{this.autoCompactionInProgress=false;}}async runTask(e,t){if(process.env.CLI_DEBUG==="1"&&(m.debug("TASK","========================================"),m.debug("TASK","=== runTask ENTRY ==="),m.debug("TASK",` userInput: "${e?.substring(0,50)}..."`),m.debug("TASK",` isRunning: ${this.isRunning}`),m.debug("TASK",` shouldInterrupt: ${this.shouldInterrupt}`),m.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`),m.debug("TASK",` stdin.destroyed: ${process.stdin.destroyed}`)),this.syncWorkspaceEnv(),!e.trim())throw new Error("Input is required");if(this.shouldInterrupt=false,this.isRunning=true,this.abortController=new AbortController,t?.abortSignal){let C=t.abortSignal;if(C.aborted)this.shouldInterrupt=true,this.abortController.abort();else {let k=()=>{this.shouldInterrupt=true,this.abortController?.abort();};C.addEventListener("abort",k,{once:true});}}let s=t?.metadata?.mode,n=this.runner.getMode(),r=s==="ask"&&n!=="ask";r&&this.runner.setMode("ask");let i=this.prepareTaskInput(e,t?.metadata),o=this.extractImageUrls(t?.metadata);if(this.currentTaskMetadata=t?.metadata,this.sessionSync&&this.sessionEnabled)try{let C=this.sessionSync.getTurnCount()+1,k=await this.sessionSync.createCheckpoint(`turn_${C}`);this.emitEvent({type:"checkpoint",id:k,auto:!0});}catch(C){m.error("TASK","\u68C0\u67E5\u70B9\u521B\u5EFA\u5931\u8D25\uFF01 \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25\uFF01",C),console.error("Failed to create auto checkpoint",C);}this.emitEvent({type:"status",status:"thinking",message:"Starting..."});let l=Date.now(),c="",u=0,d=0,p=0,h="",g="",f="",b="",y=0,w=0;try{let C=this.abortController?.signal;process.env.CLI_DEBUG==="1"&&m.debug("TASK","=== \u5F00\u59CBagent loop \u5FAA\u73AF ===");let k=0,T=this.createInterruptPromise(),_=this.runner.run(i,o.length>0?o:void 0,C)[Symbol.asyncIterator]();for(;;){let R=_.next();R.catch(()=>{});let j=await Promise.race([R,T]);if("interrupted"in j){if(this.shouldInterrupt=!0,_.return)try{_.return(void 0)?.catch?.(()=>{});}catch{}break}if(j.done)break;let v=j.value;if(k++,process.env.CLI_DEBUG==="1"&&m.debug("TASK",` \u4E8B\u4EF6 #${k}: ${v.type}`),this.shouldInterrupt){process.env.CLI_DEBUG==="1"&&m.debug("TASK"," shouldInterrupt=true, \u9000\u51FAloop");break}switch(v.type){case "iteration_start":if(this.emitEvent({type:"text_complete"}),u=v.iteration||0,u>1){let A=this.processPendingInjectedMessages();A>0&&(m.info("INJECT",`\u2705 Processed ${A} injected messages at iteration ${u}`),this.emitEvent({type:"queued_messages_processed",count:A}));}if(this.emitEvent({type:"thinking",iteration:u,timestamp:Date.now()}),this.emitEvent({type:"status",status:"thinking",message:Qp()}),w=0,this.memoryPressure){let A=this.memory.getMessagesForLLM();process.env.CLI_DEBUG&&(m.debug("CONTEXT",`\u8FED\u4EE3\u5F00\u59CB: \u77ED\u671F\u8BB0\u5FC6 \u6709 ${A.length} \u6D88\u606F`),A.forEach((O,$)=>{let P=typeof O.content=="string"?O.content.length:JSON.stringify(O.content).length;m.debug("CONTEXT",` [${$}] role=${O.role}, content_len=${P}`);}));}break;case "text_delta":if(v.delta){c+=v.delta,h+=v.delta,g+=v.delta;let A=Math.ceil(v.delta.length/4);w+=A,(v.delta.trim().length>0||v.delta.includes(`
1844
- `))&&(this.emitEvent({type:"status",status:"thinking",message:"Generating response..."}),this.emitEvent({type:"text",delta:v.delta}));}break;case "reasoning_delta":v.delta&&this.emitEvent({type:"reasoning",delta:v.delta,timestamp:Date.now()});break;case "reasoning_complete":this.emitEvent({type:"reasoning_complete",timestamp:Date.now()});break;case "tool_call_start":d++,f="",y=0,b=v.name||"",this.emitEvent({type:"status",status:"tool_call",message:`Calling: ${v.name}`});break;case "tool_call_delta":if(v.arguments_delta){f+=v.arguments_delta,y+=v.arguments_delta.length;let A=Math.ceil(v.arguments_delta.length/4);if(w+=A,v.arguments_delta.trim().length>0&&this.emitEvent({type:"tool_call_delta",name:b||v.name||"unknown",argumentsDelta:v.arguments_delta}),y>1e3){let N=1-f.trim().length/y;N>.9&&(console.error(`[AgentHost] \u26A0\uFE0F Abnormal tool call: ${b} - ${(N*100).toFixed(1)}% whitespace (${y} bytes)`),this.emitLog("warn",`Model output abnormal: ${b} generating mostly whitespace content`));}if(b==="write_file"||b==="Write"||v.name==="write_file"||v.name==="Write"){let P=Math.floor(y/80),N=(y/1024).toFixed(1);this.emitEvent({type:"status",status:"tool_call",message:`\u26A1 Generating... ${N}KB (~${P} lines)`});try{let D=f.match(/"file_path"\s*:\s*"([^"]+)"/),G=f.match(/"content"\s*:\s*"/);if(D&&G){let z=D[1],oe=f.indexOf('"',G.index+9+1)+1;if(oe>0){let ue=f.substring(oe),Se=-1,q=0;for(let ne=0;ne<ue.length;ne++)if(ue[ne]==="\\")q++;else {if(ue[ne]==='"'&&q%2===0){Se=ne;break}q=0;}Se>0&&(ue=ue.substring(0,Se));let J=ue.replace(/\\n/g,`
1843
+ \u5F53\u524D\u4E0A\u4E0B\u6587: ${h.tokensUsed.toLocaleString()} / ${h.profile.contextWindow.toLocaleString()} tokens (${g}%)`;}}let d=(await i.getTimeline()).filter(h=>h.item.type==="message"),p=Fs(this.memory.getAll());this.emitEvent({type:"context_compaction",status:"completed",originalMessages:n,keptMessages:d.length,droppedMessages:l.removedMessages,compressedMessages:0,originalTokens:r.totalTokens,finalTokens:p.totalTokens,budgetTokens:t.profile.contextWindow||0,useLLM:!1,timestamp:Date.now()}),this.emitCompacting("\u2713 \u81EA\u52A8\u538B\u7F29\u5B8C\u6210",`\u6458\u8981 ${l.summaryLines} \u884C\uFF0C\u79FB\u9664 ${l.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${l.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\u3002${c}`),this.emitEvent({type:"status",status:"complete",message:"Compaction complete"});}}catch(i){let o=i?.message||String(i);this.emitLog("error","\u81EA\u52A8\u538B\u7F29\u5931\u8D25",`\u9519\u8BEF\u8BE6\u60C5: ${o}`),process.env.CLI_DEBUG==="1"&&m.error("[COMPACTION] Failed:",i);}finally{this.autoCompactionInProgress=false;}}async runTask(e,t){if(process.env.CLI_DEBUG==="1"&&(m.debug("TASK","========================================"),m.debug("TASK","=== runTask ENTRY ==="),m.debug("TASK",` userInput: "${e?.substring(0,50)}..."`),m.debug("TASK",` isRunning: ${this.isRunning}`),m.debug("TASK",` shouldInterrupt: ${this.shouldInterrupt}`),m.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`),m.debug("TASK",` stdin.destroyed: ${process.stdin.destroyed}`)),this.syncWorkspaceEnv(),!e.trim())throw new Error("Input is required");if(this.shouldInterrupt=false,this.isRunning=true,this.abortController=new AbortController,t?.abortSignal){let C=t.abortSignal;if(C.aborted)this.shouldInterrupt=true,this.abortController.abort();else {let k=()=>{this.shouldInterrupt=true,this.abortController?.abort();};C.addEventListener("abort",k,{once:true});}}let s=t?.metadata?.mode,n=this.runner.getMode(),r=s==="ask"&&n!=="ask";r&&this.runner.setMode("ask");let i=this.prepareTaskInput(e,t?.metadata),o=this.extractImageUrls(t?.metadata);if(this.currentTaskMetadata=t?.metadata,this.sessionSync&&this.sessionEnabled)try{let C=this.sessionSync.getTurnCount()+1,k=await this.sessionSync.createCheckpoint(`turn_${C}`);this.emitEvent({type:"checkpoint",id:k,auto:!0});}catch(C){m.error("TASK","\u68C0\u67E5\u70B9\u521B\u5EFA\u5931\u8D25\uFF01 \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25\uFF01",C),console.error("Failed to create auto checkpoint",C);}this.emitEvent({type:"status",status:"thinking",message:"Starting..."});let l=Date.now(),c="",u=0,d=0,p=0,h="",g="",f="",b="",y=0,w=0;try{let C=this.abortController?.signal;process.env.CLI_DEBUG==="1"&&m.debug("TASK","=== \u5F00\u59CBagent loop \u5FAA\u73AF ===");let k=0,T=this.createInterruptPromise(),_=this.runner.run(i,o.length>0?o:void 0,C)[Symbol.asyncIterator]();for(;;){let R=_.next();R.catch(()=>{});let j=await Promise.race([R,T]);if("interrupted"in j){if(this.shouldInterrupt=!0,_.return)try{_.return(void 0)?.catch?.(()=>{});}catch{}break}if(j.done)break;let v=j.value;if(k++,process.env.CLI_DEBUG==="1"&&m.debug("TASK",` \u4E8B\u4EF6 #${k}: ${v.type}`),this.shouldInterrupt){process.env.CLI_DEBUG==="1"&&m.debug("TASK"," shouldInterrupt=true, \u9000\u51FAloop");break}switch(v.type){case "iteration_start":if(this.emitEvent({type:"text_complete"}),u=v.iteration||0,u>1){let A=this.processPendingInjectedMessages();A>0&&(m.info("INJECT",`\u2705 Processed ${A} injected messages at iteration ${u}`),this.emitEvent({type:"queued_messages_processed",count:A}));}if(this.emitEvent({type:"thinking",iteration:u,timestamp:Date.now()}),this.emitEvent({type:"status",status:"thinking",message:Qp()}),w=0,this.memoryPressure){let A=this.memory.getMessagesForLLM();process.env.CLI_DEBUG&&(m.debug("CONTEXT",`\u8FED\u4EE3\u5F00\u59CB: \u77ED\u671F\u8BB0\u5FC6 \u6709 ${A.length} \u6D88\u606F`),A.forEach((O,$)=>{let D=typeof O.content=="string"?O.content.length:JSON.stringify(O.content).length;m.debug("CONTEXT",` [${$}] role=${O.role}, content_len=${D}`);}));}break;case "text_delta":if(v.delta){c+=v.delta,h+=v.delta,g+=v.delta;let A=Math.ceil(v.delta.length/4);w+=A,(v.delta.trim().length>0||v.delta.includes(`
1844
+ `))&&(this.emitEvent({type:"status",status:"thinking",message:"Generating response..."}),this.emitEvent({type:"text",delta:v.delta}));}break;case "reasoning_delta":v.delta&&this.emitEvent({type:"reasoning",delta:v.delta,timestamp:Date.now()});break;case "reasoning_complete":this.emitEvent({type:"reasoning_complete",timestamp:Date.now()});break;case "tool_call_start":d++,f="",y=0,b=v.name||"",this.emitEvent({type:"status",status:"tool_call",message:`Calling: ${v.name}`});break;case "tool_call_delta":if(v.arguments_delta){f+=v.arguments_delta,y+=v.arguments_delta.length;let A=Math.ceil(v.arguments_delta.length/4);if(w+=A,v.arguments_delta.trim().length>0&&this.emitEvent({type:"tool_call_delta",name:b||v.name||"unknown",argumentsDelta:v.arguments_delta}),y>1e3){let N=1-f.trim().length/y;N>.9&&(console.error(`[AgentHost] \u26A0\uFE0F Abnormal tool call: ${b} - ${(N*100).toFixed(1)}% whitespace (${y} bytes)`),this.emitLog("warn",`Model output abnormal: ${b} generating mostly whitespace content`));}if(b==="write_file"||b==="Write"||v.name==="write_file"||v.name==="Write"){let D=Math.floor(y/80),N=(y/1024).toFixed(1);this.emitEvent({type:"status",status:"tool_call",message:`\u26A1 Generating... ${N}KB (~${D} lines)`});try{let L=f.match(/"file_path"\s*:\s*"([^"]+)"/),G=f.match(/"content"\s*:\s*"/);if(L&&G){let z=L[1],oe=f.indexOf('"',G.index+9+1)+1;if(oe>0){let ue=f.substring(oe),Se=-1,q=0;for(let ne=0;ne<ue.length;ne++)if(ue[ne]==="\\")q++;else {if(ue[ne]==='"'&&q%2===0){Se=ne;break}q=0;}Se>0&&(ue=ue.substring(0,Se));let J=ue.replace(/\\n/g,`
1845
1845
  `).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ie=z.split(".").pop()||"",K={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"},xe=J.split(`
1846
- `),fe=xe.length<=5;J.length>2e3&&(J=J.slice(-2e3)),fe?this.emitEvent({type:"file_stream",filePath:z,content:J,language:K[ie]||ie,description:h.trim()||"Generating code...",timestamp:Date.now()}):this.emitEvent({type:"status",status:"tool_call",message:`Writing ${z} (${xe.length} lines)...`});}}}catch{m.error("MK","\u4E0D\u5B8C\u6574\u7684json \u5904\u7406");}}}break;case "tool_call_done":{if(v.name&&v.arguments)try{let A=v.arguments.trim(),O=em(v.name,A);if(O.isTruncated){process.env.CLI_DEBUG_CONSOLE==="1"&&m.log("MK",`[AgentHost] \u26A0\uFE0F Truncation detected: ${O.reason}`);let K=Zp(A);if(K)process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[AgentHost] \u2705 JSON repaired successfully"),A=K;else throw new Error(`Tool arguments truncated: ${O.reason}`)}let $=A?JSON.parse(A):{};process.env.CLI_DEBUG_CONSOLE==="1"&&m.debug("TOOL",`\u2705 Tool call parsed: ${v.name}`,{argsLength:A.length});let P=v.name,N=$;v.name==="call_tool"&&$?.name&&(P=$.name,N=$.args||{},m.info("TOOL",`\u{1F500} call_tool unwrap: ${v.name} \u2192 ${P}`));let D=Ds(P,N),G=this.descriptionExtractor.extractFromAssistantMessage(h,P);G||(G=Xp(P,N));let z=this.commandGenerator.generateEquivalentCommand(P,N),oe=v.id||`tool-${++this.toolCallIdCounter}-${Math.floor(Date.now())}`,ue=Date.now(),Se=this.batchDetector.detectBatch(oe,P,D||"",N,ue);this.recentToolCalls.set(oe,{toolId:oe,batchId:Se.batchId,targetPath:D,args:N,toolName:P});let q={targetPath:D,argsPreview:JSON.stringify(N).substring(0,200)};P==="search"&&N.pattern?q.pattern=N.pattern.substring(0,80):(P==="readfile"||P==="edit_file")&&N.path&&(q.file=N.path),m.info("TOOL",`\u{1F916} [AGENT] Call: ${P}`,q),this.emitEvent({type:"tool_call_start",name:P,args:N,targetPath:D,description:G,equivalentCommand:z,timestamp:ue+Math.random()*.1,toolId:oe,isBatch:Se.type==="batch",batchId:Se.batchId,viaCallTool:v.name==="call_tool"});let J=P==="write_file"||P==="Write",ie=N.file_path||N.filePath||N.path;J&&ie&&N.content&&(await this.emitFileStreamEvent(ie,N.content,h.trim()||void 0),h="");}catch(A){console.error("[AgentHost] \u274C Failed to parse tool arguments for:",v.name),console.error("[AgentHost] Error:",A.message),console.error("[AgentHost] Arguments length:",v.arguments?.length||0),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.error("[AgentHost] First 200 chars:",v.arguments?.substring(0,200)||""),console.error("[AgentHost] Last 200 chars:",v.arguments?.substring(Math.max(0,(v.arguments?.length||0)-200))||""));let O=tm(v.name,v.arguments||"",A),$=O.category==="tool_truncated"?`\u274C Tool ${v.name}: content truncated during streaming`:`\u274C Tool ${v.name}: ${O.code}`;this.emitEvent({type:"status",status:"error",message:$}),this.emitEvent({type:"tool_call_start",name:v.name,args:{_raw:v.arguments?.substring(0,500)||"",_error:O.code,_errorCategory:O.category,_errorMessage:O.message,_suggestion:O.suggestion,_retryable:O.retryable},timestamp:Date.now()});let P=v.id;P&&this.recentToolCalls.delete(P),this.emitEvent({type:"tool_output",name:v.name,output:JSON.stringify(O),success:!1,toolId:P});}break}case "tool_output":if(v.name&&v.output!==void 0){let A=typeof v.output=="string"?v.output:JSON.stringify(v.output),O=A.length,$=v.success??!0,P=A.slice(0,nm),N=A.length>nm;m.info("TOOL",`\u{1F916} [AGENT] Result: ${v.name} ${$?"\u2713":"\u2717"}`,{success:$,resultLength:O,outputString:A});let D=v.id,G=D?this.recentToolCalls.get(D):void 0,{batchId:z,targetPath:oe,args:ue}=G||{},Se=G?.toolName||v.name,q=ue||{},J=oe||Ds(Se,q)||(q&&typeof q.directory=="string"?q.directory:void 0),ie=this.buildToolOutputSummary(Se,q,A,O,J,$);if(m.info("TOOL",`\u{1F525} tool_output \u2192 emitting tool_call_end: realName=${Se} toolId=${D} summary=${ie?.substring(0,60)}`),$&&J&&this.batchDetector.recordCompletion(Se,J),this.emitEvent({type:"tool_call_end",name:Se,success:$,resultLength:O,timestamp:Date.now(),toolId:D,batchId:z,targetPath:J,summary:ie,output:P,outputTruncated:N,args:q}),Se==="write_file"&&v.success&&q?.file_path&&q?.content){try{let K=q.file_path,xe=q.content,ee=K.split(".").pop()?.toLowerCase()||"",fe={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"scss",less:"less",html:"html",vue:"vue",svelte:"svelte",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash"};this.emitEvent({type:"write_file_stream",filePath:K,content:xe,isComplete:!0,language:fe[ee]||ee,timestamp:Date.now()});}catch(K){m.error("TOOL","write_file_stream \u53D1\u9001\u5931\u8D25",K);}await this.handleWriteFile(q.file_path,q.content,void 0);}if(Se==="edit_file"&&v.success&&this.sessionSync&&this.sessionEnabled)try{let K=JSON.parse(A),xe=K.metadata?.edit_info||K.edit_info,ee=K.metadata?.hunks;if(m.info("TOOL","edit file\u7684\u7ED3\u679C "+K),m.info("TOOL","edit file\u7684editInfo "+xe),K.status==="success"&&xe){let fe=[];if(Array.isArray(ee)&&ee.length>0)for(let ne of ee)fe.push({type:"file_edit_snapshot",data:{filePath:K.file_path,oldString:ne.old_string,newString:ne.new_string,startLine:ne.start_line,oldLineCount:ne.old_line_count,newLineCount:ne.new_line_count,replaceAll:!1,replacementCount:1}});else fe.push({type:"file_edit_snapshot",data:{filePath:K.file_path,oldString:xe.old_string,newString:xe.new_string,startLine:xe.start_line,oldLineCount:xe.old_line_count,newLineCount:xe.new_line_count,replaceAll:(K.metadata?.replacements||K.replacements)>1,replacementCount:K.metadata?.replacements||K.replacements}});await this.sessionSync.getSession().addItems(fe);}}catch{m.error("TOOL","session\u7684edit file \u4FDD\u5B58\u5931\u8D25 ");}if(Se==="edit_file"&&v.success)try{let K=JSON.parse(A),xe=K.metadata?.edit_info||K.edit_info;if(K.status==="success"&&xe){let ee=Array.isArray(K.metadata?.hunks)?K.metadata.hunks.map(le=>({oldString:le.old_string,newString:le.new_string,startLine:le.start_line})):void 0,fe=K.file_path.split(".").pop()?.toLowerCase()||"",ne={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"scss",less:"less",html:"html",vue:"vue",svelte:"svelte",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash"};this.emitEvent({type:"edit_file_stream",filePath:K.file_path,oldString:xe.old_string,newString:xe.new_string,startLine:xe.start_line,hunks:ee,isComplete:!0,language:ne[fe]||fe,timestamp:Date.now()});}}catch{m.error("TOOL","edit file \u4FDD\u5B58\u5931\u8D25 ");}this.emitEvent({type:"tool_output",name:v.name,output:v.output,success:$,toolId:D});}break;case "token_usage":if(v.usage){p=v.usage.total_tokens;let A=v.usage.prompt_tokens||0,O=v.usage.completion_tokens||0,$=v.usage.prompt_tokens_details?.cached_tokens||0,P=v.usage.cache_read_input_tokens||0,N=v.usage.cache_creation_input_tokens||0,D=$||P||v.usage.cached_tokens||0,G=A+P+N+$;if(m.debug("CACHE","\u{1F525} Cache token calculation:"),m.debug("CACHE",` actualInputTokens=${A}`),m.debug("CACHE",` anthropicCacheReadTokens=${P}`),m.debug("CACHE",` anthropicCacheCreationTokens=${N}`),m.debug("CACHE",` openaiCachedTokens=${$}`),m.debug("CACHE",` fullContextInputTokens=${G}`),m.debug("CACHE",` formula: ${A} + ${P} + ${N} + ${$} = ${G}`),this.sessionTotalInputTokens+=G,this.sessionTotalOutputTokens+=O,process.env.CLI_DEBUG&&(m.debug("CONTEXT","token_usage event received:"),m.debug("CONTEXT",` actualInputTokens=${A}, actualOutputTokens=${O}`),m.debug("CONTEXT",` anthropicCacheReadTokens=${P}, openaiCachedTokens=${$}`),m.debug("CONTEXT",` anthropicCacheCreationTokens=${N}`),m.debug("CONTEXT",` fullContextInputTokens=${G}`),m.debug("CONTEXT",` sessionTotalInput=${this.sessionTotalInputTokens}, sessionTotalOutput=${this.sessionTotalOutputTokens}`),m.debug("CONTEXT",` memoryPressure initialized: ${!!this.memoryPressure}`)),this.memoryPressure){let z=this.memory.getMessagesForLLM(),oe=this.memoryPressure.estimateMessagesForDisplay(z);this.memoryPressure.recordCalibration(oe,A,P);let ue=this.memoryPressure.recordActualUsage(G,O,z.length);m.debug("SNAPSHOT","\u{1F525} Snapshot values:"),m.debug("SNAPSHOT",` fullContextInputTokens (passed to recordActualUsage)=${G}`),m.debug("SNAPSHOT",` snapshot.promptTokens (returned)=${ue.promptTokens}`),m.debug("SNAPSHOT",` snapshot.tokensUsed=${ue.tokensUsed}`),m.debug("SNAPSHOT",` snapshot.pressure=${ue.pressure}`),process.env.CLI_DEBUG&&(m.debug("CONTEXT","recordActualUsage snapshot:"),m.debug("CONTEXT",` tokensUsed=${ue.tokensUsed}, promptTokens=${ue.promptTokens}`),m.debug("CONTEXT",` completionTokens=${ue.completionTokens}, contextWindow=${ue.profile.contextWindow}`),m.debug("CONTEXT",` pressure=${ue.pressure}, state=${ue.state}`)),await this.handleMemorySnapshot(ue);}w=0,this.emitEvent({type:"token_usage",promptTokens:G,completionTokens:O,totalTokens:G+O,cachedTokens:D>0?D:void 0,openaiCachedTokens:$>0?$:void 0,anthropicCacheReadTokens:P>0?P:void 0,anthropicCacheCreationTokens:N>0?N:void 0,sessionPromptTokens:this.sessionTotalInputTokens,sessionCompletionTokens:this.sessionTotalOutputTokens});}break;case "context_compaction":this.emitEvent({type:"context_compaction",status:v.status,originalMessages:v.originalMessages,keptMessages:v.keptMessages,droppedMessages:v.droppedMessages,compressedMessages:v.compressedMessages,originalTokens:v.originalTokens,finalTokens:v.finalTokens,budgetTokens:v.budgetTokens,useLLM:v.useLLM,timestamp:v.timestamp??Date.now()});break;case "raw_response_event":if(v.event_type==="input_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking input guardrails..."});else if(v.event_type==="output_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking output guardrails..."});else if(v.event_type==="structured_output.retry"){this.emitEvent({type:"text_complete"}),c="";let A=Array.isArray(v.data?.errors)&&v.data.errors.length>0?v.data.errors.join("; "):v.data?.message;this.emitLog("warn","Structured output validation failed",A),this.emitEvent({type:"status",status:"error",message:"Structured output invalid, retrying..."});}else if(v.event_type==="structured_output.accepted")typeof v.data?.normalized_text=="string"&&(c=v.data.normalized_text),this.emitLog("info","Structured output ready",v.data?.schema?`Schema: ${v.data.schema}`:void 0);else if(v.event_type==="error.classified"){let A=v.data;this.emitEvent({type:"error_classified",category:A.category||"INTERNAL",code:A.code||"UNKNOWN_ERROR",message:A.message||"An unknown error occurred",suggestion:A.suggestion,retryable:A.retryable??!1});}else if(v.event_type==="context_compaction"){let A=v.data;if(this.memoryPressure&&A.finalTokens!==void 0){let P=this.memoryPressure.setPromptEstimateFromMessages(this.memory.getMessagesForLLM());this.handleMemorySnapshot(P,!0);}let O=A.droppedMessages||0,$=A.compressedMessages||0;if(O>0||$>0){let P=(A.originalTokens||0)-(A.finalTokens||0),N=A.useLLM?"\u667A\u80FD\u538B\u7F29":"\u88C1\u526A";this.emitLog("info",`\u25B8 \u4E0A\u4E0B\u6587${N}`,`\u79FB\u9664 ${O} \u6761\u6D88\u606F${$>0?`\uFF0C\u538B\u7F29 ${$} \u6761`:""}\uFF0C\u8282\u7701\u7EA6 ${P.toLocaleString()} tokens`),this.emitEvent({type:"status",status:"compacting",message:`Context compacted: -${O} messages`});}}else v.event_type==="response.completed"&&(process.env.CLI_DEBUG_CONSOLE==="1"&&m.debug("EVENTS","\u{1F4E4} Forwarding response.completed"),this.emitEvent({type:"raw_response_event",data:v.data,event_type:v.event_type}));break;case "run_done":break;case "error":m.error("AGENT",`Error: ${v.error||"Unknown error"}`),this.emitEvent({type:"error",message:v.error||"Unknown error"}),this.emitEvent({type:"status",status:"error",message:`Error: ${v.error||"Unknown error"}`});break;case "stream_retry":let E=v;this.emitEvent({type:"stream_retry",error:E.error,errorCode:E.errorCode||"STREAM_ERROR",attempt:E.attempt,maxRetries:E.maxRetries,delayMs:E.delayMs});break;case "stream_recovered":let L=v;this.emitEvent({type:"stream_recovered",attempt:L.attempt,maxRetries:L.maxRetries});break;case "plan_update":let I=v;m.info("RUNTIME_HOST","\u{1F525} Forwarding plan_update event",{hasExplanation:!!I.explanation,planSteps:I.plan?.length}),this.emitEvent({type:"plan_update",explanation:I.explanation,plan:I.plan,timestamp:I.timestamp||Date.now()});break}}process.env.CLI_DEBUG==="1"&&(m.debug("TASK","=== runner.run loop COMPLETED ==="),m.debug("TASK",` Total events: ${k}`),m.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`)),this.emitEvent({type:"text_complete"});let M=Date.now()-l,F=c;if(this.shouldInterrupt)this.emitEvent({type:"status",status:"error",message:"Task interrupted"});else if(this.emitEvent({type:"status",status:"complete",message:"Complete!"}),this.emitLog("info","Task complete",`${u} iterations, ${d} tool calls, ${p} tokens, ${(M/1e3).toFixed(2)}s`),this.sessionSync&&this.sessionEnabled&&F)try{await this.sessionSync.saveTurn({role:"user",content:i},{role:"assistant",content:F});}catch{}let x={output:F,totalTokens:p,durationMs:M,iterations:u,toolCalls:d,interrupted:this.shouldInterrupt};return this.emitEvent({type:"run_result",output:F,currentTurnText:g,totalTokens:p,iterations:u,toolCalls:d,durationMs:M}),x}catch(C){if(C?.code==="ERR_CANCELED"||C?.name==="CanceledError"||C?.name==="AbortError"||C?.category==="canceled"||this.shouldInterrupt){this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:"Task interrupted"}),this.emitLog("info","Task interrupted by user");let _=Date.now()-l;return {output:c,totalTokens:p,durationMs:_,iterations:u,toolCalls:d,interrupted:true}}let T=C?.message||String(C)||"Unknown error";throw this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:`Error: ${T}`}),this.emitLog("error",`Error: ${T}`),C}finally{process.env.CLI_DEBUG&&(m.debug("TASK","=== runTask finally block START ==="),m.debug("TASK",` isRunning was: ${this.isRunning}`)),r&&this.runner.setMode(n),this.isRunning=false,this.abortController=null,this.clearInterruptPromise(),process.env.CLI_DEBUG&&m.debug("TASK","=== runTask finally block END ===");}}syncWorkspaceEnv(){this.workDir&&(process.env.NEOX_WORKDIR=this.workDir);}async listSessions(){return this.sessionManager.listSessions()}getCurrentSessionId(){return this.session?.sessionId}async getSessionInfo(){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.getSessionInfo()}async emitFileStreamEvent(e,t,s){let n=e.split(".").pop()||"",i={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[n]||n,o=Date.now();this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:false,language:i,description:s,timestamp:o});}async handleWriteFile(e,t,s){let n=e.split(".").pop()||"",i={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[n]||n,o=Date.now();try{let l=await import('fs'),c=await import('path'),u=c.isAbsolute(e)?c.resolve(e):c.resolve(this.workDir,e);if(this.sessionSync&&this.sessionEnabled)try{let d=null,p="create";l.existsSync(u)&&(p="modify",d=null);let h={type:"file_snapshot",data:{filePath:e,originalContent:d,operation:p,newContent:t}};await this.sessionSync.getSession().addItems([h]);}catch(d){console.debug("Failed to capture file snapshot",d);}this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:!0,language:i,description:s,timestamp:o}),this.emitLog("info",`\u2713 Saved ${e}`,`${t.split(`
1846
+ `),fe=xe.length<=5;J.length>2e3&&(J=J.slice(-2e3)),fe?this.emitEvent({type:"file_stream",filePath:z,content:J,language:K[ie]||ie,description:h.trim()||"Generating code...",timestamp:Date.now()}):this.emitEvent({type:"status",status:"tool_call",message:`Writing ${z} (${xe.length} lines)...`});}}}catch{m.error("MK","\u4E0D\u5B8C\u6574\u7684json \u5904\u7406");}}}break;case "tool_call_done":{if(v.name&&v.arguments)try{let A=v.arguments.trim(),O=em(v.name,A);if(O.isTruncated){process.env.CLI_DEBUG_CONSOLE==="1"&&m.log("MK",`[AgentHost] \u26A0\uFE0F Truncation detected: ${O.reason}`);let K=Zp(A);if(K)process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[AgentHost] \u2705 JSON repaired successfully"),A=K;else throw new Error(`Tool arguments truncated: ${O.reason}`)}let $=A?JSON.parse(A):{};process.env.CLI_DEBUG_CONSOLE==="1"&&m.debug("TOOL",`\u2705 Tool call parsed: ${v.name}`,{argsLength:A.length});let D=v.name,N=$;v.name==="call_tool"&&$?.name&&(D=$.name,N=$.args||{},m.info("TOOL",`\u{1F500} call_tool unwrap: ${v.name} \u2192 ${D}`));let L=Ds(D,N),G=this.descriptionExtractor.extractFromAssistantMessage(h,D);G||(G=Xp(D,N));let z=this.commandGenerator.generateEquivalentCommand(D,N),oe=v.id||`tool-${++this.toolCallIdCounter}-${Math.floor(Date.now())}`,ue=Date.now(),Se=this.batchDetector.detectBatch(oe,D,L||"",N,ue);this.recentToolCalls.set(oe,{toolId:oe,batchId:Se.batchId,targetPath:L,args:N,toolName:D});let q={targetPath:L,argsPreview:JSON.stringify(N).substring(0,200)};D==="search"&&N.pattern?q.pattern=N.pattern.substring(0,80):(D==="readfile"||D==="edit_file")&&N.path&&(q.file=N.path),m.info("TOOL",`\u{1F916} [AGENT] Call: ${D}`,q),this.emitEvent({type:"tool_call_start",name:D,args:N,targetPath:L,description:G,equivalentCommand:z,timestamp:ue+Math.random()*.1,toolId:oe,isBatch:Se.type==="batch",batchId:Se.batchId,viaCallTool:v.name==="call_tool"});let J=D==="write_file"||D==="Write",ie=N.file_path||N.filePath||N.path;J&&ie&&N.content&&(await this.emitFileStreamEvent(ie,N.content,h.trim()||void 0),h="");}catch(A){console.error("[AgentHost] \u274C Failed to parse tool arguments for:",v.name),console.error("[AgentHost] Error:",A.message),console.error("[AgentHost] Arguments length:",v.arguments?.length||0),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.error("[AgentHost] First 200 chars:",v.arguments?.substring(0,200)||""),console.error("[AgentHost] Last 200 chars:",v.arguments?.substring(Math.max(0,(v.arguments?.length||0)-200))||""));let O=tm(v.name,v.arguments||"",A),$=O.category==="tool_truncated"?`\u274C Tool ${v.name}: content truncated during streaming`:`\u274C Tool ${v.name}: ${O.code}`;this.emitEvent({type:"status",status:"error",message:$}),this.emitEvent({type:"tool_call_start",name:v.name,args:{_raw:v.arguments?.substring(0,500)||"",_error:O.code,_errorCategory:O.category,_errorMessage:O.message,_suggestion:O.suggestion,_retryable:O.retryable},timestamp:Date.now()});let D=v.id;D&&this.recentToolCalls.delete(D),this.emitEvent({type:"tool_output",name:v.name,output:JSON.stringify(O),success:!1,toolId:D});}break}case "tool_output":if(v.name&&v.output!==void 0){let A=typeof v.output=="string"?v.output:JSON.stringify(v.output),O=A.length,$=v.success??!0,D=A.slice(0,nm),N=A.length>nm;m.info("TOOL",`\u{1F916} [AGENT] Result: ${v.name} ${$?"\u2713":"\u2717"}`,{success:$,resultLength:O,outputString:A});let L=v.id,G=L?this.recentToolCalls.get(L):void 0,{batchId:z,targetPath:oe,args:ue}=G||{},Se=G?.toolName||v.name,q=ue||{},J=oe||Ds(Se,q)||(q&&typeof q.directory=="string"?q.directory:void 0),ie=this.buildToolOutputSummary(Se,q,A,O,J,$);if(m.info("TOOL",`\u{1F525} tool_output \u2192 emitting tool_call_end: realName=${Se} toolId=${L} summary=${ie?.substring(0,60)}`),$&&J&&this.batchDetector.recordCompletion(Se,J),this.emitEvent({type:"tool_call_end",name:Se,success:$,resultLength:O,timestamp:Date.now(),toolId:L,batchId:z,targetPath:J,summary:ie,output:D,outputTruncated:N,args:q}),Se==="write_file"&&v.success&&q?.file_path&&q?.content){try{let K=q.file_path,xe=q.content,ee=K.split(".").pop()?.toLowerCase()||"",fe={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"scss",less:"less",html:"html",vue:"vue",svelte:"svelte",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash"};this.emitEvent({type:"write_file_stream",filePath:K,content:xe,isComplete:!0,language:fe[ee]||ee,timestamp:Date.now()});}catch(K){m.error("TOOL","write_file_stream \u53D1\u9001\u5931\u8D25",K);}await this.handleWriteFile(q.file_path,q.content,void 0);}if(Se==="edit_file"&&v.success&&this.sessionSync&&this.sessionEnabled)try{let K=JSON.parse(A),xe=K.metadata?.edit_info||K.edit_info,ee=K.metadata?.hunks;if(m.info("TOOL","edit file\u7684\u7ED3\u679C "+K),m.info("TOOL","edit file\u7684editInfo "+xe),K.status==="success"&&xe){let fe=[];if(Array.isArray(ee)&&ee.length>0)for(let ne of ee)fe.push({type:"file_edit_snapshot",data:{filePath:K.file_path,oldString:ne.old_string,newString:ne.new_string,startLine:ne.start_line,oldLineCount:ne.old_line_count,newLineCount:ne.new_line_count,replaceAll:!1,replacementCount:1}});else fe.push({type:"file_edit_snapshot",data:{filePath:K.file_path,oldString:xe.old_string,newString:xe.new_string,startLine:xe.start_line,oldLineCount:xe.old_line_count,newLineCount:xe.new_line_count,replaceAll:(K.metadata?.replacements||K.replacements)>1,replacementCount:K.metadata?.replacements||K.replacements}});await this.sessionSync.getSession().addItems(fe);}}catch{m.error("TOOL","session\u7684edit file \u4FDD\u5B58\u5931\u8D25 ");}if(Se==="edit_file"&&v.success)try{let K=JSON.parse(A),xe=K.metadata?.edit_info||K.edit_info;if(K.status==="success"&&xe){let ee=Array.isArray(K.metadata?.hunks)?K.metadata.hunks.map(le=>({oldString:le.old_string,newString:le.new_string,startLine:le.start_line})):void 0,fe=K.file_path.split(".").pop()?.toLowerCase()||"",ne={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"scss",less:"less",html:"html",vue:"vue",svelte:"svelte",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash"};this.emitEvent({type:"edit_file_stream",filePath:K.file_path,oldString:xe.old_string,newString:xe.new_string,startLine:xe.start_line,hunks:ee,isComplete:!0,language:ne[fe]||fe,timestamp:Date.now()});}}catch{m.error("TOOL","edit file \u4FDD\u5B58\u5931\u8D25 ");}this.emitEvent({type:"tool_output",name:v.name,output:v.output,success:$,toolId:L});}break;case "token_usage":if(v.usage){p=v.usage.total_tokens;let A=v.usage.prompt_tokens||0,O=v.usage.completion_tokens||0,$=v.usage.prompt_tokens_details?.cached_tokens||0,D=v.usage.cache_read_input_tokens||0,N=v.usage.cache_creation_input_tokens||0,L=$||D||v.usage.cached_tokens||0,G=A+D+N+$;if(m.debug("CACHE","\u{1F525} Cache token calculation:"),m.debug("CACHE",` actualInputTokens=${A}`),m.debug("CACHE",` anthropicCacheReadTokens=${D}`),m.debug("CACHE",` anthropicCacheCreationTokens=${N}`),m.debug("CACHE",` openaiCachedTokens=${$}`),m.debug("CACHE",` fullContextInputTokens=${G}`),m.debug("CACHE",` formula: ${A} + ${D} + ${N} + ${$} = ${G}`),this.sessionTotalInputTokens+=G,this.sessionTotalOutputTokens+=O,process.env.CLI_DEBUG&&(m.debug("CONTEXT","token_usage event received:"),m.debug("CONTEXT",` actualInputTokens=${A}, actualOutputTokens=${O}`),m.debug("CONTEXT",` anthropicCacheReadTokens=${D}, openaiCachedTokens=${$}`),m.debug("CONTEXT",` anthropicCacheCreationTokens=${N}`),m.debug("CONTEXT",` fullContextInputTokens=${G}`),m.debug("CONTEXT",` sessionTotalInput=${this.sessionTotalInputTokens}, sessionTotalOutput=${this.sessionTotalOutputTokens}`),m.debug("CONTEXT",` memoryPressure initialized: ${!!this.memoryPressure}`)),this.memoryPressure){let z=this.memory.getMessagesForLLM(),oe=this.memoryPressure.estimateMessagesForDisplay(z);this.memoryPressure.recordCalibration(oe,A,D);let ue=this.memoryPressure.recordActualUsage(G,O,z.length);m.debug("SNAPSHOT","\u{1F525} Snapshot values:"),m.debug("SNAPSHOT",` fullContextInputTokens (passed to recordActualUsage)=${G}`),m.debug("SNAPSHOT",` snapshot.promptTokens (returned)=${ue.promptTokens}`),m.debug("SNAPSHOT",` snapshot.tokensUsed=${ue.tokensUsed}`),m.debug("SNAPSHOT",` snapshot.pressure=${ue.pressure}`),process.env.CLI_DEBUG&&(m.debug("CONTEXT","recordActualUsage snapshot:"),m.debug("CONTEXT",` tokensUsed=${ue.tokensUsed}, promptTokens=${ue.promptTokens}`),m.debug("CONTEXT",` completionTokens=${ue.completionTokens}, contextWindow=${ue.profile.contextWindow}`),m.debug("CONTEXT",` pressure=${ue.pressure}, state=${ue.state}`)),await this.handleMemorySnapshot(ue);}w=0,this.emitEvent({type:"token_usage",promptTokens:G,completionTokens:O,totalTokens:G+O,cachedTokens:L>0?L:void 0,openaiCachedTokens:$>0?$:void 0,anthropicCacheReadTokens:D>0?D:void 0,anthropicCacheCreationTokens:N>0?N:void 0,sessionPromptTokens:this.sessionTotalInputTokens,sessionCompletionTokens:this.sessionTotalOutputTokens});}break;case "context_compaction":this.emitEvent({type:"context_compaction",status:v.status,originalMessages:v.originalMessages,keptMessages:v.keptMessages,droppedMessages:v.droppedMessages,compressedMessages:v.compressedMessages,originalTokens:v.originalTokens,finalTokens:v.finalTokens,budgetTokens:v.budgetTokens,useLLM:v.useLLM,timestamp:v.timestamp??Date.now()});break;case "raw_response_event":if(v.event_type==="input_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking input guardrails..."});else if(v.event_type==="output_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking output guardrails..."});else if(v.event_type==="structured_output.retry"){this.emitEvent({type:"text_complete"}),c="";let A=Array.isArray(v.data?.errors)&&v.data.errors.length>0?v.data.errors.join("; "):v.data?.message;this.emitLog("warn","Structured output validation failed",A),this.emitEvent({type:"status",status:"error",message:"Structured output invalid, retrying..."});}else if(v.event_type==="structured_output.accepted")typeof v.data?.normalized_text=="string"&&(c=v.data.normalized_text),this.emitLog("info","Structured output ready",v.data?.schema?`Schema: ${v.data.schema}`:void 0);else if(v.event_type==="error.classified"){let A=v.data;this.emitEvent({type:"error_classified",category:A.category||"INTERNAL",code:A.code||"UNKNOWN_ERROR",message:A.message||"An unknown error occurred",suggestion:A.suggestion,retryable:A.retryable??!1});}else if(v.event_type==="context_compaction"){let A=v.data;if(this.memoryPressure&&A.finalTokens!==void 0){let D=this.memoryPressure.setPromptEstimateFromMessages(this.memory.getMessagesForLLM());this.handleMemorySnapshot(D,!0);}let O=A.droppedMessages||0,$=A.compressedMessages||0;if(O>0||$>0){let D=(A.originalTokens||0)-(A.finalTokens||0),N=A.useLLM?"\u667A\u80FD\u538B\u7F29":"\u88C1\u526A";this.emitLog("info",`\u25B8 \u4E0A\u4E0B\u6587${N}`,`\u79FB\u9664 ${O} \u6761\u6D88\u606F${$>0?`\uFF0C\u538B\u7F29 ${$} \u6761`:""}\uFF0C\u8282\u7701\u7EA6 ${D.toLocaleString()} tokens`),this.emitEvent({type:"status",status:"compacting",message:`Context compacted: -${O} messages`});}}else v.event_type==="response.completed"&&(process.env.CLI_DEBUG_CONSOLE==="1"&&m.debug("EVENTS","\u{1F4E4} Forwarding response.completed"),this.emitEvent({type:"raw_response_event",data:v.data,event_type:v.event_type}));break;case "run_done":break;case "error":m.error("AGENT",`Error: ${v.error||"Unknown error"}`),this.emitEvent({type:"error",message:v.error||"Unknown error"}),this.emitEvent({type:"status",status:"error",message:`Error: ${v.error||"Unknown error"}`});break;case "stream_retry":let E=v;this.emitEvent({type:"stream_retry",error:E.error,errorCode:E.errorCode||"STREAM_ERROR",attempt:E.attempt,maxRetries:E.maxRetries,delayMs:E.delayMs});break;case "stream_recovered":let P=v;this.emitEvent({type:"stream_recovered",attempt:P.attempt,maxRetries:P.maxRetries});break;case "plan_update":let I=v;m.info("RUNTIME_HOST","\u{1F525} Forwarding plan_update event",{hasExplanation:!!I.explanation,planSteps:I.plan?.length}),this.emitEvent({type:"plan_update",explanation:I.explanation,plan:I.plan,timestamp:I.timestamp||Date.now()});break}}process.env.CLI_DEBUG==="1"&&(m.debug("TASK","=== runner.run loop COMPLETED ==="),m.debug("TASK",` Total events: ${k}`),m.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`)),this.emitEvent({type:"text_complete"});let M=Date.now()-l,F=c;if(this.shouldInterrupt)this.emitEvent({type:"status",status:"error",message:"Task interrupted"});else if(this.emitEvent({type:"status",status:"complete",message:"Complete!"}),this.emitLog("info","Task complete",`${u} iterations, ${d} tool calls, ${p} tokens, ${(M/1e3).toFixed(2)}s`),this.sessionSync&&this.sessionEnabled&&F)try{await this.sessionSync.saveTurn({role:"user",content:i},{role:"assistant",content:F});}catch{}let x={output:F,totalTokens:p,durationMs:M,iterations:u,toolCalls:d,interrupted:this.shouldInterrupt};return this.emitEvent({type:"run_result",output:F,currentTurnText:g,totalTokens:p,iterations:u,toolCalls:d,durationMs:M}),x}catch(C){if(C?.code==="ERR_CANCELED"||C?.name==="CanceledError"||C?.name==="AbortError"||C?.category==="canceled"||this.shouldInterrupt){this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:"Task interrupted"}),this.emitLog("info","Task interrupted by user");let _=Date.now()-l;return {output:c,totalTokens:p,durationMs:_,iterations:u,toolCalls:d,interrupted:true}}let T=C?.message||String(C)||"Unknown error";throw this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:`Error: ${T}`}),this.emitLog("error",`Error: ${T}`),C}finally{process.env.CLI_DEBUG&&(m.debug("TASK","=== runTask finally block START ==="),m.debug("TASK",` isRunning was: ${this.isRunning}`)),r&&this.runner.setMode(n),this.isRunning=false,this.abortController=null,this.clearInterruptPromise(),process.env.CLI_DEBUG&&m.debug("TASK","=== runTask finally block END ===");}}syncWorkspaceEnv(){this.workDir&&(process.env.NEOX_WORKDIR=this.workDir);}async listSessions(){return this.sessionManager.listSessions()}getCurrentSessionId(){return this.session?.sessionId}async getSessionInfo(){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.getSessionInfo()}async emitFileStreamEvent(e,t,s){let n=e.split(".").pop()||"",i={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[n]||n,o=Date.now();this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:false,language:i,description:s,timestamp:o});}async handleWriteFile(e,t,s){let n=e.split(".").pop()||"",i={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[n]||n,o=Date.now();try{let l=await import('fs'),c=await import('path'),u=c.isAbsolute(e)?c.resolve(e):c.resolve(this.workDir,e);if(this.sessionSync&&this.sessionEnabled)try{let d=null,p="create";l.existsSync(u)&&(p="modify",d=null);let h={type:"file_snapshot",data:{filePath:e,originalContent:d,operation:p,newContent:t}};await this.sessionSync.getSession().addItems([h]);}catch(d){console.debug("Failed to capture file snapshot",d);}this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:!0,language:i,description:s,timestamp:o}),this.emitLog("info",`\u2713 Saved ${e}`,`${t.split(`
1847
1847
  `).length} lines written to disk`);}catch(l){this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:true,language:i,description:s,timestamp:o}),this.emitLog("error",`Error handling file write: ${l.message}`);}}async switchSession(e){let t=await this.sessionManager.getSession(e);if(!t)throw new Error(`Session ${e} not found`);return this.session=t,this.session}async createSession(e){let t=await this.sessionManager.createSession({model:e||this.model});return this.session=t,t}async saveTurn(e,t){!this.sessionSync||!this.sessionEnabled||await this.sessionSync.saveTurn({role:"user",content:e},{role:"assistant",content:t});}async undoTurns(e=1){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.undo(e)}async createCheckpoint(e){if(!this.sessionSync)throw new Error("Session is not ready");let t=await this.sessionSync.createCheckpoint(e);return this.emitEvent({type:"checkpoint",id:t}),t}async listCheckpoints(){if(!this.sessionSync)throw new Error("Session is not ready");return await this.sessionSync.getSession().getCheckpoints()}async rollbackTo(e){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.rollback(e)}async clearSession(){this.sessionSync&&await this.sessionSync.clearSession(),this.memory.clear();}async compactSession(){if(!this.sessionSync||!this.compatProfile)throw new Error("Compaction is not available");let e=this.sessionSync.getSession(),t=this.memory.getAll(),s=Fs(t),n=s.totalTokens,r=s.systemTokens,i=s.userTokens+s.assistantTokens+s.toolCallTokens+s.toolResultTokens,l=this.memoryPressure?.getSnapshot()?.profile?.contextWindow||2e5,c=n/l,u=Math.round(c*100),p=(await e.getTimeline()).filter(f=>f.item.type==="message");process.env.CLI_DEBUG==="1"&&m.debug("COMPACT","Compaction status",{llmProvider:!!this.llmProvider,totalContextTokens:n,systemPromptTokens:r,dialogTokens:i,breakdown:s,messageCount:p.length,memoryMessageCount:t.length,contextWindow:l,pressure:c});let h=`\u603B Context: ${n.toLocaleString()} tokens (${u}% \u4F7F\u7528)
1848
1848
  \u7CFB\u7EDF\u63D0\u793A\u8BCD: ${r.toLocaleString()} tokens
1849
1849
  \u5BF9\u8BDD\u5386\u53F2: ${i.toLocaleString()} tokens (Memory: ${t.length-1} \u6761, Session: ${p.length} \u6761)`;this.emitCompacting("\u25A0 \u538B\u7F29\u524D\u72B6\u6001",h),this.emitCompacting("\u25C7 \u538B\u7F29\u65B9\u5F0F",`\u4F7F\u7528 LLM \u667A\u80FD\u538B\u7F29
@@ -1860,7 +1860,7 @@ ${s}`),s.trim()}extractImageUrls(e){return e?.attachments?.length?e.attachments.
1860
1860
  \u2502 \u603B\u8BA1: ${x(M.totalTokens)}`,T+=`
1861
1861
  \u2514\u2500 \u8282\u7701\uFF1A`,T+=`
1862
1862
  User: ${x(F.userTokens)} \u2022 Assistant: ${x(F.assistantTokens)} \u2022 Tool: ${x(F.toolTokens)}`,T+=`
1863
- \u51C0\u8282\u7701: ${x(F.totalTokens)}`;}this.emitCompacting("\u2713 LLM \u538B\u7F29\u5B8C\u6210",T);}else this.emitCompacting("\u2139 \u65E0\u9700\u538B\u7F29","Context \u4F7F\u7528\u91CF\u5728\u9884\u7B97\u8303\u56F4\u5185");}catch(f){throw this.emitLog("error","\u274C LLM \u538B\u7F29\u5931\u8D25",f?.message||String(f)),f}}setSandboxMode(e){this.sandboxSetter?.(e);}setApprovalHandler(e){this.runner.setApprovalHandler(e);}setMode(e){this.runner.setMode(e);}setConversationHistory(e){this.memory.clear(),this.systemPrompt&&this.memory.add({role:"system",content:this.systemPrompt});for(let t of e)!t||!t.content||this.memory.add({role:t.role,content:t.content,name:t.name,tool_calls:t.tool_calls});}dispose(){this.isRunning&&this.interrupt(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.eventEmitter.removeAllListeners(),this.memory.clear(),this.recentToolCalls.clear(),this.batchDetector.reset(),console.log("[AgentRuntimeHost] Disposed");}};var Ew="ark.cn-beijing.volces.com";function Iw(a){return a.includes("opus-4-6")||a.includes("opus-4.6")||a.includes("opus-4-5")||a.includes("opus-4.5")||a.endsWith("-thinking")}function Ll(a){return a.includes("doubao-seed")}function Ol(a){return !!a&&a.includes(Ew)}function Mw(a){let e=a?.getProvider?.();return e instanceof Vt?e:void 0}function Pw(a){let e=a?.getProvider?.();return e instanceof bn?e:void 0}function Dw(a){let e=a?.getProvider?.();return e instanceof vn?e:void 0}function Lw(a){let{model:e,baseUrl:t,openaiProvider:s,anthropicProvider:n,doubaoProvider:r,geminiProvider:i}=a,o={openai:s,anthropic:n,doubao:r,gemini:i},l=!!s&&Ol(t)&&Ll(e);return (n||r||l)&&(o.setThinkingMode=u=>{if(r&&r.setThinking({type:u}),l&&s&&s.setDoubaoThinking({type:u}),n){let d=u==="auto"?"enabled":u;n.setThinking({type:d});}}),o}function ho(a){let{provider:e,model:t,sessionId:s}=a,n=e.protocol,r=e.models?.find(h=>h.name===t),i=e.baseUrl||void 0,o,l,c,u,d;if(n==="openai"||n==="openai-responses"||n==="kimi"){let h={...e,defaultModel:t,lastSelectedModel:t,apiEndpoint:e.urlSuffix,sessionId:s,modelConfig:r,doubaoThinking:Ol(i)&&Ll(t)?{type:"enabled"}:void 0},g=Ot.createAdapter(n,h);o=g,l=Mw(g),l&&Ol(i)&&Ll(t)&&l.setDoubaoThinking({type:"enabled"});}else if(n==="anthropic"){let h={...e,defaultModel:t,lastSelectedModel:t},g=Ot.createAdapter(n,h);o=g,c=Pw(g),c&&Iw(t)&&c.setThinking({type:"enabled"});}else if(n==="anthropic-openai"){let h=e.urlSuffix||"/v1/messages",g={apiKey:e.apiKey,baseUrl:i,defaultModel:t,apiEndpoint:h,streamFormat:"anthropic",sessionId:s,retry:e.retry,modelConfig:r};l=new Vt(g),o=l;}else if(n==="doubao")u=new ao({apiKey:e.apiKey,baseUrl:i,defaultModel:t,thinking:{type:"enabled"},retry:e.retry}),o=u;else if(n==="gemini"){let h={...e,defaultModel:t,lastSelectedModel:t},g=Ot.createAdapter(n,h);o=g,d=Dw(g);}else throw new Error(`Unsupported provider protocol: ${n}`);let p=Lw({model:t,baseUrl:i,openaiProvider:l,anthropicProvider:c,doubaoProvider:u,geminiProvider:d});return {llmProvider:o,controls:p}}function rm(a){return new Vi({llmProvider:a.llmProvider,model:a.model,tools:a.tools,memory:a.memory,config:a.config,agentName:a.agentName,agentDescription:a.agentDescription,instructions:a.instructions,contextInjection:a.contextInjection,plannerMode:a.plannerMode,structuredOutput:a.structuredOutput,providerName:a.providerName,contextWindow:a.contextWindow,tailTokenBudget:a.tailTokenBudget,maxInputTokensOverride:a.maxInputTokensOverride,toolInputGuardrails:a.toolInputGuardrails??Op,toolOutputGuardrails:a.toolOutputGuardrails??Np,compressionMode:a.compressionMode,workspacePath:a.workspacePath,permissionManager:a.permissionManager,disableSystemPrompt:a.disableSystemPrompt,enableFGTS:a.enableFGTS})}function im(a){return new go({runner:a.runner,memory:a.memory,sessionManager:a.sessionManager||new Qt,sessionEnabled:a.sessionEnabled??false,workDir:a.workDir,model:a.model,memoryPressure:a.memoryPressure,compatProfile:a.compatProfile,systemPrompt:a.systemPrompt,setSandboxMode:a.setSandboxMode,llmProvider:a.llmProvider})}function fo(a){return new at(a)}W();async function om(a){let{sessionId:e,provider:t,llmConfig:s,workspacePath:n,workDir:r,instructions:i,systemPrompt:o,agentName:l,agentDescription:c,permissionManager:u,tools:d,memory:p,memorySize:h,agentConfig:g,contextInjection:f,plannerMode:b,structuredOutput:y,toolInputGuardrails:w,toolOutputGuardrails:C,compressionMode:k,platformServices:T,sessionManager:_,sessionEnabled:M,disableSystemPrompt:F,enableFGTS:x}=a,R=p??fo(h??50),j=typeof i=="string"?i:"[Function]";m.info("HOST_FACTORY",`Creating host with instructions length: ${j.length}`),m.info("HOST_FACTORY",`instructions contains \u534F\u4F5C\u6A21\u5F0F: ${j.includes("\u534F\u4F5C\u6A21\u5F0F")}`),m.info("HOST_FACTORY",`instructions contains delegate_task: ${j.includes("delegate_task")}`),m.debug("HOST_FACTORY",`instructions preview: ${j.substring(0,300)}`);let{llmProvider:v,controls:E}=ho({provider:t,model:s.model,sessionId:e}),L=s.compatProfile??null,I=L?new Hr(L):void 0,A=d??await un(n,T),O=g??{maxIterations:0,temperature:.7},$=rm({llmProvider:v,model:s.model,tools:A,memory:R,config:O,agentName:l,agentDescription:c,instructions:i,contextInjection:f,plannerMode:b,structuredOutput:y,providerName:s.providerName,contextWindow:L?.contextWindow,tailTokenBudget:L?.tailTokenBudget,maxInputTokensOverride:s.maxInputTokens,toolInputGuardrails:w,toolOutputGuardrails:C,compressionMode:k,workspacePath:n,permissionManager:u,disableSystemPrompt:F,enableFGTS:x});return {host:im({runner:$,memory:R,sessionManager:_??new Qt,sessionEnabled:M??false,workDir:r,model:s.model,memoryPressure:I,compatProfile:L,systemPrompt:o??(typeof i=="string"?i:""),llmProvider:v}),controls:E,llmProvider:v,runner:$,memory:R}}var Nt=class{hostController;platformServices;constructor(e){this.platformServices=e.platformServices,this.hostController=e.hostController??new zr;}setWorkspace(e){this.hostController.setWorkspace(e);}getHost(e){return this.hostController.getHost(e)}hasHost(e){return this.hostController.hasHost(e)}clearHost(e){this.hostController.clearHost(e);}clearAll(){this.hostController.clearAll();}forEachHost(e){this.hostController.forEachHost(e);}async getOrCreateHost(e){let{sessionId:t,configKey:s,provider:n,llmConfig:r,workspacePath:i,workDir:o,instructions:l,systemPrompt:c,agentName:u,agentDescription:d,permissionManager:p,tools:h,memory:g,memorySize:f,agentConfig:b,contextInjection:y,plannerMode:w,structuredOutput:C,toolInputGuardrails:k,toolOutputGuardrails:T,compressionMode:_,sessionManager:M,sessionEnabled:F,disableSystemPrompt:x,enableFGTS:R,onHostCreated:j}=e;return this.hostController.getOrCreateHost({sessionId:t,configKey:s,createHost:async()=>{let{host:v,controls:E,llmProvider:L,runner:I,memory:A}=await om({sessionId:t,provider:n,llmConfig:r,workspacePath:i,workDir:o,instructions:l,systemPrompt:c,agentName:u,agentDescription:d,permissionManager:p,tools:h,memory:g,memorySize:f,agentConfig:b,contextInjection:y,plannerMode:w,structuredOutput:C,toolInputGuardrails:k,toolOutputGuardrails:T,compressionMode:_,platformServices:this.platformServices,sessionManager:M,sessionEnabled:F,disableSystemPrompt:x,enableFGTS:R});return j?.({host:v,controls:E,llmProvider:L,runner:I,memory:A}),v}})}async runTask(e){let{prompt:t,metadata:s,abortSignal:n,onHostReady:r,onEvent:i,...o}=e,l=await this.getOrCreateHost(o);r?.(l);let c=i?l.on(i):void 0;try{return await l.runTask(t,{metadata:s,abortSignal:n})}finally{c&&c();}}};async function am(a){let e=a.initialProviderId,t=a.initialModelName,s=a.routeConfig,n=0,r=null,i=s?s.routes.filter(o=>o.enabled).length:a.resolvedRoute?.fallbackChain.length??1;for(;;)try{return await a.runAttempt({providerId:e,modelName:t,routeConfig:s,attempt:n,isRetry:n>0,previousError:r})}catch(o){let l=o instanceof Error?o:new Error(String(o));if(r=l,a.modelRouter&&e&&a.modelRouter.recordFailure(e,l),!!!(a.autoFailover&&a.resolvedRoute&&a.fallbackDecider&&a.modelAlias&&e))throw l;let u=a.fallbackDecider.shouldFallback(a.modelAlias,e,l,a.resolvedRoute.fallbackChain);if(u.shouldFallback&&u.targetProvider&&u.event){if(a.fallbackDecider.executeFallback(u),n+=1,e=u.targetProvider.providerId,t=u.targetProvider.modelName,s&&(s={...s,routes:s.routes.filter(d=>d.providerId!==u.event.fromProviderId)}),a.onRetry?.({providerId:e,modelName:t,attempt:n,decision:u}),n>=i)throw a.onExhausted?.("All providers have failed. Please try again later."),l;continue}throw u.exhausted&&a.onExhausted?.(u.reason),l}}W();var _r=240,yo=2e3;function Rt(a,e){return a?a.length<=e?a:a.slice(0,e).trimEnd()+"...":""}var Nl=class extends Error{code;constructor(e){super(e),this.code="missing_provider";}},$t=class{hostService;checkpointService;resolveProvider;actionLog;constructor(e){this.hostService=e.hostService,this.checkpointService=e.checkpointService,this.resolveProvider=e.resolveProvider,this.actionLog=e.actionLog;}async runSession(e){let{sessionId:t,prompt:s,metadata:n,startedAt:r=Date.now(),isAutoRouted:i,routeConfig:o,modelRouter:l,fallbackDecider:c,eventHub:u,abortSignal:d,buildHostConfig:p,onHostReady:h,onRuntimeEvent:g,onStatus:f,onRouteResolved:b,onRetry:y}=e,w=e.providerId,C=e.modelName,k=null,T=this.actionLog?.createRunId();if(this.actionLog){let F=Rt(s,_r);this.actionLog.record({type:"run_start",sessionId:t,runId:T,actor:"user",summary:F?`User: ${F}`:"User: (empty prompt)",data:{prompt:Rt(s,yo),promptLength:s.length,attachments:n?.attachments?.map(x=>({type:x.type,name:x.name,path:x.path}))}});}i&&o&&l&&(k=l.resolveProvider(o.modelAlias),k&&(w=k.providerId,C=k.modelName,b?.(k),k.degraded&&f?.("warning",`Using degraded provider: ${w}`)));let _=n;if(this.checkpointService)try{await this.checkpointService.startMessage(t);}catch{f?.("warning","Checkpoint start failed");}let M=false;try{let F=await am({modelAlias:o?.modelAlias,initialProviderId:w,initialModelName:C,routeConfig:o,resolvedRoute:k,fallbackDecider:c,modelRouter:l??void 0,autoFailover:o?.autoFailover===!0,onRetry:({decision:x})=>{this.actionLog&&this.actionLog.record({type:"status",sessionId:t,runId:T,actor:"system",summary:x?.event?`Fallback: ${x.event.fromProviderId} -> ${x.event.toProviderId}`:"Fallback: switching provider",data:{from:x?.event?.fromProviderId,to:x?.event?.toProviderId,reason:x?.reason}}),y?.(x);},onExhausted:x=>{f?.("error",`All providers exhausted: ${x}`),this.actionLog&&this.actionLog.record({type:"run_error",sessionId:t,runId:T,actor:"system",summary:`All providers exhausted: ${Rt(x,_r)}`,data:{reason:x}});},runAttempt:async x=>{let R=this.resolveProvider(x.providerId,x.modelName);if(!R.provider||!R.llmConfig)throw new Nl("No provider configured. Please add an API provider first.");f?.("info",`Connecting to ${R.llmConfig.model}...`),this.actionLog&&this.actionLog.record({type:"run_attempt",sessionId:t,runId:T,actor:"system",summary:x.isRetry?`Retry ${x.attempt}: ${R.llmConfig.model}`:`Run: ${R.llmConfig.model}`,data:{providerId:R.provider.id,providerName:R.llmConfig.providerName,model:R.llmConfig.model,attempt:x.attempt,isRetry:x.isRetry,previousError:x.previousError?.message}});let j=p(R.provider,R.llmConfig),v={contextUsed:0,startTime:Date.now(),provider:R.llmConfig.providerName||R.provider.id||"unknown",model:R.llmConfig.model};return {summary:await this.hostService.runTask({...j,prompt:s,metadata:_,abortSignal:d,onHostReady:h,onEvent:L=>{if(L.type==="tool_call_end"&&m.info("ORCHESTRATOR",`\u{1F525} onEvent received tool_call_end: name=${L.name} toolId=${L.toolId}`),this.actionLog){let I=this.buildActionLogEntry(L,t,T);I&&this.actionLog.record(I);}u?.emit(t,L,v),g?.(L,v);}}),contextUsed:v.contextUsed,providerId:R.provider.id}}});if(k&&F.providerId&&l){let x=Date.now()-r;l.recordSuccess(F.providerId,x),c&&c.recordSuccess(F.providerId);}if(this.checkpointService)try{await this.checkpointService.finishMessage(t,"Message completed"),M=!0;}catch{f?.("warning","Checkpoint save failed");}return {summary:F.summary,contextUsed:F.contextUsed,providerId:F.providerId}}catch(F){if(this.actionLog){let x=F instanceof Error?F.message:String(F);this.actionLog.record({type:"run_error",sessionId:t,runId:T,actor:"system",summary:`Run error: ${Rt(x,_r)}`,data:{message:x}});}throw F}finally{if(this.checkpointService&&!M)try{await this.checkpointService.stopWatching();}catch{f?.("warning","Checkpoint cleanup failed");}}}buildActionLogEntry(e,t,s){if(!this.actionLog)return null;let n=r=>this.actionLog?.formatFilePath(r)??r;switch(e.type){case "tool_call_start":{let r=e.targetPath?n(e.targetPath):void 0,i=r?`Tool start: ${e.name} (${r})`:`Tool start: ${e.name}`,o=e.args?Rt(JSON.stringify(e.args),yo):void 0;return {type:"tool_call_start",sessionId:t,runId:s,actor:"tool",summary:i,files:r?[r]:void 0,data:{name:e.name,toolId:e.toolId,batchId:e.batchId,targetPath:r,description:e.description,equivalentCommand:e.equivalentCommand,argsPreview:o}}}case "tool_call_end":{let r=e.targetPath?n(e.targetPath):void 0,i=r?`Tool ${e.success?"done":"failed"}: ${e.name} (${r})`:`Tool ${e.success?"done":"failed"}: ${e.name}`,o=e.output?Rt(e.output,yo):void 0;return {type:"tool_call_end",sessionId:t,runId:s,actor:"tool",summary:i,files:r?[r]:void 0,data:{name:e.name,success:e.success,duration:e.duration,resultLength:e.resultLength,summary:e.summary,outputPreview:o,outputTruncated:e.outputTruncated,toolId:e.toolId,batchId:e.batchId,targetPath:r}}}case "file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=e.additions||e.removals?`File updated: ${r} (+${e.additions??0}/-${e.removals??0})`:`File updated: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,additions:e.additions,removals:e.removals,description:e.description,contentLength:e.content?.length??0}}}case "edit_file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=`File edited: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,startLine:e.startLine,hunks:e.hunks?.length??0,oldPreview:Rt(e.oldString,200),newPreview:Rt(e.newString,200),description:e.description}}}case "write_file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=`File written: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,contentLength:e.content?.length??0,description:e.description}}}case "checkpoint":return {type:"checkpoint",sessionId:t,runId:s,actor:"system",summary:`Checkpoint saved: ${e.id}`,data:{id:e.id,auto:e.auto}};case "plan_update":{let r=e.plan.length,i=e.plan.filter(c=>c.status==="completed").length,o=e.plan.filter(c=>c.status==="in_progress").length,l=r-i-o;return {type:"plan_update",sessionId:t,runId:s,actor:"assistant",summary:`Plan update: ${i} done, ${o} active, ${l} pending`,data:{explanation:e.explanation,plan:e.plan}}}case "context_compaction":return {type:"context_compaction",sessionId:t,runId:s,actor:"system",summary:`Context compacted: ${e.originalTokens} -> ${e.finalTokens} tokens`,data:{originalMessages:e.originalMessages,keptMessages:e.keptMessages,droppedMessages:e.droppedMessages,compressedMessages:e.compressedMessages,originalTokens:e.originalTokens,finalTokens:e.finalTokens,budgetTokens:e.budgetTokens,useLLM:e.useLLM}};case "stream_retry":return {type:"stream_retry",sessionId:t,runId:s,actor:"system",summary:`Stream retry ${e.attempt}/${e.maxRetries}: ${e.errorCode}`,data:{error:e.error,errorCode:e.errorCode,attempt:e.attempt,maxRetries:e.maxRetries,delayMs:e.delayMs}};case "stream_recovered":return {type:"stream_recovered",sessionId:t,runId:s,actor:"system",summary:`Stream recovered (attempt ${e.attempt})`,data:{attempt:e.attempt,maxRetries:e.maxRetries}};case "run_result":return {type:"run_result",sessionId:t,runId:s,actor:"assistant",summary:`Run completed in ${e.durationMs}ms, tokens ${e.totalTokens}`,data:{outputPreview:Rt(e.output,yo),totalTokens:e.totalTokens,iterations:e.iterations,toolCalls:e.toolCalls,durationMs:e.durationMs}};case "error":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Runtime error: ${Rt(e.message,_r)}`,data:{message:e.message}};case "error_classified":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Error ${e.code}: ${Rt(e.message,_r)}`,data:{category:e.category,code:e.code,message:e.message,suggestion:e.suggestion,retryable:e.retryable}};default:return null}}};W();function $l(a){let e=a.getAll();if(e.length===0)return "";let t=[],s=0,n=12e3;for(let r=e.length-1;r>=0&&!(s>=n);r--){let i=e[r];if(i.role==="tool")continue;let l=(typeof i.content=="string"?i.content:JSON.stringify(i.content)).substring(0,1e3);t.unshift(`[${i.role}]: ${l}`),s+=l.length;}return t.join(`
1863
+ \u51C0\u8282\u7701: ${x(F.totalTokens)}`;}this.emitCompacting("\u2713 LLM \u538B\u7F29\u5B8C\u6210",T);}else this.emitCompacting("\u2139 \u65E0\u9700\u538B\u7F29","Context \u4F7F\u7528\u91CF\u5728\u9884\u7B97\u8303\u56F4\u5185");}catch(f){throw this.emitLog("error","\u274C LLM \u538B\u7F29\u5931\u8D25",f?.message||String(f)),f}}setSandboxMode(e){this.sandboxSetter?.(e);}setApprovalHandler(e){this.runner.setApprovalHandler(e);}setMode(e){this.runner.setMode(e);}setConversationHistory(e){this.memory.clear(),this.systemPrompt&&this.memory.add({role:"system",content:this.systemPrompt});for(let t of e)!t||!t.content||this.memory.add({role:t.role,content:t.content,name:t.name,tool_calls:t.tool_calls});}dispose(){this.isRunning&&this.interrupt(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.eventEmitter.removeAllListeners(),this.memory.clear(),this.recentToolCalls.clear(),this.batchDetector.reset(),console.log("[AgentRuntimeHost] Disposed");}};var Ew="ark.cn-beijing.volces.com";function Iw(a){return a.includes("opus-4-6")||a.includes("opus-4.6")||a.includes("opus-4-5")||a.includes("opus-4.5")||a.endsWith("-thinking")}function Ll(a){return a.includes("doubao-seed")}function Ol(a){return !!a&&a.includes(Ew)}function Mw(a){let e=a?.getProvider?.();return e instanceof Vt?e:void 0}function Pw(a){let e=a?.getProvider?.();return e instanceof bn?e:void 0}function Dw(a){let e=a?.getProvider?.();return e instanceof vn?e:void 0}function Lw(a){let{model:e,baseUrl:t,openaiProvider:s,anthropicProvider:n,doubaoProvider:r,geminiProvider:i}=a,o={openai:s,anthropic:n,doubao:r,gemini:i},l=!!s&&Ol(t)&&Ll(e);return (n||r||l)&&(o.setThinkingMode=u=>{if(r&&r.setThinking({type:u}),l&&s&&s.setDoubaoThinking({type:u}),n){let d=u==="auto"?"enabled":u;n.setThinking({type:d});}}),o}function ho(a){let{provider:e,model:t,sessionId:s}=a,n=e.protocol,r=e.models?.find(h=>h.name===t),i=e.baseUrl||void 0,o,l,c,u,d;if(n==="openai"||n==="openai-responses"||n==="kimi"){let h={...e,defaultModel:t,lastSelectedModel:t,apiEndpoint:e.urlSuffix,sessionId:s,modelConfig:r,doubaoThinking:Ol(i)&&Ll(t)?{type:"enabled"}:void 0},g=Ot.createAdapter(n,h);o=g,l=Mw(g),l&&Ol(i)&&Ll(t)&&l.setDoubaoThinking({type:"enabled"});}else if(n==="anthropic"){let h={...e,defaultModel:t,lastSelectedModel:t},g=Ot.createAdapter(n,h);o=g,c=Pw(g),c&&Iw(t)&&c.setThinking({type:"enabled"});}else if(n==="anthropic-openai"){let h=e.urlSuffix||"/v1/messages",g={apiKey:e.apiKey,baseUrl:i,defaultModel:t,apiEndpoint:h,streamFormat:"anthropic",sessionId:s,retry:e.retry,modelConfig:r};l=new Vt(g),o=l;}else if(n==="doubao")u=new ao({apiKey:e.apiKey,baseUrl:i,defaultModel:t,thinking:{type:"enabled"},retry:e.retry}),o=u;else if(n==="gemini"){let h={...e,defaultModel:t,lastSelectedModel:t},g=Ot.createAdapter(n,h);o=g,d=Dw(g);}else throw new Error(`Unsupported provider protocol: ${n}`);let p=Lw({model:t,baseUrl:i,openaiProvider:l,anthropicProvider:c,doubaoProvider:u,geminiProvider:d});return {llmProvider:o,controls:p}}function rm(a){return new Vi({llmProvider:a.llmProvider,model:a.model,tools:a.tools,memory:a.memory,config:a.config,agentName:a.agentName,agentDescription:a.agentDescription,instructions:a.instructions,contextInjection:a.contextInjection,plannerMode:a.plannerMode,structuredOutput:a.structuredOutput,providerName:a.providerName,contextWindow:a.contextWindow,tailTokenBudget:a.tailTokenBudget,maxInputTokensOverride:a.maxInputTokensOverride,toolInputGuardrails:a.toolInputGuardrails??Op,toolOutputGuardrails:a.toolOutputGuardrails??Np,compressionMode:a.compressionMode,workspacePath:a.workspacePath,permissionManager:a.permissionManager,disableSystemPrompt:a.disableSystemPrompt,enableFGTS:a.enableFGTS})}function im(a){return new go({runner:a.runner,memory:a.memory,sessionManager:a.sessionManager||new Qt,sessionEnabled:a.sessionEnabled??false,workDir:a.workDir,model:a.model,memoryPressure:a.memoryPressure,compatProfile:a.compatProfile,systemPrompt:a.systemPrompt,setSandboxMode:a.setSandboxMode,llmProvider:a.llmProvider})}function fo(a){return new at(a)}W();async function om(a){let{sessionId:e,provider:t,llmConfig:s,workspacePath:n,workDir:r,instructions:i,systemPrompt:o,agentName:l,agentDescription:c,permissionManager:u,tools:d,memory:p,memorySize:h,agentConfig:g,contextInjection:f,plannerMode:b,structuredOutput:y,toolInputGuardrails:w,toolOutputGuardrails:C,compressionMode:k,platformServices:T,sessionManager:_,sessionEnabled:M,disableSystemPrompt:F,enableFGTS:x}=a,R=p??fo(h??50),j=typeof i=="string"?i:"[Function]";m.info("HOST_FACTORY",`Creating host with instructions length: ${j.length}`),m.info("HOST_FACTORY",`instructions contains \u534F\u4F5C\u6A21\u5F0F: ${j.includes("\u534F\u4F5C\u6A21\u5F0F")}`),m.info("HOST_FACTORY",`instructions contains delegate_task: ${j.includes("delegate_task")}`),m.debug("HOST_FACTORY",`instructions preview: ${j.substring(0,300)}`);let{llmProvider:v,controls:E}=ho({provider:t,model:s.model,sessionId:e}),P=s.compatProfile??null,I=P?new Hr(P):void 0,A=d??await un(n,T),O=g??{maxIterations:0,temperature:.7},$=rm({llmProvider:v,model:s.model,tools:A,memory:R,config:O,agentName:l,agentDescription:c,instructions:i,contextInjection:f,plannerMode:b,structuredOutput:y,providerName:s.providerName,contextWindow:P?.contextWindow,tailTokenBudget:P?.tailTokenBudget,maxInputTokensOverride:s.maxInputTokens,toolInputGuardrails:w,toolOutputGuardrails:C,compressionMode:k,workspacePath:n,permissionManager:u,disableSystemPrompt:F,enableFGTS:x});return {host:im({runner:$,memory:R,sessionManager:_??new Qt,sessionEnabled:M??false,workDir:r,model:s.model,memoryPressure:I,compatProfile:P,systemPrompt:o??(typeof i=="string"?i:""),llmProvider:v}),controls:E,llmProvider:v,runner:$,memory:R}}var Nt=class{hostController;platformServices;constructor(e){this.platformServices=e.platformServices,this.hostController=e.hostController??new zr;}setWorkspace(e){this.hostController.setWorkspace(e);}getHost(e){return this.hostController.getHost(e)}hasHost(e){return this.hostController.hasHost(e)}clearHost(e){this.hostController.clearHost(e);}clearAll(){this.hostController.clearAll();}forEachHost(e){this.hostController.forEachHost(e);}async getOrCreateHost(e){let{sessionId:t,configKey:s,provider:n,llmConfig:r,workspacePath:i,workDir:o,instructions:l,systemPrompt:c,agentName:u,agentDescription:d,permissionManager:p,tools:h,memory:g,memorySize:f,agentConfig:b,contextInjection:y,plannerMode:w,structuredOutput:C,toolInputGuardrails:k,toolOutputGuardrails:T,compressionMode:_,sessionManager:M,sessionEnabled:F,disableSystemPrompt:x,enableFGTS:R,onHostCreated:j}=e;return this.hostController.getOrCreateHost({sessionId:t,configKey:s,createHost:async()=>{let{host:v,controls:E,llmProvider:P,runner:I,memory:A}=await om({sessionId:t,provider:n,llmConfig:r,workspacePath:i,workDir:o,instructions:l,systemPrompt:c,agentName:u,agentDescription:d,permissionManager:p,tools:h,memory:g,memorySize:f,agentConfig:b,contextInjection:y,plannerMode:w,structuredOutput:C,toolInputGuardrails:k,toolOutputGuardrails:T,compressionMode:_,platformServices:this.platformServices,sessionManager:M,sessionEnabled:F,disableSystemPrompt:x,enableFGTS:R});return j?.({host:v,controls:E,llmProvider:P,runner:I,memory:A}),v}})}async runTask(e){let{prompt:t,metadata:s,abortSignal:n,onHostReady:r,onEvent:i,...o}=e,l=await this.getOrCreateHost(o);r?.(l);let c=i?l.on(i):void 0;try{return await l.runTask(t,{metadata:s,abortSignal:n})}finally{c&&c();}}};async function am(a){let e=a.initialProviderId,t=a.initialModelName,s=a.routeConfig,n=0,r=null,i=s?s.routes.filter(o=>o.enabled).length:a.resolvedRoute?.fallbackChain.length??1;for(;;)try{return await a.runAttempt({providerId:e,modelName:t,routeConfig:s,attempt:n,isRetry:n>0,previousError:r})}catch(o){let l=o instanceof Error?o:new Error(String(o));if(r=l,a.modelRouter&&e&&a.modelRouter.recordFailure(e,l),!!!(a.autoFailover&&a.resolvedRoute&&a.fallbackDecider&&a.modelAlias&&e))throw l;let u=a.fallbackDecider.shouldFallback(a.modelAlias,e,l,a.resolvedRoute.fallbackChain);if(u.shouldFallback&&u.targetProvider&&u.event){if(a.fallbackDecider.executeFallback(u),n+=1,e=u.targetProvider.providerId,t=u.targetProvider.modelName,s&&(s={...s,routes:s.routes.filter(d=>d.providerId!==u.event.fromProviderId)}),a.onRetry?.({providerId:e,modelName:t,attempt:n,decision:u}),n>=i)throw a.onExhausted?.("All providers have failed. Please try again later."),l;continue}throw u.exhausted&&a.onExhausted?.(u.reason),l}}W();var _r=240,yo=2e3;function Rt(a,e){return a?a.length<=e?a:a.slice(0,e).trimEnd()+"...":""}var Nl=class extends Error{code;constructor(e){super(e),this.code="missing_provider";}},$t=class{hostService;checkpointService;resolveProvider;actionLog;constructor(e){this.hostService=e.hostService,this.checkpointService=e.checkpointService,this.resolveProvider=e.resolveProvider,this.actionLog=e.actionLog;}async runSession(e){let{sessionId:t,prompt:s,metadata:n,startedAt:r=Date.now(),isAutoRouted:i,routeConfig:o,modelRouter:l,fallbackDecider:c,eventHub:u,abortSignal:d,buildHostConfig:p,onHostReady:h,onRuntimeEvent:g,onStatus:f,onRouteResolved:b,onRetry:y}=e,w=e.providerId,C=e.modelName,k=null,T=this.actionLog?.createRunId();if(this.actionLog){let F=Rt(s,_r);this.actionLog.record({type:"run_start",sessionId:t,runId:T,actor:"user",summary:F?`User: ${F}`:"User: (empty prompt)",data:{prompt:Rt(s,yo),promptLength:s.length,attachments:n?.attachments?.map(x=>({type:x.type,name:x.name,path:x.path}))}});}i&&o&&l&&(k=l.resolveProvider(o.modelAlias),k&&(w=k.providerId,C=k.modelName,b?.(k),k.degraded&&f?.("warning",`Using degraded provider: ${w}`)));let _=n;if(this.checkpointService)try{await this.checkpointService.startMessage(t);}catch{f?.("warning","Checkpoint start failed");}let M=false;try{let F=await am({modelAlias:o?.modelAlias,initialProviderId:w,initialModelName:C,routeConfig:o,resolvedRoute:k,fallbackDecider:c,modelRouter:l??void 0,autoFailover:o?.autoFailover===!0,onRetry:({decision:x})=>{this.actionLog&&this.actionLog.record({type:"status",sessionId:t,runId:T,actor:"system",summary:x?.event?`Fallback: ${x.event.fromProviderId} -> ${x.event.toProviderId}`:"Fallback: switching provider",data:{from:x?.event?.fromProviderId,to:x?.event?.toProviderId,reason:x?.reason}}),y?.(x);},onExhausted:x=>{f?.("error",`All providers exhausted: ${x}`),this.actionLog&&this.actionLog.record({type:"run_error",sessionId:t,runId:T,actor:"system",summary:`All providers exhausted: ${Rt(x,_r)}`,data:{reason:x}});},runAttempt:async x=>{let R=this.resolveProvider(x.providerId,x.modelName);if(!R.provider||!R.llmConfig)throw new Nl("No provider configured. Please add an API provider first.");f?.("info",`Connecting to ${R.llmConfig.model}...`),this.actionLog&&this.actionLog.record({type:"run_attempt",sessionId:t,runId:T,actor:"system",summary:x.isRetry?`Retry ${x.attempt}: ${R.llmConfig.model}`:`Run: ${R.llmConfig.model}`,data:{providerId:R.provider.id,providerName:R.llmConfig.providerName,model:R.llmConfig.model,attempt:x.attempt,isRetry:x.isRetry,previousError:x.previousError?.message}});let j=p(R.provider,R.llmConfig),v={contextUsed:0,startTime:Date.now(),provider:R.llmConfig.providerName||R.provider.id||"unknown",model:R.llmConfig.model};return {summary:await this.hostService.runTask({...j,prompt:s,metadata:_,abortSignal:d,onHostReady:h,onEvent:P=>{if(P.type==="tool_call_end"&&m.info("ORCHESTRATOR",`\u{1F525} onEvent received tool_call_end: name=${P.name} toolId=${P.toolId}`),this.actionLog){let I=this.buildActionLogEntry(P,t,T);I&&this.actionLog.record(I);}u?.emit(t,P,v),g?.(P,v);}}),contextUsed:v.contextUsed,providerId:R.provider.id}}});if(k&&F.providerId&&l){let x=Date.now()-r;l.recordSuccess(F.providerId,x),c&&c.recordSuccess(F.providerId);}if(this.checkpointService)try{await this.checkpointService.finishMessage(t,"Message completed"),M=!0;}catch{f?.("warning","Checkpoint save failed");}return {summary:F.summary,contextUsed:F.contextUsed,providerId:F.providerId}}catch(F){if(this.actionLog){let x=F instanceof Error?F.message:String(F);this.actionLog.record({type:"run_error",sessionId:t,runId:T,actor:"system",summary:`Run error: ${Rt(x,_r)}`,data:{message:x}});}throw F}finally{if(this.checkpointService&&!M)try{await this.checkpointService.stopWatching();}catch{f?.("warning","Checkpoint cleanup failed");}}}buildActionLogEntry(e,t,s){if(!this.actionLog)return null;let n=r=>this.actionLog?.formatFilePath(r)??r;switch(e.type){case "tool_call_start":{let r=e.targetPath?n(e.targetPath):void 0,i=r?`Tool start: ${e.name} (${r})`:`Tool start: ${e.name}`,o=e.args?Rt(JSON.stringify(e.args),yo):void 0;return {type:"tool_call_start",sessionId:t,runId:s,actor:"tool",summary:i,files:r?[r]:void 0,data:{name:e.name,toolId:e.toolId,batchId:e.batchId,targetPath:r,description:e.description,equivalentCommand:e.equivalentCommand,argsPreview:o}}}case "tool_call_end":{let r=e.targetPath?n(e.targetPath):void 0,i=r?`Tool ${e.success?"done":"failed"}: ${e.name} (${r})`:`Tool ${e.success?"done":"failed"}: ${e.name}`,o=e.output?Rt(e.output,yo):void 0;return {type:"tool_call_end",sessionId:t,runId:s,actor:"tool",summary:i,files:r?[r]:void 0,data:{name:e.name,success:e.success,duration:e.duration,resultLength:e.resultLength,summary:e.summary,outputPreview:o,outputTruncated:e.outputTruncated,toolId:e.toolId,batchId:e.batchId,targetPath:r}}}case "file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=e.additions||e.removals?`File updated: ${r} (+${e.additions??0}/-${e.removals??0})`:`File updated: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,additions:e.additions,removals:e.removals,description:e.description,contentLength:e.content?.length??0}}}case "edit_file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=`File edited: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,startLine:e.startLine,hunks:e.hunks?.length??0,oldPreview:Rt(e.oldString,200),newPreview:Rt(e.newString,200),description:e.description}}}case "write_file_stream":{if(!e.isComplete)return null;let r=n(e.filePath),i=`File written: ${r}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[r],data:{filePath:r,contentLength:e.content?.length??0,description:e.description}}}case "checkpoint":return {type:"checkpoint",sessionId:t,runId:s,actor:"system",summary:`Checkpoint saved: ${e.id}`,data:{id:e.id,auto:e.auto}};case "plan_update":{let r=e.plan.length,i=e.plan.filter(c=>c.status==="completed").length,o=e.plan.filter(c=>c.status==="in_progress").length,l=r-i-o;return {type:"plan_update",sessionId:t,runId:s,actor:"assistant",summary:`Plan update: ${i} done, ${o} active, ${l} pending`,data:{explanation:e.explanation,plan:e.plan}}}case "context_compaction":return {type:"context_compaction",sessionId:t,runId:s,actor:"system",summary:`Context compacted: ${e.originalTokens} -> ${e.finalTokens} tokens`,data:{originalMessages:e.originalMessages,keptMessages:e.keptMessages,droppedMessages:e.droppedMessages,compressedMessages:e.compressedMessages,originalTokens:e.originalTokens,finalTokens:e.finalTokens,budgetTokens:e.budgetTokens,useLLM:e.useLLM}};case "stream_retry":return {type:"stream_retry",sessionId:t,runId:s,actor:"system",summary:`Stream retry ${e.attempt}/${e.maxRetries}: ${e.errorCode}`,data:{error:e.error,errorCode:e.errorCode,attempt:e.attempt,maxRetries:e.maxRetries,delayMs:e.delayMs}};case "stream_recovered":return {type:"stream_recovered",sessionId:t,runId:s,actor:"system",summary:`Stream recovered (attempt ${e.attempt})`,data:{attempt:e.attempt,maxRetries:e.maxRetries}};case "run_result":return {type:"run_result",sessionId:t,runId:s,actor:"assistant",summary:`Run completed in ${e.durationMs}ms, tokens ${e.totalTokens}`,data:{outputPreview:Rt(e.output,yo),totalTokens:e.totalTokens,iterations:e.iterations,toolCalls:e.toolCalls,durationMs:e.durationMs}};case "error":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Runtime error: ${Rt(e.message,_r)}`,data:{message:e.message}};case "error_classified":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Error ${e.code}: ${Rt(e.message,_r)}`,data:{category:e.category,code:e.code,message:e.message,suggestion:e.suggestion,retryable:e.retryable}};default:return null}}};W();function $l(a){let e=a.getAll();if(e.length===0)return "";let t=[],s=0,n=12e3;for(let r=e.length-1;r>=0&&!(s>=n);r--){let i=e[r];if(i.role==="tool")continue;let l=(typeof i.content=="string"?i.content:JSON.stringify(i.content)).substring(0,1e3);t.unshift(`[${i.role}]: ${l}`),s+=l.length;}return t.join(`
1864
1864
 
1865
1865
  `)}W();var Ow=new Set(["search_files","search","grep","list_directory","show_tree","smart_tree","git_status","git_diff","git_log","smart_read","readfile","read","execute_shell"]);function jl(a){return [Nw(a)]}var Bl=`
1866
1866
  ## \u5B50 Agent \u5DE5\u5177
@@ -2004,7 +2004,7 @@ ${i.output}`}let o=i.toolCalls.map(c=>` ${c.name} (${c.durationMs}ms)`).join(`
2004
2004
  ${o}
2005
2005
  ${i.output}`}}}var wn=class{config;hostService;orchestrator;abortController=null;toolTreeEngine=null;constructor(e){this.config=e,this.hostService=new Nt({platformServices:e.services}),this.orchestrator=new $t({hostService:this.hostService,resolveProvider:e.resolveProvider}),m.info("SINGLE_AGENT","SingleAgentRuntime initialized");}async chat(e,t){let{sessionId:s,prompt:n,metadata:r}=e,i=e.providerId||this.config.providerId,o=e.modelName||this.config.modelName;m.info("SINGLE_AGENT","Chat started",{sessionId:s,promptLength:n.length});try{this.abortController=new AbortController;let l=jl({orchestrator:this.orchestrator,providerId:i,modelName:o,permissionManager:this.config.permissionManager,allTools:this.config.tools,workDir:this.config.workDir,getParentMemory:()=>this.config.memory,abortSignal:this.abortController.signal,onSubAgentEvent:t?.onRuntimeEvent?(b,y,w)=>t.onRuntimeEvent({...y,subAgentId:b,sourceLabel:b},w):void 0}),c=[...this.config.tools,...l];if(this.config.enablePTC){let b=mm(this.config.tools);c.push(b),m.info("SINGLE_AGENT","PTC tool injected");}this.toolTreeEngine=new bo(c);let u=this.toolTreeEngine.liveTools,p=[this.config.systemPrompt??"Single agent mode",Bl,zw];if(this.config.enablePTC&&p.push(qw),this.config.actionLog)try{let b=await this.config.actionLog.getMemoryInjectionSummary({language:"zh",maxChars:4e3});b&&(p.push(b),m.info("SINGLE_AGENT","ActionLog memory injected",{chars:b.length}));}catch(b){m.warn("SINGLE_AGENT","ActionLog injection failed",{error:b.message});}try{let b=await dm(this.config.workDir);b&&p.push(b);}catch(b){m.warn("SINGLE_AGENT","Project memory load failed",{error:b.message});}let h=p.join(`
2006
2006
 
2007
- `),g=await this.orchestrator.runSession({sessionId:s,prompt:n,metadata:r,providerId:i,modelName:o,buildHostConfig:(b,y)=>({sessionId:s,configKey:"single_agent",provider:b,llmConfig:y,workspacePath:this.config.workDir,workDir:this.config.workDir,instructions:h,systemPrompt:h,agentName:"SingleAgent",agentDescription:"Single agent mode runtime",permissionManager:this.config.permissionManager,tools:u,memory:this.config.memory,sessionEnabled:!0,enableFGTS:this.config.enableFGTS,agentConfig:{temperature:.3,mode:this.config.agentMode??"agent"}}),onRuntimeEvent:(b,y)=>{t?.onRuntimeEvent?.(b,y),this.handleRuntimeEvent(b,t);}}),f=g.summary.output||"Task completed";return t?.onComplete?.(f),m.info("SINGLE_AGENT","Chat completed",{sessionId:s,contextUsed:g.contextUsed}),f}catch(l){let c=l instanceof Error?l:new Error(String(l));throw t?.onError?.(c),m.error("SINGLE_AGENT","Chat failed",{error:c.message}),c}}handleRuntimeEvent(e,t){switch(e.type){case "text":t?.onText?.(e.text);break;case "thinking":t?.onThinking?.(e.text);break;case "tool_call":t?.onToolCall?.(e.name,e.args);break;case "tool_result":t?.onToolResult?.(e.name,e.result);break}}abort(){this.abortController?.abort(),this.abortController=null,this.hostService.clearAll(),m.info("SINGLE_AGENT","Aborted");}getModeName(){return "single"}},zw=`
2007
+ `),g=await this.orchestrator.runSession({sessionId:s,prompt:n,metadata:r,providerId:i,modelName:o,buildHostConfig:(b,y)=>({sessionId:s,configKey:"single_agent",provider:b,llmConfig:y,workspacePath:this.config.workDir,workDir:this.config.workDir,instructions:h,systemPrompt:h,agentName:"SingleAgent",agentDescription:"Single agent mode runtime",permissionManager:this.config.permissionManager,tools:u,memory:this.config.memory,sessionEnabled:!0,enableFGTS:this.config.enableFGTS,agentConfig:{temperature:.3,mode:this.config.agentMode??"agent"}}),onRuntimeEvent:(b,y)=>{t?.onRuntimeEvent?.(b,y),this.handleRuntimeEvent(b,t);}}),f=g.summary.output||"Task completed";return t?.onComplete?.(f),m.info("SINGLE_AGENT","Chat completed",{sessionId:s,contextUsed:g.contextUsed}),f}catch(l){let c=l instanceof Error?l:new Error(String(l));throw t?.onError?.(c),m.error("SINGLE_AGENT","Chat failed",{error:c.message}),c}}handleRuntimeEvent(e,t){switch(e.type){case "text":t?.onText?.(e.text);break;case "thinking":t?.onThinking?.(e.text);break;case "tool_call":t?.onToolCall?.(e.name,e.args);break;case "tool_result":t?.onToolResult?.(e.name,e.result);break}}abort(){this.abortController?.abort(),this.abortController=null,this.hostService.clearAll(),m.info("SINGLE_AGENT","Aborted");}setAgentMode(e){this.config.agentMode=e;}getModeName(){return "single"}},zw=`
2008
2008
  ## \u5DE5\u5177\u6811
2009
2009
  \u4F60\u7684\u5DE5\u5177\u6309\u7C7B\u522B\u7EC4\u7EC7\u3002\u9ED8\u8BA4\u53EA\u6709\u5E38\u9A7B\u5DE5\u5177\u53EF\u7528\u3002
2010
2010
  \u9700\u8981\u5176\u4ED6\u5DE5\u5177\u65F6\uFF1A
@@ -3367,7 +3367,7 @@ ${R.lines.join(`
3367
3367
  `)}`),x.lines.length>0&&I.push(`${x.title}
3368
3368
  ${x.lines.join(`
3369
3369
  `)}`),I.join(`
3370
- `)},v=["activity","session","lesson","standard","progress","pinned"],E=new Map([["activity",x],["session",R],...F.map(I=>[I.key,I])]),L=j();if(L.length>i){let I=0;for(;L.length>i&&I<500;){I+=1;let A=false;for(let O of v){let $=E.get(O);if($&&$.lines.length>0){$.lines.shift(),A=true;break}}if(!A)break;L=j();}}return L}async getMemoryInjectionSummary(e){await this.ensureReady(),this.summaryItems.length===0&&await this.loadSummarySnapshot();let t=e?.language??"zh",s=e?.maxMemoryItems??$c,n=e?.maxSessionItems??Nc,r=e?.maxChars??this.options.maxSummaryChars,i=e?.includePersistent??true,o=e?.includeLastRun??true,l=e?.includeSessionSummaries??true,c=e?.query?.trim(),u=t==="zh"?{memoryHeader:"## \u9879\u76EE\u8BB0\u5FC6",pinned:"### \u56FA\u5B9A",progress:"### \u8FDB\u5EA6",standard:"### \u89C4\u8303",lesson:"### \u6559\u8BAD",sessionHeader:"## \u76F8\u5173\u4F1A\u8BDD\u6458\u8981",lastRunHeader:"## \u4E0A\u6B21\u4EFB\u52A1\u6458\u8981"}:{memoryHeader:"## Project Memory",pinned:"### Pinned",progress:"### Progress",standard:"### Standards",lesson:"### Lessons",sessionHeader:"## Related Session Summaries",lastRunHeader:"## Last Run Summary"},d=null;if(c){let k=this.tokenizeQuery(c);d={tokens:k,graphMatches:await this.getGraphRunMatches(k)};}let p=[];if(i){let k=c&&d?await this.getRelevantMemoryItems(c,s,d):{pinned:await this.getRecentMemoryItems("pinned",s),progress:await this.getRecentMemoryItems("progress",s),standard:await this.getRecentMemoryItems("standard",s),lesson:await this.getRecentMemoryItems("lesson",s)},T=_=>_.map(M=>`- [${Dr(M.ts)}] ${M.summary}`);p=[{key:"pinned",title:u.pinned,lines:T(k.pinned)},{key:"progress",title:u.progress,lines:T(k.progress)},{key:"standard",title:u.standard,lines:T(k.standard)},{key:"lesson",title:u.lesson,lines:T(k.lesson)}];}let h=o?await this.getLastMeaningfulSessionSummary():null,g=h?[`- [${Dr(h.ts)}] ${h.summary}`]:[],f=[];if(l){let T=(c&&d?await this.getRelevantSessionSummaries(c,n,d):await this.getRecentSessionSummaries(n)).filter(M=>!this.isMetaQuerySummary(M.summary));f=(h?T.filter(M=>M.id!==h.id):T).map(M=>`- [${Dr(M.ts)}] ${M.summary}`);}if(p.every(k=>k.lines.length===0)&&f.length===0&&g.length===0)return null;let b=()=>{let k=[],T=p.filter(_=>_.lines.length>0).map(_=>`${_.title}
3370
+ `)},v=["activity","session","lesson","standard","progress","pinned"],E=new Map([["activity",x],["session",R],...F.map(I=>[I.key,I])]),P=j();if(P.length>i){let I=0;for(;P.length>i&&I<500;){I+=1;let A=false;for(let O of v){let $=E.get(O);if($&&$.lines.length>0){$.lines.shift(),A=true;break}}if(!A)break;P=j();}}return P}async getMemoryInjectionSummary(e){await this.ensureReady(),this.summaryItems.length===0&&await this.loadSummarySnapshot();let t=e?.language??"zh",s=e?.maxMemoryItems??$c,n=e?.maxSessionItems??Nc,r=e?.maxChars??this.options.maxSummaryChars,i=e?.includePersistent??true,o=e?.includeLastRun??true,l=e?.includeSessionSummaries??true,c=e?.query?.trim(),u=t==="zh"?{memoryHeader:"## \u9879\u76EE\u8BB0\u5FC6",pinned:"### \u56FA\u5B9A",progress:"### \u8FDB\u5EA6",standard:"### \u89C4\u8303",lesson:"### \u6559\u8BAD",sessionHeader:"## \u76F8\u5173\u4F1A\u8BDD\u6458\u8981",lastRunHeader:"## \u4E0A\u6B21\u4EFB\u52A1\u6458\u8981"}:{memoryHeader:"## Project Memory",pinned:"### Pinned",progress:"### Progress",standard:"### Standards",lesson:"### Lessons",sessionHeader:"## Related Session Summaries",lastRunHeader:"## Last Run Summary"},d=null;if(c){let k=this.tokenizeQuery(c);d={tokens:k,graphMatches:await this.getGraphRunMatches(k)};}let p=[];if(i){let k=c&&d?await this.getRelevantMemoryItems(c,s,d):{pinned:await this.getRecentMemoryItems("pinned",s),progress:await this.getRecentMemoryItems("progress",s),standard:await this.getRecentMemoryItems("standard",s),lesson:await this.getRecentMemoryItems("lesson",s)},T=_=>_.map(M=>`- [${Dr(M.ts)}] ${M.summary}`);p=[{key:"pinned",title:u.pinned,lines:T(k.pinned)},{key:"progress",title:u.progress,lines:T(k.progress)},{key:"standard",title:u.standard,lines:T(k.standard)},{key:"lesson",title:u.lesson,lines:T(k.lesson)}];}let h=o?await this.getLastMeaningfulSessionSummary():null,g=h?[`- [${Dr(h.ts)}] ${h.summary}`]:[],f=[];if(l){let T=(c&&d?await this.getRelevantSessionSummaries(c,n,d):await this.getRecentSessionSummaries(n)).filter(M=>!this.isMetaQuerySummary(M.summary));f=(h?T.filter(M=>M.id!==h.id):T).map(M=>`- [${Dr(M.ts)}] ${M.summary}`);}if(p.every(k=>k.lines.length===0)&&f.length===0&&g.length===0)return null;let b=()=>{let k=[],T=p.filter(_=>_.lines.length>0).map(_=>`${_.title}
3371
3371
  ${_.lines.join(`
3372
3372
  `)}`);return T.length>0&&k.push(`${u.memoryHeader}
3373
3373
  ${T.join(`
@@ -3408,5 +3408,5 @@ ${e.map(s=>{let n=Dr(s.ts),r=s.files&&s.files.length>0?` files=${s.files.join(",
3408
3408
  [
3409
3409
  {"category":"progress","summary":"\u5B8C\u6210\u4E86 X\uFF0C\u4E0B\u4E00\u6B65 Y","files":["src/app.ts"],"confidence":0.7},
3410
3410
  {"category":"lesson","summary":"\u907F\u514D\u91CD\u590D\u6267\u884C Z\uFF0C\u5BB9\u6613\u8D85\u65F6","confidence":0.5}
3411
- ]`}parseSummaryItems(e){if(!e)return [];let t=e.match(/```(?:json)?\s*([\s\S]*?)\s*```/),s=t?t[1]:e,n=s.indexOf("["),r=s.lastIndexOf("]");if(n===-1||r===-1||r<=n)return [];try{let i=JSON.parse(s.slice(n,r+1));if(!Array.isArray(i))return [];let o=["progress","standard","lesson","pinned"];return i.map(l=>({category:l.category,summary:l.summary,files:Array.isArray(l.files)?l.files.filter(Boolean):void 0,confidence:typeof l.confidence=="number"?Math.min(1,Math.max(0,l.confidence)):void 0})).filter(l=>o.includes(l.category)&&typeof l.summary=="string"&&l.summary.trim())}catch{return []}}updateRunAggregate(e){if(!e.runId)return;let t=this.runAggregates.get(e.runId);switch(t||(t={sessionId:e.sessionId,startTs:e.ts,toolCalls:0,fileChanges:0,planUpdates:0,retries:0,errors:0,files:new Set},this.runAggregates.set(e.runId,t)),e.type){case "run_start":t.startTs=e.ts,t.sessionId=e.sessionId,t.promptSummary=e.summary??e.data?.prompt;break;case "run_attempt":t.provider=e.data?.providerName??e.data?.providerId,t.model=e.data?.model;break;case "tool_call_start":t.toolCalls+=1;break;case "file_change":if(t.fileChanges+=1,e.files?.length)for(let s of e.files){if(t.files.size>=uk)break;t.files.add(s);}break;case "plan_update":t.planUpdates+=1;break;case "stream_retry":t.retries+=1;break;case "run_error":t.errors+=1,t.errorMessage=e.data?.message??e.summary;break;case "run_result":t.tokens=e.data?.totalTokens,t.durationMs=e.data?.durationMs,t.outputPreview=e.data?.outputPreview;break;}}maybeQueueSessionSummary(e){if(!e.runId||e.type!=="run_result"&&e.type!=="run_error")return;let t=this.runAggregates.get(e.runId);if(!t)return;this.runAggregates.delete(e.runId);let s=t.durationMs??Math.max(0,e.ts-t.startTs),n=t.tokens,r=e.type==="run_result"?`Completed in ${s}ms, tokens ${n??"n/a"}`:`Failed: ${ot(t.errorMessage??e.summary??"Error",120)}`,i=[];t.toolCalls>0&&i.push(`tools ${t.toolCalls}`),t.fileChanges>0&&i.push(`files ${t.fileChanges}`),t.retries>0&&i.push(`retries ${t.retries}`);let o=i.length?` (${i.join(", ")})`:"",l=t.promptSummary??"User request";if(this.isLowValuePrompt(l))return;let c=t.outputPreview?ot(t.outputPreview.replace(/\s+/g," ").trim(),120):"",u=c?` | Result: ${c}`:"",d=ot(`${l} -> ${r}${o}${u}`,ck),p=Array.from(t.files),h={schemaVersion:1,id:e.id,ts:e.ts,sessionId:t.sessionId,runId:e.runId,summary:d,files:p.length?p:void 0,evidence:{eventId:e.id},model:t.model,provider:t.provider,toolCalls:t.toolCalls||void 0,errors:t.errors||(e.type==="run_error"?1:void 0),durationMs:s,tokens:n};this.sessionSummaryQueue.push(h),m.info("SESSION_SUMMARY_QUEUED","Session summary queued",{runId:h.runId,sessionId:h.sessionId,summary:ot(h.summary,160),files:h.files,toolCalls:h.toolCalls,retries:t.retries,errors:h.errors,durationMs:h.durationMs,tokens:h.tokens}),this.enqueueSummarizer(h);}async loadSummarySnapshot(){if(this.summaryPath)try{let e=await ce__default.readFile(this.summaryPath,"utf-8"),t=JSON.parse(e);t?.items?.length&&(this.summaryItems=t.items.slice(-this.options.summaryWindow));}catch{}}async persistSummarySnapshot(){if(!this.summaryPath||!this.workspaceId||!this.summaryDirty)return;let e={schemaVersion:1,workspaceId:this.workspaceId,updatedAt:Date.now(),windowSize:this.options.summaryWindow,items:this.summaryItems},t=`${this.summaryPath}.${Date.now()}.tmp`;await ce__default.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ce__default.rename(t,this.summaryPath),this.summaryDirty=false;}async loadMeta(){if(this.metaPath)try{let e=await ce__default.readFile(this.metaPath,"utf-8"),t=JSON.parse(e);if(t?.lastSeq&&(this.seq=t.lastSeq),t?.createdAt&&(this.createdAt=t.createdAt),t?.currentFile&&this.eventsDir){let s=te__default.join(this.eventsDir,t.currentFile);this.currentFile=s,this.currentDate=t.currentFile.slice(7,17),this.currentFileBytes=await this.getFileSize(s);}}catch{}}async persistMeta(){if(!this.metaPath||!this.workspaceId||!this.workspacePath||!this.workspaceName)return;let e={schemaVersion:1,workspaceId:this.workspaceId,workspacePath:this.workspacePath,workspaceName:this.workspaceName,createdAt:this.createdAt,updatedAt:Date.now(),lastSeq:this.seq,currentFile:this.currentFile?te__default.basename(this.currentFile):void 0,currentFileBytes:this.currentFileBytes,source:this.options.source,agentName:this.options.agentName},t=`${this.metaPath}.${Date.now()}.tmp`;await ce__default.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ce__default.rename(t,this.metaPath);}};W();var Ho=class{id="edge";tts;constructor(){this.tts=new EdgeTTS;}async init(){}async synthesize(e,t){let s=t?.voice||"zh-CN-XiaoxiaoNeural",n=t?.speed?`${Math.round((t.speed-1)*100)}%`:"+0%",r=t?.format||"mp3",i=r==="opus"?"webm-24khz-16bit-mono-opus":"audio-24khz-48kbitrate-mono-mp3";await this.tts.synthesize(e,s,{rate:n,outputFormat:i});let o=this.tts.toBuffer(),l=this.tts.getAudioInfo();return {audio:o,format:r,durationMs:Math.round(l.estimatedDuration*1e3)}}async synthesizeStream(e,t,s){let n=s?.voice||"zh-CN-XiaoxiaoNeural",r=s?.format||"mp3",i=0;for await(let o of this.tts.synthesizeStream(e,n))o&&o.length>0&&(t(Buffer.from(o),i),i++);return {format:r,totalChunks:i}}async getVoices(){return (await this.tts.getVoicesByLanguage("zh-CN")).map(t=>({id:t.ShortName,name:t.LocalName||t.FriendlyName,locale:t.Locale,gender:t.Gender}))}destroy(){}},Jo=class{provider=null;config;summarizeFn=null;constructor(e){this.config=e;}setSummarizeFn(e){this.summarizeFn=e;}updateConfig(e){this.config={...this.config,...e};}isEnabled(){return this.config.enabled===true}async init(){if(!this.config.enabled)return;(this.config.provider||"edge")==="edge"?this.provider=new Ho:this.provider=new Ho,await this.provider.init(),m.info("TTS",`TTS service initialized with provider: ${this.provider.id}`);}async speak(e){if(!this.config.enabled||!this.provider||!e||e.trim().length===0)return null;try{let t=await this.provider.synthesize(e,{voice:this.config.voice,speed:this.config.speed,format:this.config.format||"mp3"});return {audio:t.audio.toString("base64"),format:t.format,voiceSummary:e,durationMs:t.durationMs}}catch(t){return m.error("TTS",`TTS synthesis failed: ${t.message}`),null}}async speakStream(e,t){if(!this.config.enabled||!this.provider||!e||e.trim().length===0)return null;try{let s=await this.provider.synthesizeStream(e,(n,r)=>{t(n.toString("base64"),r);},{voice:this.config.voice,speed:this.config.speed,format:this.config.format||"mp3"});return {format:s.format,totalChunks:s.totalChunks,voiceText:e}}catch(s){return m.error("TTS",`TTS stream synthesis failed: ${s.message}`),null}}async getVoices(){return this.provider?this.provider.getVoices():[]}destroy(){this.provider?.destroy(),this.provider=null;}};var Fc=te.join(In.homedir(),".neox"),Or=te.join(Fc,"server.pid");function kk(a){Me.existsSync(Fc)||Me.mkdirSync(Fc,{recursive:true}),Me.writeFileSync(Or,JSON.stringify(a,null,2));}function eg(){try{Me.existsSync(Or)&&Me.unlinkSync(Or);}catch{}}function hB(){try{return Me.existsSync(Or)?JSON.parse(Me.readFileSync(Or,"utf-8")):null}catch{return null}}function Sk(){let a=process.argv.slice(2),e=4399,t=process.cwd(),s=false;for(let n=0;n<a.length;n++)a[n]==="--port"&&a[n+1]?(e=parseInt(a[n+1],10),n++):a[n]==="--workdir"&&a[n+1]?(t=a[n+1],n++):a[n]==="--daemon"&&(s=true);return {port:e,workDir:t,daemon:s}}async function xk(a,e){let t=Oe(),s=Wr(),n=new rt(t),r=t.agentApprovalMode||t.approvalMode||"auto",i=new ls({defaultPermission:"allow"}),o=(v,E)=>{let L=n.getProvider(v);if(!L)return {provider:null,llmConfig:null};let I=E||L.defaultModel||L.models?.[0]?.name;return {provider:L,llmConfig:{model:I,providerName:L.name||L.id,maxInputTokens:L.contextWindow||128e3}}},l=fo(500),c=new Lr({workspacePath:a,source:"server",agentName:"Neox Server"}),u=new Jo(t.tts??{enabled:false});t.tts?.enabled&&(u.setSummarizeFn(async(v,E,L)=>{let I=g;if(!I)return v.substring(0,E);let A=Ot.createAdapter(I.protocol,I),O=L||"claude-haiku-4-5-20251001";return (await A.chat([{role:"system",content:`\u4F60\u662F\u4E00\u4E2A\u8BED\u97F3\u6458\u8981\u52A9\u624B\u3002\u628A\u4EE5\u4E0B\u5185\u5BB9\u538B\u7F29\u6210${E}\u5B57\u4EE5\u5185\u7684\u53E3\u8BED\u5316\u6458\u8981\uFF0C\u9002\u5408\u8BED\u97F3\u6717\u8BFB\u3002\u4E0D\u8981\u7528\u4EE3\u7801\u3001markdown\u683C\u5F0F\u3001\u5217\u8868\u3002\u76F4\u63A5\u8BF4\u91CD\u70B9\u3002`},{role:"user",content:v}],{model:O,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||v.substring(0,E)}),await u.init());let d=await un(a,s),p=Ji({workDir:a}),h=typeof p=="string"?p:"",g=n.getDefaultProvider(),f=g?.id??"",b=g?.defaultModel??g?.models?.[0]?.name??"",y={services:s,permissionManager:i,tools:d,memory:l,workDir:a,providerId:f,modelName:b,resolveProvider:o,systemPrompt:h},w=new qo;w.setWorkspace(a);let C=null,k=null,T=null,_=null,M=t.runMode||"single";try{C=new wn({...y,actionLog:c,agentMode:r==="dangerous"?"auto":"agent",enableFGTS:t.experimental?.enableFGTS,enablePTC:t.experimental?.enablePTC});}catch(v){m.error("SERVER","Failed to init SingleAgentRuntime",{error:v});}try{k=new xn({...y,actionLog:c});}catch(v){m.error("SERVER","Failed to init AssistantRuntime",{error:v});}try{let v=new At(void 0,"cooperate");T=new ps({...y,ccbReviewMode:v.getCCBReviewMode(),workerModels:v.getEnabledWorkerModels().map(E=>({providerId:E.providerId,model:E.model,traits:E.traits}))});}catch(v){m.error("SERVER","Failed to init CooperateRuntime",{error:v});}try{let v=async(L,I,A)=>{let O=g;if(!O)throw new Error("No provider configured for NetworkRuntime");let $=Ot.createAdapter(O.protocol,O),P=[{role:"system",content:L},{role:"user",content:I}],N=A?.model||b;if(A?.onText&&$.chatStreamed){let G="",z=$.chatStreamed(P,{model:N,maxTokens:A.maxTokens,temperature:A.temperature,signal:A.signal});for await(let oe of z)oe.type==="text"&&oe.text?(G+=oe.text,A.onText(oe.text)):oe.type==="content_block_delta"&&oe.delta?.text&&(G+=oe.delta.text,A.onText(oe.delta.text));return G}return (await $.chat(P,{model:N,maxTokens:A?.maxTokens,temperature:A?.temperature,signal:A?.signal})).choices?.[0]?.message?.content||""},E=new At(void 0,"network");_=new Rn({llmCall:v,executionCapability:{orchestrator:new $t({hostService:new Nt({platformServices:s}),resolveProvider:o}),tools:d,permissionManager:i,memory:l,workDir:a,providerId:f,modelName:b,resolveProvider:o,maxIterations:30},autoCreateDefaultAgents:!0,customRoles:E.getNetworkRoles?.()});}catch(v){m.error("SERVER","Failed to init NetworkRuntime",{error:v});}let F=new Set,x=new Map,R=new Map,j={async chat(v,E){F.add(v);let L=new AbortController;x.set(v,L);let I=(N,D)=>{if(m.info("SERVER",`\u{1F4E1} publishRawEvent: type=${N.type} sessionId=${v}`),e.publish({sessionId:v,type:N.type,data:N,tracker:D,timestamp:Date.now()}),N.type==="run_result"&&u.isEnabled()){let G=N.currentTurnText||N.output;G&&u.speak(G).then(z=>{z&&e.publish({sessionId:v,type:"tts_audio",data:{type:"tts_audio",audio:z.audio,audioFormat:z.format,voiceSummary:z.voiceSummary,durationMs:z.durationMs??0},timestamp:Date.now()});}).catch(z=>{m.warn("SERVER",`TTS generation failed: ${z.message}`);});}},O=N=>{e.publish({sessionId:v,type:"error",data:{type:"error",message:N.message},timestamp:Date.now()});},$={onRuntimeEvent:(N,D)=>I(N,D),onError:O},P={onRuntimeEvent:N=>I(N),onError:O};try{let N=E.mode??M,D=E.attachments?{attachments:E.attachments}:void 0;if(N==="single"&&C)await C.chat({sessionId:v,prompt:E.prompt,metadata:D,providerId:E.providerId,modelName:E.modelName},$);else if(N==="assistant"&&k)k.removeAllListeners("worker_event"),k.removeAllListeners("worker_result"),k.on("worker_event",G=>{if(G?.event){let z={...G.event,sourceLabel:G.agentId,workerRole:G.role,workerTask:G.taskSummary};I(z,G.tracker);}}),k.on("worker_result",G=>{e.publish({sessionId:v,type:"worker_result",data:{type:"worker_result",agentId:G.agentId,success:G.success,output:G.output},timestamp:Date.now()});}),await k.chat({sessionId:v,prompt:E.prompt,metadata:D});else if(N==="cooperate"&&T)await T.chat({sessionId:v,prompt:E.prompt,metadata:D},P);else if(N==="network"&&_)await _.chat({prompt:E.prompt,history:[]});else if(C)await C.chat({sessionId:v,prompt:E.prompt,metadata:D,providerId:E.providerId,modelName:E.modelName},$);else throw new Error("No runtime available")}finally{F.delete(v),x.delete(v);}},abort(v){let E=x.get(v);E&&(E.abort(),x.delete(v)),C&&C.abort(),k&&k.abort(),T&&T.abort?.();},replyPermission(v,E,L){let I=R.get(v);I&&(I.resolve(E),R.delete(v));},getActiveSessions(){return [...F]},setRunMode(v){Wo.isValidMode(v)&&(M=v,m.info("SERVER",`Run mode changed to: ${M}`));},getRunMode(){return M},setSandboxMode(v,E){cp(E);},setApprovalMode(v,E){m.info("SERVER",`Approval mode set to: ${E}`);},async compactSession(v){m.info("SERVER",`Compact session: ${v}`);},clearSession(v){l.clear(),m.info("SERVER",`Cleared session: ${v}`);},getContextHealth(v){return l.checkContextHealth?.()??null},async getSessionInfo(v){return {messageCount:l.length,messages:l.getAll()}},setCompressionMode(v,E){m.info("SERVER",`Compression mode set to: ${E}`);},getMemoryStats(v){return {length:l.length,contextHealth:l.checkContextHealth?.()??null}},clearMemory(v){l.clear();},addMemoryMessage(v,E,L){l.add({role:E,content:L});},getToolList(){return {count:d.length,names:d.map(v=>v.name)}},async reloadTools(v){let E=await un(v,s);d.length=0,d.push(...E),m.info("SERVER",`Reloaded ${d.length} tools for ${v}`);},async setWorkspace(v){let E=await un(v,s);d.length=0,d.push(...E),w.setWorkspace(v),m.info("SERVER",`Workspace switched to: ${v}`);},async startCheckpointWatching(v){return w.startMessage(v)},async stopCheckpointWatching(){await w.stopWatching();},async createCheckpoint(v,E){return w.createCheckpoint(v,E)},async rollbackToCheckpoint(v){return w.rollbackToCheckpoint(v)},async rollbackSingleFile(v){return w.rollbackSingleFile(v)},async reapplySingleFile(v){return w.reapplySingleFile(v)},async getCheckpoints(v,E){return w.getCheckpoints(v,E)},async getCheckpointStats(){return w.getCurrentStats?.()??{created:0,modified:0,deleted:0,directories:0,total:0}},async getCheckpointChanges(){return w.getChangeBuffer?.()??[]},setCheckpointEnabled(v){w.setEnabled(v);},isCheckpointEnabled(){return w.isEnabled()},async cleanupCheckpoints(){await w.cleanup?.();},async getHostStatus(){return {isRunning:F.size>0,currentTask:null,mode:M,workingDirectory:a,uptime:Math.floor(process.uptime()),memoryUsage:{tokensUsed:l.length,contextWindow:128e3,pressure:l.length/128e3}}},async getHostAgents(){return [{id:"main",role:"main",status:F.size>0?"running":"idle"}]},async getHostActivity(v=10){return []},async getHostSession(){return {messageCount:l.length,tokensUsed:0}},async getHostSystem(){let v=null,E="unknown";try{let{execSync:L}=await import('child_process');try{v=L("git rev-parse --abbrev-ref HEAD",{cwd:a,encoding:"utf-8",timeout:5e3}).trim();}catch{}try{E=L("git status --porcelain",{cwd:a,encoding:"utf-8",timeout:5e3}).trim().length===0?"clean":"dirty";}catch{}}catch{}return {platform:process.platform,arch:process.arch,cwd:a,gitBranch:v,gitStatus:E,nodeVersion:process.version}},async hostInterrupt(v){for(let[L,I]of x)I.abort();C&&C.abort(),k&&k.abort(),T&&T.abort?.();let E=F.size>0;return F.clear(),x.clear(),{interrupted:E}},async hostSendCommand(v,E){let L=`cmd-${Date.now()}`,I={prompt:v};return j.chat(L,I).catch(A=>{m.error("SERVER",`hostSendCommand failed: ${A.message}`);}),{queued:true,sessionId:L}},setTTSEnabled(v){let E=u.isEnabled();u.updateConfig({enabled:v,provider:"edge"}),v&&!E&&(u.summarizeFn||u.setSummarizeFn(async(L,I,A)=>{let O=g;if(!O)return L.substring(0,I);let $=Ot.createAdapter(O.protocol,O),P=A||"claude-haiku-4-5-20251001";return (await $.chat([{role:"system",content:`\u4F60\u662F\u4E00\u4E2A\u8BED\u97F3\u6458\u8981\u52A9\u624B\u3002\u628A\u4EE5\u4E0B\u5185\u5BB9\u538B\u7F29\u6210${I}\u5B57\u4EE5\u5185\u7684\u53E3\u8BED\u5316\u6458\u8981\uFF0C\u9002\u5408\u8BED\u97F3\u6717\u8BFB\u3002\u4E0D\u8981\u7528\u4EE3\u7801\u3001markdown\u683C\u5F0F\u3001\u5217\u8868\u3002\u76F4\u63A5\u8BF4\u91CD\u70B9\u3002`},{role:"user",content:L}],{model:P,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||L.substring(0,I)}),u.init().catch(L=>{m.error("SERVER",`TTS init failed: ${L.message}`);})),m.info("SERVER",`TTS ${v?"enabled":"disabled"}`);},isTTSEnabled(){return u.isEnabled()},getTTSConfig(){return t.tts??{enabled:false}},updateTTSConfig(v){let E=u.isEnabled();u.updateConfig(v),v.enabled&&!E&&u.init().catch(L=>{m.error("SERVER",`TTS init failed: ${L.message}`);});}};return j}async function Tk(){let{port:a,workDir:e,daemon:t}=Sk(),s=Oe(),n=s.remote??{};m.info("SERVER",`Starting Neox Server on port ${a}, workDir: ${e}`);let r=new Br,i=new Ns,o=await xk(e,r),l={workDir:e};n.enabled&&n.token&&(l.auth={token:n.token,allowLocalWithoutAuth:true},l.rateLimit={maxRequests:120,windowMs:6e4},l.corsOrigins=["*"],m.info("SERVER","Remote mode enabled \u2014 auth + rateLimit active"));let{app:c,channelRegistry:u}=Hc(l,o,r,i),d=s.channels;d&&(await u.initialize(d),u.setHandler(async g=>{let f=`ch-${g.channelId}-${g.chatId}`;return new Promise(b=>{let y="",w=r.subscribe(f);(async()=>{for await(let C of w){if(C.type==="run_result"){y=C.data?.output||"",w.close();break}if(C.type==="error"){y=`Error: ${C.data?.message||"unknown"}`,w.close();break}}b(y||"[no response]");})(),o.chat(f,{prompt:g.text}).catch(()=>{b("[error processing message]"),w.close();});})}),await u.startAll(),m.info("SERVER","Channel adapters initialized")),await ht.initialize(e),ht.watch(e),m.info("SERVER",`Skills hot-reload active (${ht.size} skills loaded)`);let p=process.env.NEOX_HOST||(n.enabled?n.host||"0.0.0.0":"127.0.0.1");kk({pid:process.pid,port:a,workDir:e,startedAt:Date.now(),daemon:t});let h=()=>{m.info("SERVER","Shutting down..."),ht.stopWatch(),u.stopAll().catch(()=>{}),eg(),i.dispose(),r.dispose(),process.exit(0);};process.on("SIGINT",h),process.on("SIGTERM",h),serve({fetch:c.fetch,port:a,hostname:p},g=>{m.info("SERVER",`Neox Server listening on http://${p}:${g.port}`),process.send&&process.send({type:"ready",port:g.port});});}Tk().catch(a=>{m.error("SERVER","Failed to start server",{error:a}),eg(),process.exit(1);});
3411
+ ]`}parseSummaryItems(e){if(!e)return [];let t=e.match(/```(?:json)?\s*([\s\S]*?)\s*```/),s=t?t[1]:e,n=s.indexOf("["),r=s.lastIndexOf("]");if(n===-1||r===-1||r<=n)return [];try{let i=JSON.parse(s.slice(n,r+1));if(!Array.isArray(i))return [];let o=["progress","standard","lesson","pinned"];return i.map(l=>({category:l.category,summary:l.summary,files:Array.isArray(l.files)?l.files.filter(Boolean):void 0,confidence:typeof l.confidence=="number"?Math.min(1,Math.max(0,l.confidence)):void 0})).filter(l=>o.includes(l.category)&&typeof l.summary=="string"&&l.summary.trim())}catch{return []}}updateRunAggregate(e){if(!e.runId)return;let t=this.runAggregates.get(e.runId);switch(t||(t={sessionId:e.sessionId,startTs:e.ts,toolCalls:0,fileChanges:0,planUpdates:0,retries:0,errors:0,files:new Set},this.runAggregates.set(e.runId,t)),e.type){case "run_start":t.startTs=e.ts,t.sessionId=e.sessionId,t.promptSummary=e.summary??e.data?.prompt;break;case "run_attempt":t.provider=e.data?.providerName??e.data?.providerId,t.model=e.data?.model;break;case "tool_call_start":t.toolCalls+=1;break;case "file_change":if(t.fileChanges+=1,e.files?.length)for(let s of e.files){if(t.files.size>=uk)break;t.files.add(s);}break;case "plan_update":t.planUpdates+=1;break;case "stream_retry":t.retries+=1;break;case "run_error":t.errors+=1,t.errorMessage=e.data?.message??e.summary;break;case "run_result":t.tokens=e.data?.totalTokens,t.durationMs=e.data?.durationMs,t.outputPreview=e.data?.outputPreview;break;}}maybeQueueSessionSummary(e){if(!e.runId||e.type!=="run_result"&&e.type!=="run_error")return;let t=this.runAggregates.get(e.runId);if(!t)return;this.runAggregates.delete(e.runId);let s=t.durationMs??Math.max(0,e.ts-t.startTs),n=t.tokens,r=e.type==="run_result"?`Completed in ${s}ms, tokens ${n??"n/a"}`:`Failed: ${ot(t.errorMessage??e.summary??"Error",120)}`,i=[];t.toolCalls>0&&i.push(`tools ${t.toolCalls}`),t.fileChanges>0&&i.push(`files ${t.fileChanges}`),t.retries>0&&i.push(`retries ${t.retries}`);let o=i.length?` (${i.join(", ")})`:"",l=t.promptSummary??"User request";if(this.isLowValuePrompt(l))return;let c=t.outputPreview?ot(t.outputPreview.replace(/\s+/g," ").trim(),120):"",u=c?` | Result: ${c}`:"",d=ot(`${l} -> ${r}${o}${u}`,ck),p=Array.from(t.files),h={schemaVersion:1,id:e.id,ts:e.ts,sessionId:t.sessionId,runId:e.runId,summary:d,files:p.length?p:void 0,evidence:{eventId:e.id},model:t.model,provider:t.provider,toolCalls:t.toolCalls||void 0,errors:t.errors||(e.type==="run_error"?1:void 0),durationMs:s,tokens:n};this.sessionSummaryQueue.push(h),m.info("SESSION_SUMMARY_QUEUED","Session summary queued",{runId:h.runId,sessionId:h.sessionId,summary:ot(h.summary,160),files:h.files,toolCalls:h.toolCalls,retries:t.retries,errors:h.errors,durationMs:h.durationMs,tokens:h.tokens}),this.enqueueSummarizer(h);}async loadSummarySnapshot(){if(this.summaryPath)try{let e=await ce__default.readFile(this.summaryPath,"utf-8"),t=JSON.parse(e);t?.items?.length&&(this.summaryItems=t.items.slice(-this.options.summaryWindow));}catch{}}async persistSummarySnapshot(){if(!this.summaryPath||!this.workspaceId||!this.summaryDirty)return;let e={schemaVersion:1,workspaceId:this.workspaceId,updatedAt:Date.now(),windowSize:this.options.summaryWindow,items:this.summaryItems},t=`${this.summaryPath}.${Date.now()}.tmp`;await ce__default.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ce__default.rename(t,this.summaryPath),this.summaryDirty=false;}async loadMeta(){if(this.metaPath)try{let e=await ce__default.readFile(this.metaPath,"utf-8"),t=JSON.parse(e);if(t?.lastSeq&&(this.seq=t.lastSeq),t?.createdAt&&(this.createdAt=t.createdAt),t?.currentFile&&this.eventsDir){let s=te__default.join(this.eventsDir,t.currentFile);this.currentFile=s,this.currentDate=t.currentFile.slice(7,17),this.currentFileBytes=await this.getFileSize(s);}}catch{}}async persistMeta(){if(!this.metaPath||!this.workspaceId||!this.workspacePath||!this.workspaceName)return;let e={schemaVersion:1,workspaceId:this.workspaceId,workspacePath:this.workspacePath,workspaceName:this.workspaceName,createdAt:this.createdAt,updatedAt:Date.now(),lastSeq:this.seq,currentFile:this.currentFile?te__default.basename(this.currentFile):void 0,currentFileBytes:this.currentFileBytes,source:this.options.source,agentName:this.options.agentName},t=`${this.metaPath}.${Date.now()}.tmp`;await ce__default.writeFile(t,JSON.stringify(e,null,2),"utf-8"),await ce__default.rename(t,this.metaPath);}};W();var Ho=class{id="edge";tts;constructor(){this.tts=new EdgeTTS;}async init(){}async synthesize(e,t){let s=t?.voice||"zh-CN-XiaoxiaoNeural",n=t?.speed?`${Math.round((t.speed-1)*100)}%`:"+0%",r=t?.format||"mp3",i=r==="opus"?"webm-24khz-16bit-mono-opus":"audio-24khz-48kbitrate-mono-mp3";await this.tts.synthesize(e,s,{rate:n,outputFormat:i});let o=this.tts.toBuffer(),l=this.tts.getAudioInfo();return {audio:o,format:r,durationMs:Math.round(l.estimatedDuration*1e3)}}async synthesizeStream(e,t,s){let n=s?.voice||"zh-CN-XiaoxiaoNeural",r=s?.format||"mp3",i=0;for await(let o of this.tts.synthesizeStream(e,n))o&&o.length>0&&(t(Buffer.from(o),i),i++);return {format:r,totalChunks:i}}async getVoices(){return (await this.tts.getVoicesByLanguage("zh-CN")).map(t=>({id:t.ShortName,name:t.LocalName||t.FriendlyName,locale:t.Locale,gender:t.Gender}))}destroy(){}},Jo=class{provider=null;config;summarizeFn=null;constructor(e){this.config=e;}setSummarizeFn(e){this.summarizeFn=e;}updateConfig(e){this.config={...this.config,...e};}isEnabled(){return this.config.enabled===true}async init(){if(!this.config.enabled)return;(this.config.provider||"edge")==="edge"?this.provider=new Ho:this.provider=new Ho,await this.provider.init(),m.info("TTS",`TTS service initialized with provider: ${this.provider.id}`);}async speak(e){if(!this.config.enabled||!this.provider||!e||e.trim().length===0)return null;try{let t=await this.provider.synthesize(e,{voice:this.config.voice,speed:this.config.speed,format:this.config.format||"mp3"});return {audio:t.audio.toString("base64"),format:t.format,voiceSummary:e,durationMs:t.durationMs}}catch(t){return m.error("TTS",`TTS synthesis failed: ${t.message}`),null}}async speakStream(e,t){if(!this.config.enabled||!this.provider||!e||e.trim().length===0)return null;try{let s=await this.provider.synthesizeStream(e,(n,r)=>{t(n.toString("base64"),r);},{voice:this.config.voice,speed:this.config.speed,format:this.config.format||"mp3"});return {format:s.format,totalChunks:s.totalChunks,voiceText:e}}catch(s){return m.error("TTS",`TTS stream synthesis failed: ${s.message}`),null}}async getVoices(){return this.provider?this.provider.getVoices():[]}destroy(){this.provider?.destroy(),this.provider=null;}};var Fc=te.join(In.homedir(),".neox"),Or=te.join(Fc,"server.pid");function kk(a){Me.existsSync(Fc)||Me.mkdirSync(Fc,{recursive:true}),Me.writeFileSync(Or,JSON.stringify(a,null,2));}function eg(){try{Me.existsSync(Or)&&Me.unlinkSync(Or);}catch{}}function hB(){try{return Me.existsSync(Or)?JSON.parse(Me.readFileSync(Or,"utf-8")):null}catch{return null}}function Sk(){let a=process.argv.slice(2),e=4399,t=process.cwd(),s=false;for(let n=0;n<a.length;n++)a[n]==="--port"&&a[n+1]?(e=parseInt(a[n+1],10),n++):a[n]==="--workdir"&&a[n+1]?(t=a[n+1],n++):a[n]==="--daemon"&&(s=true);return {port:e,workDir:t,daemon:s}}async function xk(a,e){let t=Oe(),s=Wr(),n=new rt(t),r=t.agentApprovalMode||t.approvalMode||"auto",i=new ls({defaultPermission:"allow"}),o=(v,E)=>{let P=n.getProvider(v);if(!P)return {provider:null,llmConfig:null};let I=E||P.defaultModel||P.models?.[0]?.name;return {provider:P,llmConfig:{model:I,providerName:P.name||P.id,maxInputTokens:P.contextWindow||128e3}}},l=fo(500),c=new Lr({workspacePath:a,source:"server",agentName:"Neox Server"}),u=new Jo(t.tts??{enabled:false});t.tts?.enabled&&(u.setSummarizeFn(async(v,E,P)=>{let I=g;if(!I)return v.substring(0,E);let A=Ot.createAdapter(I.protocol,I),O=P||"claude-haiku-4-5-20251001";return (await A.chat([{role:"system",content:`\u4F60\u662F\u4E00\u4E2A\u8BED\u97F3\u6458\u8981\u52A9\u624B\u3002\u628A\u4EE5\u4E0B\u5185\u5BB9\u538B\u7F29\u6210${E}\u5B57\u4EE5\u5185\u7684\u53E3\u8BED\u5316\u6458\u8981\uFF0C\u9002\u5408\u8BED\u97F3\u6717\u8BFB\u3002\u4E0D\u8981\u7528\u4EE3\u7801\u3001markdown\u683C\u5F0F\u3001\u5217\u8868\u3002\u76F4\u63A5\u8BF4\u91CD\u70B9\u3002`},{role:"user",content:v}],{model:O,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||v.substring(0,E)}),await u.init());let d=await un(a,s),p=Ji({workDir:a}),h=typeof p=="string"?p:"",g=n.getDefaultProvider(),f=g?.id??"",b=g?.defaultModel??g?.models?.[0]?.name??"",y={services:s,permissionManager:i,tools:d,memory:l,workDir:a,providerId:f,modelName:b,resolveProvider:o,systemPrompt:h},w=new qo;w.setWorkspace(a);let C=null,k=null,T=null,_=null,M=t.runMode||"single";try{C=new wn({...y,actionLog:c,agentMode:r==="dangerous"?"auto":"agent",enableFGTS:t.experimental?.enableFGTS,enablePTC:t.experimental?.enablePTC});}catch(v){m.error("SERVER","Failed to init SingleAgentRuntime",{error:v});}try{k=new xn({...y,actionLog:c});}catch(v){m.error("SERVER","Failed to init AssistantRuntime",{error:v});}try{let v=new At(void 0,"cooperate");T=new ps({...y,ccbReviewMode:v.getCCBReviewMode(),workerModels:v.getEnabledWorkerModels().map(E=>({providerId:E.providerId,model:E.model,traits:E.traits}))});}catch(v){m.error("SERVER","Failed to init CooperateRuntime",{error:v});}try{let v=async(P,I,A)=>{let O=g;if(!O)throw new Error("No provider configured for NetworkRuntime");let $=Ot.createAdapter(O.protocol,O),D=[{role:"system",content:P},{role:"user",content:I}],N=A?.model||b;if(A?.onText&&$.chatStreamed){let G="",z=$.chatStreamed(D,{model:N,maxTokens:A.maxTokens,temperature:A.temperature,signal:A.signal});for await(let oe of z)oe.type==="text"&&oe.text?(G+=oe.text,A.onText(oe.text)):oe.type==="content_block_delta"&&oe.delta?.text&&(G+=oe.delta.text,A.onText(oe.delta.text));return G}return (await $.chat(D,{model:N,maxTokens:A?.maxTokens,temperature:A?.temperature,signal:A?.signal})).choices?.[0]?.message?.content||""},E=new At(void 0,"network");_=new Rn({llmCall:v,executionCapability:{orchestrator:new $t({hostService:new Nt({platformServices:s}),resolveProvider:o}),tools:d,permissionManager:i,memory:l,workDir:a,providerId:f,modelName:b,resolveProvider:o,maxIterations:30},autoCreateDefaultAgents:!0,customRoles:E.getNetworkRoles?.()});}catch(v){m.error("SERVER","Failed to init NetworkRuntime",{error:v});}let F=new Set,x=new Map,R=new Map,j={async chat(v,E){F.add(v);let P=new AbortController;x.set(v,P);let I=(N,L)=>{if(m.info("SERVER",`\u{1F4E1} publishRawEvent: type=${N.type} sessionId=${v}`),e.publish({sessionId:v,type:N.type,data:N,tracker:L,timestamp:Date.now()}),N.type==="run_result"&&u.isEnabled()){let G=N.currentTurnText||N.output;G&&u.speak(G).then(z=>{z&&e.publish({sessionId:v,type:"tts_audio",data:{type:"tts_audio",audio:z.audio,audioFormat:z.format,voiceSummary:z.voiceSummary,durationMs:z.durationMs??0},timestamp:Date.now()});}).catch(z=>{m.warn("SERVER",`TTS generation failed: ${z.message}`);});}},O=N=>{e.publish({sessionId:v,type:"error",data:{type:"error",message:N.message},timestamp:Date.now()});},$={onRuntimeEvent:(N,L)=>I(N,L),onError:O},D={onRuntimeEvent:N=>I(N),onError:O};try{let N=E.mode??M,L=E.attachments?{attachments:E.attachments}:void 0;if(N==="single"&&C)await C.chat({sessionId:v,prompt:E.prompt,metadata:L,providerId:E.providerId,modelName:E.modelName},$);else if(N==="assistant"&&k)k.removeAllListeners("worker_event"),k.removeAllListeners("worker_result"),k.on("worker_event",G=>{if(G?.event){let z={...G.event,sourceLabel:G.agentId,workerRole:G.role,workerTask:G.taskSummary};I(z,G.tracker);}}),k.on("worker_result",G=>{e.publish({sessionId:v,type:"worker_result",data:{type:"worker_result",agentId:G.agentId,success:G.success,output:G.output},timestamp:Date.now()});}),await k.chat({sessionId:v,prompt:E.prompt,metadata:L});else if(N==="cooperate"&&T)await T.chat({sessionId:v,prompt:E.prompt,metadata:L},D);else if(N==="network"&&_)await _.chat({prompt:E.prompt,history:[]});else if(C)await C.chat({sessionId:v,prompt:E.prompt,metadata:L,providerId:E.providerId,modelName:E.modelName},$);else throw new Error("No runtime available")}finally{F.delete(v),x.delete(v);}},abort(v){let E=x.get(v);E&&(E.abort(),x.delete(v)),C&&C.abort(),k&&k.abort(),T&&T.abort?.();},replyPermission(v,E,P){let I=R.get(v);I&&(I.resolve(E),R.delete(v));},getActiveSessions(){return [...F]},setRunMode(v){Wo.isValidMode(v)&&(M=v,m.info("SERVER",`Run mode changed to: ${M}`));},getRunMode(){return M},setSandboxMode(v,E){cp(E);},setApprovalMode(v,E){let P=E==="auto"?"auto":"agent";C&&C.setAgentMode(P),m.info("SERVER",`Approval mode set to: ${E} \u2192 agentMode=${P==="auto"?"AUTO":"AGENT"}`);},async compactSession(v){m.info("SERVER",`Compact session: ${v}`);},clearSession(v){l.clear(),m.info("SERVER",`Cleared session: ${v}`);},getContextHealth(v){return l.checkContextHealth?.()??null},async getSessionInfo(v){return {messageCount:l.length,messages:l.getAll()}},setCompressionMode(v,E){m.info("SERVER",`Compression mode set to: ${E}`);},getMemoryStats(v){return {length:l.length,contextHealth:l.checkContextHealth?.()??null}},clearMemory(v){l.clear();},addMemoryMessage(v,E,P){l.add({role:E,content:P});},getToolList(){return {count:d.length,names:d.map(v=>v.name)}},async reloadTools(v){let E=await un(v,s);d.length=0,d.push(...E),m.info("SERVER",`Reloaded ${d.length} tools for ${v}`);},async setWorkspace(v){let E=await un(v,s);d.length=0,d.push(...E),w.setWorkspace(v),m.info("SERVER",`Workspace switched to: ${v}`);},async startCheckpointWatching(v){return w.startMessage(v)},async stopCheckpointWatching(){await w.stopWatching();},async createCheckpoint(v,E){return w.createCheckpoint(v,E)},async rollbackToCheckpoint(v){return w.rollbackToCheckpoint(v)},async rollbackSingleFile(v){return w.rollbackSingleFile(v)},async reapplySingleFile(v){return w.reapplySingleFile(v)},async getCheckpoints(v,E){return w.getCheckpoints(v,E)},async getCheckpointStats(){return w.getCurrentStats?.()??{created:0,modified:0,deleted:0,directories:0,total:0}},async getCheckpointChanges(){return w.getChangeBuffer?.()??[]},setCheckpointEnabled(v){w.setEnabled(v);},isCheckpointEnabled(){return w.isEnabled()},async cleanupCheckpoints(){await w.cleanup?.();},async getHostStatus(){return {isRunning:F.size>0,currentTask:null,mode:M,workingDirectory:a,uptime:Math.floor(process.uptime()),memoryUsage:{tokensUsed:l.length,contextWindow:128e3,pressure:l.length/128e3}}},async getHostAgents(){return [{id:"main",role:"main",status:F.size>0?"running":"idle"}]},async getHostActivity(v=10){return []},async getHostSession(){return {messageCount:l.length,tokensUsed:0}},async getHostSystem(){let v=null,E="unknown";try{let{execSync:P}=await import('child_process');try{v=P("git rev-parse --abbrev-ref HEAD",{cwd:a,encoding:"utf-8",timeout:5e3}).trim();}catch{}try{E=P("git status --porcelain",{cwd:a,encoding:"utf-8",timeout:5e3}).trim().length===0?"clean":"dirty";}catch{}}catch{}return {platform:process.platform,arch:process.arch,cwd:a,gitBranch:v,gitStatus:E,nodeVersion:process.version}},async hostInterrupt(v){for(let[P,I]of x)I.abort();C&&C.abort(),k&&k.abort(),T&&T.abort?.();let E=F.size>0;return F.clear(),x.clear(),{interrupted:E}},async hostSendCommand(v,E){let P=`cmd-${Date.now()}`,I={prompt:v};return j.chat(P,I).catch(A=>{m.error("SERVER",`hostSendCommand failed: ${A.message}`);}),{queued:true,sessionId:P}},setTTSEnabled(v){let E=u.isEnabled();u.updateConfig({enabled:v,provider:"edge"}),v&&!E&&(u.summarizeFn||u.setSummarizeFn(async(P,I,A)=>{let O=g;if(!O)return P.substring(0,I);let $=Ot.createAdapter(O.protocol,O),D=A||"claude-haiku-4-5-20251001";return (await $.chat([{role:"system",content:`\u4F60\u662F\u4E00\u4E2A\u8BED\u97F3\u6458\u8981\u52A9\u624B\u3002\u628A\u4EE5\u4E0B\u5185\u5BB9\u538B\u7F29\u6210${I}\u5B57\u4EE5\u5185\u7684\u53E3\u8BED\u5316\u6458\u8981\uFF0C\u9002\u5408\u8BED\u97F3\u6717\u8BFB\u3002\u4E0D\u8981\u7528\u4EE3\u7801\u3001markdown\u683C\u5F0F\u3001\u5217\u8868\u3002\u76F4\u63A5\u8BF4\u91CD\u70B9\u3002`},{role:"user",content:P}],{model:D,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||P.substring(0,I)}),u.init().catch(P=>{m.error("SERVER",`TTS init failed: ${P.message}`);})),m.info("SERVER",`TTS ${v?"enabled":"disabled"}`);},isTTSEnabled(){return u.isEnabled()},getTTSConfig(){return t.tts??{enabled:false}},updateTTSConfig(v){let E=u.isEnabled();u.updateConfig(v),v.enabled&&!E&&u.init().catch(P=>{m.error("SERVER",`TTS init failed: ${P.message}`);});}};return j}async function Tk(){let{port:a,workDir:e,daemon:t}=Sk(),s=Oe(),n=s.remote??{};m.info("SERVER",`Starting Neox Server on port ${a}, workDir: ${e}`);let r=new Br,i=new Ns,o=await xk(e,r),l={workDir:e};n.enabled&&n.token&&(l.auth={token:n.token,allowLocalWithoutAuth:true},l.rateLimit={maxRequests:120,windowMs:6e4},l.corsOrigins=["*"],m.info("SERVER","Remote mode enabled \u2014 auth + rateLimit active"));let{app:c,channelRegistry:u}=Hc(l,o,r,i),d=s.channels;d&&(await u.initialize(d),u.setHandler(async g=>{let f=`ch-${g.channelId}-${g.chatId}`;return new Promise(b=>{let y="",w=r.subscribe(f);(async()=>{for await(let C of w){if(C.type==="run_result"){y=C.data?.output||"",w.close();break}if(C.type==="error"){y=`Error: ${C.data?.message||"unknown"}`,w.close();break}}b(y||"[no response]");})(),o.chat(f,{prompt:g.text}).catch(()=>{b("[error processing message]"),w.close();});})}),await u.startAll(),m.info("SERVER","Channel adapters initialized")),await ht.initialize(e),ht.watch(e),m.info("SERVER",`Skills hot-reload active (${ht.size} skills loaded)`);let p=process.env.NEOX_HOST||(n.enabled?n.host||"0.0.0.0":"127.0.0.1");kk({pid:process.pid,port:a,workDir:e,startedAt:Date.now(),daemon:t});let h=()=>{m.info("SERVER","Shutting down..."),ht.stopWatch(),u.stopAll().catch(()=>{}),eg(),i.dispose(),r.dispose(),process.exit(0);};process.on("SIGINT",h),process.on("SIGTERM",h),serve({fetch:c.fetch,port:a,hostname:p},g=>{m.info("SERVER",`Neox Server listening on http://${p}:${g.port}`),process.send&&process.send({type:"ready",port:g.port});});}Tk().catch(a=>{m.error("SERVER","Failed to start server",{error:a}),eg(),process.exit(1);});
3412
3412
  export{hB as readPidFile};