@mk-co/neox-cli 2.0.51 → 2.0.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/main.js +5 -5
- package/dist/sdk/index.js +27 -27
- package/dist/server/main.js +27 -27
- package/package.json +1 -1
package/dist/sdk/index.js
CHANGED
|
@@ -219,9 +219,9 @@ auto_login: { username: "admin", password: "123456" }`,properties:{username:{typ
|
|
|
219
219
|
|
|
220
220
|
window.__NEOX_INJECTED__ = true;
|
|
221
221
|
})();
|
|
222
|
-
`;(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,
|
|
222
|
+
`;(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((L,$)=>(L[$.name]=$.value,L),{})):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(`
|
|
223
223
|
`)||"",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(`
|
|
224
|
-
`)||"",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&&lu.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&&!qg.includes(v)||!n.xhr_only&&lu.includes(v)||x&&!x.test(j))return;`${R.method()}-${j}-${Date.now()}`;let O={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?O.request_body=I.substring(0,A)+"...[truncated]":O.request_body=I;}c.set(j,O),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(),L=n.body_max_length||5e3;A.length>L?(v.response_body=A.substring(0,L),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"),O=document.querySelectorAll("*"),I=0,A=0,L=0,$=Math.min(1e3,O.length),P=Math.max(1,Math.floor(O.length/$));for(let D=0;D<O.length;D+=P){let G=O[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;L=Math.max(L,oe);}let N=O.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:L}}});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 S=C.length;n.status_filter&&(C=C.filter(x=>Hg(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:S,filtered_count:C.length,error_count:T};m.info("BROWSER",`Network: ${S} 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(`
|
|
224
|
+
`)||"",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&&lu.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&&!qg.includes(v)||!n.xhr_only&&lu.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(),L=n.body_max_length||5e3;A.length>L?(v.response_body=A.substring(0,L),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,L=0,$=Math.min(1e3,P.length),D=Math.max(1,Math.floor(P.length/$));for(let O=0;O<P.length;O+=D){let G=P[O],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;L=Math.max(L,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(O=>O.name==="first-paint")?.startTime||0,first_contentful_paint:E.find(O=>O.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:L}}});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 S=C.length;n.status_filter&&(C=C.filter(x=>Hg(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:S,filtered_count:C.length,error_count:T};m.info("BROWSER",`Network: ${S} 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
225
|
`)||"\u2705 \u9875\u9762\u8FD0\u884C\u6B63\u5E38\uFF0C\u672A\u53D1\u73B0\u660E\u663E\u95EE\u9898"}async function cu(a){let e=await Jg(a);if(e)return {url:`http://localhost:${e}`,port:e,protocol:"http",source:"vite.config"};let t=await Kg(a);if(t)return {url:`http://localhost:${t}`,port:t,protocol:"http",source:"package.json"};let s=await Vg(a);if(s)return {url:`http://localhost:${s}`,port:s,protocol:"http",source:"env"};let n=await Yg(a);return {url:`http://localhost:${n}`,port:n,protocol:"http",source:"default"}}async function Jg(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 Kg(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 Vg(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 Yg(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 fa(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 ya(a){let e=await cu(a);if(await fa(e.url))return e;let s=[5173,3e3,8080,5e3,4200,8e3];for(let n of s){let r=`http://localhost:${n}`;if(await fa(r))return {url:r,port:n,protocol:"http",source:"default"}}return null}W();var th="headers.json";function uu(a){try{return new URL(a).hostname}catch{return a}}function du(){let a=Yr();return join(a,th)}function pu(){let a=du();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 mu(a){let e=du();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=uu(a),s=pu(),n=sh(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},mu(s),m.info("HEADERS","Saved headers for domain",{domain:t,headerCount:Object.keys(n).length});}function ba(a){let e=uu(a),t=pu(),s=t[e];return s?(s.lastUsed=Date.now(),mu(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 sh(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 nh=["login","signin","sign-in","sign_in","auth","oauth","sso","account","passport","cas","saml","oidc"],rh=['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")'],ih=['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"]'],oh=['input[type="password"]','input[name="password"]','input[name="pwd"]','input[name="pass"]','input[id="password"]','input[id="pwd"]'],ah=['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 gu(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 lh(a,e){let t=ba(e);return !t||Object.keys(t).length===0?false:(await a.setExtraHTTPHeaders(t),true)}async function va(a,e){let t=a.url(),s=t.toLowerCase();if(t!==e&&nh.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 rh)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 ch(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 ih)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 oh)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 ah)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 ya(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 ha({headless:l,useProfile:c}),t?.("loading",{url:o});let u=await s.newPage(),d=await lh(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 va(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=gu(u,o),y=await ch(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 va(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 S=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:S.console_logs,errors:S.errors,network_requests:S.network_requests,network_stats:S.network_stats,performance:S.performance});return await s.close(),{success:!0,url:o,load_time:S.load_time,timestamp:Date.now(),console_logs:S.console_logs,errors:S.errors,network_requests:S.network_requests,performance:S.performance,screenshot:S.screenshot,summary:`\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F\uFF01
|
|
226
226
|
|
|
227
227
|
${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}
|
|
@@ -683,16 +683,16 @@ readfile(path="src/main.ts", range_start="// BEGIN CONFIG", range_end="// END CO
|
|
|
683
683
|
- \u{1F525} edit_file \u524D\u5FC5\u987B\u5148 readfile(..., for_edit=true) - old_string \u987B\u4ECE\u8F93\u51FA\u7CBE\u786E\u590D\u5236
|
|
684
684
|
- for_edit=true \u4F1A\u5305\u542B COPY \u533A\u5757\uFF08\u8F93\u51FA\u66F4\u5927\uFF09
|
|
685
685
|
- max_output_chars \u53EF\u9650\u5236\u8F93\u51FA\u957F\u5EA6
|
|
686
|
-
- \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: ${Bn})`},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: ${jd})`},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:S,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,
|
|
687
|
-
`);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+
|
|
688
|
-
`)}let qe=ol+12,B=Math.max(5,Math.min(rb,Math.floor($/qe))),re=Q.slice(0,B),V=re.map(ae=>{let k=ae.text.length>ol?`${ae.text.slice(0,ol)}...`:ae.text;return `${String(ae.line).padStart(6)} \u2502 ${k}`}),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,
|
|
689
|
-
`)}catch(ee){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.message}`}}if(N||
|
|
686
|
+
- \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: ${Bn})`},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: ${jd})`},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:S,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=ib(P),A=j===true,L=typeof x=="number"?Math.max(0,x):ui,$=typeof v=="number"&&v>0?Math.floor(v):jd,D=E?Gn:p||(A?sb:Bn);D=Math.min(D,Gn),!p&&w&&(D=Math.max(Pi,L*2+1));let N=Array.isArray(M)&&M.length>0,O=Array.isArray(F)&&F.length>0,G=S===true;if(A&&(N||O||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=Ys(fe).split(`
|
|
687
|
+
`);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}},ke=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,k)=>{le.test(ae)&&Q.push({line:k+1,text:ae}),le.lastIndex=0;});let Be=Lt(ee);if(Q.length===0){let ae=He(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(`
|
|
688
|
+
`)}let qe=ol+12,B=Math.max(5,Math.min(rb,Math.floor($/qe))),re=Q.slice(0,B),V=re.map(ae=>{let k=ae.text.length>ol?`${ae.text.slice(0,ol)}...`:ae.text;return `${String(ae.line).padStart(6)} \u2502 ${k}`}),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(`
|
|
689
|
+
`)}catch(ee){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.message}`}}if(N||O)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(O){let V=Math.max(1,p||L*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=ke(le),qe=[`\u2713 \u6587\u4EF6: ${Lt(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=qe.join(`
|
|
690
690
|
`).length,re=0;for(let[V,pe]of Q.entries()){let Re=He(fe.slice(pe.start-1,pe.end),pe.start),k=`${`# \u533A\u5757 ${V+1}: ${pe.start}-${pe.end}`}
|
|
691
691
|
${Re}`;if(B+k.length+2>$&&re>0)break;qe.push(k,""),B+=k.length+2,re+=1;}return re<Q.length&&qe.push(`\u26A0\uFE0F \u8F93\u51FA\u5DF2\u622A\u65AD\uFF0C\u4EC5\u663E\u793A\u524D ${re} \u4E2A\u533A\u5757`),qe.join(`
|
|
692
692
|
`).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:L}:T&&_&&(q={type:"range",startPattern:T,endPattern:_});let J=ee=>{let ne=[`\u2713 \u6587\u4EF6: ${Lt(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(`
|
|
693
693
|
`).map(qe=>{let B=qe.match(/^\s*\d+\s*│\s?(.*)$/);return B?B[1]:qe}).join(`
|
|
694
694
|
`);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(`
|
|
695
|
-
`)},ie=0,K="",xe=!p;for(;;){let ee=await I.read({path:c,locator:q,mode:"smart",autoFullThreshold:xe?Hs:void 0,chunkSize:
|
|
695
|
+
`)},ie=0,K="",xe=!p;for(;;){let ee=await I.read({path:c,locator:q,mode:"smart",autoFullThreshold:xe?Hs:void 0,chunkSize:D,expandContext:L,useIndex:R});if(!ee.success)return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${ee.error}
|
|
696
696
|
|
|
697
697
|
\u{1F4A1} \u63D0\u793A:
|
|
698
698
|
- \u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E
|
|
@@ -700,7 +700,7 @@ ${Re}`;if(B+k.length+2>$&&re>0)break;qe.push(k,""),B+=k.length+2,re+=1;}return r
|
|
|
700
700
|
|
|
701
701
|
\u{1F4A1} \u5EFA\u8BAE:
|
|
702
702
|
- \u4F7F\u7528 pattern/list_matches \u5B9A\u4F4D\uFF0C\u518D\u7528 anchor_lines/ranges \u6279\u91CF\u8BFB\u53D6
|
|
703
|
-
- \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));
|
|
703
|
+
- \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>=nb||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
|
|
704
704
|
|
|
705
705
|
\u26A1 \u7279\u6027:
|
|
706
706
|
- \u89E3\u6790 TypeScript/JavaScript/Python \u4EE3\u7801\u7ED3\u6784
|
|
@@ -764,7 +764,7 @@ get_definitions(query="User", path="src/auth") \u2192 \u9650\u5B9A\u76EE\u5F55`
|
|
|
764
764
|
get_references(query="UserService")
|
|
765
765
|
get_references(symbol="handleLogin", path="src/auth")
|
|
766
766
|
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(!Bd(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:ab(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 ln(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=[],S=0,T=0,_=0;for(let x of w){if(S>=g)break;try{let R=await ce.readFile(x,"utf-8");if(R.includes("\0"))continue;let j=R.split(`
|
|
767
|
-
`),v=new Set,E=new Map;for(let
|
|
767
|
+
`),v=new Set,E=new Map;for(let P=0;P<j.length&&!(S>=g);P++){let I=j[P],A=y.test(I);if(y.lastIndex=0,A){v.add(P),S++;let L=Math.max(0,P-h),$=Math.min(j.length-1,P+h);for(let D=L;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,L)=>A-L).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=Lt(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: ${S}${S>=g?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(x=>x!=="");for(let x of C){let R=Lt(x.file);F.push(`
|
|
768
768
|
\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(`
|
|
769
769
|
`)}};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 cr(l).getStats();if(!u.hasIndex)return `\u{1F4CA} \u7D22\u5F15\u72B6\u6001: \u672A\u6784\u5EFA
|
|
770
770
|
|
|
@@ -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 lp(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 bl(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(lp(a[n+i])!==lp(e[i])){r=false;break}if(r)return n}return null}var Ob=2e5;function Lb(a,e){let t=a.length,s=e.length;if(t*s>Ob)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 Nb(a,e){if(a.length===0&&e.length===0)return [];let t=Lb(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 $b={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=We(e);Oe(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}=Db(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=bl(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=bl(c,p,b),E=p,
|
|
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=We(e);Oe(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}=Db(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=bl(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=bl(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=bl(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=Nb(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 S=w.join(u);if(S===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,S,"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=We(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=Oe(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=ov({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"),
|
|
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=We(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=Oe(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=ov({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 L=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(L.length>0)return JSON.stringify(ve("search","error",`search failed: invalid regex (${L[0]})`,void 0,{error:`Invalid regex: ${L.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 iv();we.debug("SEARCH",`<<< After isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let O=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 [Oe(T)];if(N){let H=await wl();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),vl.forEach(de=>se.push("-g",de)),se.push("--",T);let be=await ze(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 Oe(Ae)})}let k=l||"**/*",U=j?k:k.replace("**/","");return (await dp(U,{cwd:T,absolute:!0,dot:c,onlyFiles:!0,ignore:vl.map(H=>H.replace("!",""))})).map(H=>Oe(H))})();y();let re=v.map(k=>{let U=k.regex?k.pattern:rp(k.pattern),Z=k.caseInsensitive?"i":"";return {query:k,regex:new RegExp(U,Z)}}),V=[],pe=0;for(let k of B){y();let U=k,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)&&(
|
|
1029
|
+
`).filter(Boolean).map(de=>{let Ae=te__default.isAbsolute(de)?te__default.resolve(de):te__default.resolve(st(),de);return Oe(Ae)})}let k=l||"**/*",U=j?k:k.replace("**/","");return (await dp(U,{cwd:T,absolute:!0,dot:c,onlyFiles:!0,ignore:vl.map(H=>H.replace("!",""))})).map(H=>Oe(H))})();y();let re=v.map(k=>{let U=k.regex?k.pattern:rp(k.pattern),Z=k.caseInsensitive?"i":"";return {query:k,regex:new RegExp(U,Z)}}),V=[],pe=0;for(let k of B){y();let U=k,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(k),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(k=>k!==""),ae=50;return V.slice(0,ae).forEach(k=>Re.push(` ${k}`)),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(k=>k.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:rp(B.pattern),V=B.caseInsensitive?"i":"";return new RegExp(re,V)}),ke=[];if(N){let B=await wl();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),vl.forEach(H=>V.push("-g",H)),V.push("--",re.pattern,T);let pe=B,Re="",ae=0,k="",U=async H=>{let se=`${H} ${V.join(" ")}`;return ke.push(se),ze(H,V,st(),{signal:b})};try{let H=await U(pe);Re=H.stdout,k=H.stderr||"",ae=H.exitCode;}catch(H){if(H?.name==="AbortError"||b?.aborted)throw H;k=H?.message||H?.stderr||String(H),ae=H?.exitCode||2;}if(ae!==0&&ae!==1&&pe!=="rg"&&rv(ae,k)){we.warn("SEARCH","Bundled ripgrep failed, retrying with system rg",{exitCode:ae,error:k,bundledPath:pe});try{let H=await U("rg");Re=H.stdout,k=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);k=`${k}
|
|
1031
1031
|
Fallback rg failed: ${se}`.trim(),ae=H?.exitCode||2;}}if(ae!==0&&ae!==1){let H=k?`
|
|
1032
1032
|
Error: ${k}`:"",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 js=se.data?.stats;js&&typeof js.searches=="number"&&(oe=Math.max(oe,js.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,Mn=de?.lines?.text,hs=Array.isArray(de?.submatches)?de.submatches[0]:void 0;if(!Ae||!et||typeof Mn!="string")continue;let Vc=Mn.replace(/\n$/,""),ea=G.get(Ae)||new Map,Pn=ea.get(et)||{line:Vc,queryIds:new Set};if(Pn.line=Vc,be){Pn.queryIds.add(re.id),Pn.column===void 0&&hs?.start!==void 0&&(Pn.column=hs.start+1);let js=z.get(Ae)||new Set;js.add(re.id),z.set(Ae,js);}ea.set(et,Pn),G.set(Ae,ea);}}}let q=new Set(
|
|
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 js=se.data?.stats;js&&typeof js.searches=="number"&&(oe=Math.max(oe,js.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,Mn=de?.lines?.text,hs=Array.isArray(de?.submatches)?de.submatches[0]:void 0;if(!Ae||!et||typeof Mn!="string")continue;let Vc=Mn.replace(/\n$/,""),ea=G.get(Ae)||new Map,Pn=ea.get(et)||{line:Vc,queryIds:new Set};if(Pn.line=Vc,be){Pn.queryIds.add(re.id),Pn.column===void 0&&hs?.start!==void 0&&(Pn.column=hs.start+1);let js=z.get(Ae)||new Set;js.add(re.id),z.set(Ae,js);}ea.set(et,Pn),G.set(Ae,ea);}}}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 k=Oe(B);if(ee.push({file:k,anchor_lines:ae.slice(0,20),num_lines:O}),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:k,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)=>Oe(B.file).localeCompare(Oe(re.file)));let le=B=>{let V=Oe(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,qe=0;for(let B of J){qe++,qe%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=Oe(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=Oe(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 k of V.matches){if(xe>=p)break;B++,B%re===0&&await C(),k.lineNum>ae+1&&ae>0&&Q.push(" \u2504\u2504\u2504");let U=k.isMatch?"\u25B6":" ";Q.push(`${U}${String(k.lineNum).padStart(5)} \u2502 ${k.line}`),ae=k.lineNum,k.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 "${
|
|
1036
|
+
\u25B8 [${Re}] ${pe} (${V.matchCount} \u5904)`),Q.push("\u2500".repeat(50));let ae=-10;for(let k of V.matches){if(xe>=p)break;B++,B%re===0&&await C(),k.lineNum>ae+1&&ae>0&&Q.push(" \u2504\u2504\u2504");let U=k.isMatch?"\u25B6":" ";Q.push(`${U}${String(k.lineNum).padStart(5)} \u2502 ${k.line}`),ae=k.lineNum,k.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:ke.length>0?ke[0]:void 0}}))}catch(f){return JSON.stringify(ve("search","error",`search failed: ${f.message}`,void 0,{error:f.message}))}}},lv={name:$i.name,description:$i.description,parameters:$i.parameters,permission:{category:"read",allowInAskMode:true},async function(a){return Yd(a)}},cv={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 Yi=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 qi(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new Ji,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new Hi({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=Pl(this.currentMode),this.permissionManager=e.permissionManager??new ls({defaultPermission:"ask"}),this.loopDetector=Np(),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=Pl(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??$p,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??$p}, safety=${i})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Wv){for await(let i of e)yield i;return}let s=e[Symbol.asyncIterator](),n=t?new Promise((i,o)=>{t.aborted?o(Vi()):t.addEventListener("abort",()=>o(Vi()),{once:true});}):null,r=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw Vi()}let i=r?Uv:Gv,o=null,l=new Promise((c,u)=>{o=setTimeout(()=>{u(Bv(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 Is.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 ll(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,S=0,T=0,_=[],M=this.isExecutionOrientedTask(e),F=0,x=Kt.streamMaxRetries,R=false,j=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:Cp,v=j===0||j===1/0,E=Fp(this.config.maxToolCalls,Sp),O=Fp(this.config.maxRuntimeMs,kp);for(;v||p<j;){if(s?.aborted){w="interrupted",b=true,yield {type:"error",error:"Task interrupted by user."};break}if(O!==null&&Date.now()-d>=O){w="runtime_limit",b=true,yield {type:"error",error:`Reached max runtime (${nt(O)}). 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 L=tt(this.memory.getMessagesForLLM()),$=this.maxInputTokens*.97;L>$&&(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 L=this.memory.cleanupEphemeral();L>0&&m.info("Runner",`Cleaned ${L} 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 L=this.memory.getMessagesForLLM();if(m.info("LLM",`Request: model=${this.model}, messages=${L.length}, tools=${this.tools.length}`),m.debug("LLM","Request messages",{messageCount:L.length,lastMessage:L[L.length-1]?.content?.toString().substring(0,200)}),process.env.CLI_DEBUG==="1"){let q=L.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 ke={role:"assistant",content:(N||"").trimEnd()};if(D&&(ke.reasoning_content=D),G.length>0&&(ke.thinking_blocks=G),z.length>0&&(ke.tool_calls=z.map(q=>({...q,function:{...q.function,arguments:q.function.arguments}}))),this.memory.add(ke),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 k of z){let U=k.function.arguments||"";if(q.test(U)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${k.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:k.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 k=z.map(Z=>Z.function.name),U=[...new Set(k)];U.length===1&&k.length>1?m.info("RUNNER",`\u{1F504} Parallel calls: ${k.length}x ${U[0]} (different parameters)`):m.info("RUNNER",`\u{1F504} Parallel calls: ${k.join(", ")}`);}let J=new Map;for(let k of z)J.set(k.id,bn(k.function.arguments));for(let k of z){g++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:k.id,name:k.function.name,arguments:k.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:k.id,name:k.function.name};let Z=J.get(k.id),H=Z?.ok??!1;H?Z?.repaired&&m.warn("RUNNER","Tool arguments repaired from non-standard JSON",{tool:k.function.name,callId:k.id}):ge.toolError(k.function.name,`Invalid JSON arguments (${Z?.reason||"parse failed"}): ${k.function.arguments.substring(0,200)}...`),yield {type:"tool_call_done",id:k.id,name:k.function.name,arguments:k.function.arguments,success:H},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:k.id,name:k.function.name,arguments:k.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(k=>k.function.name)});for(let k of z){let U=J.get(k.id);if(!U?.ok){let de=`Invalid JSON arguments for tool "${k.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:k.id,name:k.function.name,output:de,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:k.id,name:k.function.name,output:de,success:!1},this.memory.addToolResult(k.id,k.function.name,de),this.loopDetector.updateLastStatus("error"),ie.add(k.id);continue}let Z=U.args,H=this.loopDetector.detect(k.function.name,Z);if(this.loopDetector.record(k.function.name,Z),H===0)continue;let se=this.loopDetector.generateIntervention(H,k.function.name,Z);if(this.memory.add({role:"system",content:se.message}),H===2&&eu(k.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:k.id,name:k.function.name,output:se.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:k.id,name:k.function.name,output:se.message,success:!1},this.memory.addToolResult(k.id,k.function.name,se.message),this.loopDetector.updateLastStatus("error"),ie.add(k.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(k=>!ie.has(k.id)):z,fe=new Set(this.modeStrategy.filterTools(this.tools).map(k=>k.name)),ne=k=>k.replace(/["\s/>]+$/g,"").trim(),le=[];for(let k of ee){let U=ne(k.function.name);if(fe.has(U)||fe.has(k.function.name)){le.push(k);continue}let Z=`Tool "${k.function.name}" is not allowed in ${this.currentMode} mode`;ge.toolError(k.function.name,Z),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:k.id,name:k.function.name,output:Z,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:k.id,name:k.function.name,output:Z,success:!1},this.memory.addToolResult(k.id,k.function.name,Z),m.info("PERMISSION",`Tool blocked by mode: ${k.function.name} - ${Z}`);}if(le.length===0)continue;let Q=le.map(k=>({id:k.id,type:"function",function:{name:k.function.name,arguments:(()=>{let U=J.get(k.id);return U?.ok?JSON.stringify(U.args):k.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 k=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 jp(s,async()=>this.permissionManager.checkPermission(se,H));if(!be.allowed){k.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=>!k.has(U.id)),Q=Q.filter(U=>!k.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 k=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 jp(s,async()=>Is.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:se,agent_name:this.agentName,tool:be}));if(!Y.should_execute){k.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),xl(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=>!k.has(U.id)),Q=Q.filter(U=>!k.has(U.id)),Q.length===0)continue}process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${Q.length}`);let qe=await this.parallelExecutor.execute(Q,this.tools,k=>{if(ge.toolCall(k.name,{}),k.success){let Z=typeof k.output=="string"?k.output.length:JSON.stringify(k.output).length;ge.toolResult(k.name,!0,Z,k.executionTime||0);}else ge.toolError(k.name,k.output);let U={type:"tool_call_output_item",id:k.id,name:k.name,output:k.output,success:k.success,timestamp:Date.now()};},s),B=0,re=0,V=0,pe=!1;for(let k of qe.results){if(this.toolMetricsHistory.push({name:k.name,duration:k.executionTime||0,success:k.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:k.id,name:k.name,output:k.output,success:k.success,timestamp:Date.now()}},yield {type:"tool_output",id:k.id,name:k.name,output:k.output,success:k.success},(k.name==="update_plan"||k.name==="call_tool")&&k.success)try{m.info("PLAN_UPDATE","\u{1F525} Detected plan-related tool call",{resultId:k.id,toolName:k.name,toolCallsCount:z.length});let Y=z.find(de=>de.id===k.id);if(Y){m.info("PLAN_UPDATE","\u{1F525} Found original call",{callId:Y.id,argsLength:Y.function.arguments?.length});let de=bn(Y.function.arguments||"{}");if(!de.ok)throw new Error(de.reason||"Invalid update_plan arguments");let Ae=de.args,et=null;if(k.name==="update_plan"?et=Ae:k.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:k.id,toolName:k.name,callToolName:Ae?.name});else {let Mn=!0;if(typeof k.output=="string")try{let hs=JSON.parse(k.output);hs&&typeof hs=="object"&&"success"in hs&&(Mn=hs.success!==!1);}catch{}Mn?(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:k.id});}}else m.warn("PLAN_UPDATE","\u274C Could not find original tool call",{resultId:k.id,availableIds:z.map(de=>de.id)});}catch(Y){m.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:Y});}let Z=typeof k.output=="string"?Bp(k.output):Bp(JSON.stringify(k.output));Z=this.enrichToolResult(Z,k.name,k.executionTime||0);let H=z.find(Y=>Y.id===k.id),se={};if(H){let Y=bn(H.function.arguments||"{}");Y.ok&&(se=Y.args);}if(this.toolOutputGuardrails.length>0)try{let Y=this.tools.find(de=>de.name===k.name);if(Y){let de={tool_name:k.name,tool_input:se,tool_call_id:k.id},Ae=await Is.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:de,agent_name:this.agentName,tool:Y,output:k.output});Ae.should_use_output||(Z=Ae.replacement_message||"[Output blocked by guardrail]",ge.toolError(k.name,"Output blocked by guardrail"));}}catch(Y){Y instanceof yt&&ge.toolError(k.name,`Output guardrail tripwire triggered: ${Y.message}`);}if(!k.success&&typeof k.output=="string"){let Y=k.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}}xl(this.runContext,k.name,se,k.success),m.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${k.name}`,{toolName:k.name,success:k.success,rawLength:typeof k.output=="string"?k.output.length:JSON.stringify(k.output).length,truncatedLength:Z.length,outputPreview:Z.substring(0,500)}),this.memory.addToolResult(k.id,k.name,Z);let be=k.success?"success":"error";try{let Y=typeof k.output=="string"?k.output:JSON.stringify(k.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:k.name,status:be,executionTime:k.executionTime||0}),_.length>24&&_.shift(),be==="error"?re++:be==="already_done"?(V++,this.isVerificationTool(k.name)&&(pe=!0)):(B++,this.isVerificationTool(k.name)&&(pe=!0)),be==="error"){let Y=(C.get(k.name)||0)+1;if(C.set(k.name,Y),k.name==="edit_file"&&(Y===2||Y===3)){let de=typeof k.output=="string"?k.output:JSON.stringify(k.output),Ae=k.name,et=Lp(Ae,de);this.memory.add({role:"system",content:et});}}else C.set(k.name,0);}if(p>0&&p%5===0){let k=this.buildPerformanceHint();k&&(this.memory.add({role:"system",content:k}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",k));}let Re=B+V>0;if(S=re>0&&!Re?S+1:0,process.env.CLI_DEBUG==="1"&&m.debug("LOOP_GATE","Iteration quality",{iteration:p,executionTask:M,success:B,alreadyDone:V,error:re,lowProgressStreak:S,verificationSuccess:pe}),M&&S>=2&&(this.memory.add({role:"system",content:this.buildLowProgressReplanPrompt(S)}),T++,S=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"&&qe.stats&&(yield {type:"raw_response_event",data:{type:"parallel_execution.stats",stats:qe.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 Is.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(L){if(L?.type==="stream_retry"){R=true,yield L;continue}let $=L instanceof Ce?L:ft(L);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=br($.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 fn(G),p--;continue}let P=Wi($),N=$.message;P&&!N.includes(P)&&(N=`${N}
|
|
1487
|
+
`;return l+d+c}var Yi=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 qi(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new Ji,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new Hi({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=Pl(this.currentMode),this.permissionManager=e.permissionManager??new ls({defaultPermission:"ask"}),this.loopDetector=Np(),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=Pl(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??$p,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??$p}, safety=${i})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Wv){for await(let i of e)yield i;return}let s=e[Symbol.asyncIterator](),n=t?new Promise((i,o)=>{t.aborted?o(Vi()):t.addEventListener("abort",()=>o(Vi()),{once:true});}):null,r=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw Vi()}let i=r?Uv:Gv,o=null,l=new Promise((c,u)=>{o=setTimeout(()=>{u(Bv(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 Is.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 ll(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,S=0,T=0,_=[],M=this.isExecutionOrientedTask(e),F=0,x=Kt.streamMaxRetries,R=false,j=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:Cp,v=j===0||j===1/0,E=Fp(this.config.maxToolCalls,Sp),P=Fp(this.config.maxRuntimeMs,kp);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 L=tt(this.memory.getMessagesForLLM()),$=this.maxInputTokens*.97;L>$&&(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 L=this.memory.cleanupEphemeral();L>0&&m.info("Runner",`Cleaned ${L} 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 L=this.memory.getMessagesForLLM();if(m.info("LLM",`Request: model=${this.model}, messages=${L.length}, tools=${this.tools.length}`),m.debug("LLM","Request messages",{messageCount:L.length,lastMessage:L[L.length-1]?.content?.toString().substring(0,200)}),process.env.CLI_DEBUG==="1"){let q=L.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="",O="",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&&(O+=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 ke={role:"assistant",content:(N||"").trimEnd()};if(O&&(ke.reasoning_content=O),G.length>0&&(ke.thinking_blocks=G),z.length>0&&(ke.tool_calls=z.map(q=>({...q,function:{...q.function,arguments:q.function.arguments}}))),this.memory.add(ke),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 k of z){let U=k.function.arguments||"";if(q.test(U)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${k.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:k.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 k=z.map(Z=>Z.function.name),U=[...new Set(k)];U.length===1&&k.length>1?m.info("RUNNER",`\u{1F504} Parallel calls: ${k.length}x ${U[0]} (different parameters)`):m.info("RUNNER",`\u{1F504} Parallel calls: ${k.join(", ")}`);}let J=new Map;for(let k of z)J.set(k.id,bn(k.function.arguments));for(let k of z){g++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:k.id,name:k.function.name,arguments:k.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:k.id,name:k.function.name};let Z=J.get(k.id),H=Z?.ok??!1;H?Z?.repaired&&m.warn("RUNNER","Tool arguments repaired from non-standard JSON",{tool:k.function.name,callId:k.id}):ge.toolError(k.function.name,`Invalid JSON arguments (${Z?.reason||"parse failed"}): ${k.function.arguments.substring(0,200)}...`),yield {type:"tool_call_done",id:k.id,name:k.function.name,arguments:k.function.arguments,success:H},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:k.id,name:k.function.name,arguments:k.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(k=>k.function.name)});for(let k of z){let U=J.get(k.id);if(!U?.ok){let de=`Invalid JSON arguments for tool "${k.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:k.id,name:k.function.name,output:de,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:k.id,name:k.function.name,output:de,success:!1},this.memory.addToolResult(k.id,k.function.name,de),this.loopDetector.updateLastStatus("error"),ie.add(k.id);continue}let Z=U.args,H=this.loopDetector.detect(k.function.name,Z);if(this.loopDetector.record(k.function.name,Z),H===0)continue;let se=this.loopDetector.generateIntervention(H,k.function.name,Z);if(this.memory.add({role:"system",content:se.message}),H===2&&eu(k.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:k.id,name:k.function.name,output:se.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:k.id,name:k.function.name,output:se.message,success:!1},this.memory.addToolResult(k.id,k.function.name,se.message),this.loopDetector.updateLastStatus("error"),ie.add(k.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(k=>!ie.has(k.id)):z,fe=new Set(this.modeStrategy.filterTools(this.tools).map(k=>k.name)),ne=k=>k.replace(/["\s/>]+$/g,"").trim(),le=[];for(let k of ee){let U=ne(k.function.name);if(fe.has(U)||fe.has(k.function.name)){le.push(k);continue}let Z=`Tool "${k.function.name}" is not allowed in ${this.currentMode} mode`;ge.toolError(k.function.name,Z),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:k.id,name:k.function.name,output:Z,success:!1,timestamp:Date.now()}},yield {type:"tool_output",id:k.id,name:k.function.name,output:Z,success:!1},this.memory.addToolResult(k.id,k.function.name,Z),m.info("PERMISSION",`Tool blocked by mode: ${k.function.name} - ${Z}`);}if(le.length===0)continue;let Q=le.map(k=>({id:k.id,type:"function",function:{name:k.function.name,arguments:(()=>{let U=J.get(k.id);return U?.ok?JSON.stringify(U.args):k.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 k=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 jp(s,async()=>this.permissionManager.checkPermission(se,H));if(!be.allowed){k.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=>!k.has(U.id)),Q=Q.filter(U=>!k.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 k=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 jp(s,async()=>Is.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:se,agent_name:this.agentName,tool:be}));if(!Y.should_execute){k.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),xl(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=>!k.has(U.id)),Q=Q.filter(U=>!k.has(U.id)),Q.length===0)continue}process.env.CLI_DEBUG==="1"&&m.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${Q.length}`);let qe=await this.parallelExecutor.execute(Q,this.tools,k=>{if(ge.toolCall(k.name,{}),k.success){let Z=typeof k.output=="string"?k.output.length:JSON.stringify(k.output).length;ge.toolResult(k.name,!0,Z,k.executionTime||0);}else ge.toolError(k.name,k.output);let U={type:"tool_call_output_item",id:k.id,name:k.name,output:k.output,success:k.success,timestamp:Date.now()};},s),B=0,re=0,V=0,pe=!1;for(let k of qe.results){if(this.toolMetricsHistory.push({name:k.name,duration:k.executionTime||0,success:k.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:k.id,name:k.name,output:k.output,success:k.success,timestamp:Date.now()}},yield {type:"tool_output",id:k.id,name:k.name,output:k.output,success:k.success},(k.name==="update_plan"||k.name==="call_tool")&&k.success)try{m.info("PLAN_UPDATE","\u{1F525} Detected plan-related tool call",{resultId:k.id,toolName:k.name,toolCallsCount:z.length});let Y=z.find(de=>de.id===k.id);if(Y){m.info("PLAN_UPDATE","\u{1F525} Found original call",{callId:Y.id,argsLength:Y.function.arguments?.length});let de=bn(Y.function.arguments||"{}");if(!de.ok)throw new Error(de.reason||"Invalid update_plan arguments");let Ae=de.args,et=null;if(k.name==="update_plan"?et=Ae:k.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:k.id,toolName:k.name,callToolName:Ae?.name});else {let Mn=!0;if(typeof k.output=="string")try{let hs=JSON.parse(k.output);hs&&typeof hs=="object"&&"success"in hs&&(Mn=hs.success!==!1);}catch{}Mn?(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:k.id});}}else m.warn("PLAN_UPDATE","\u274C Could not find original tool call",{resultId:k.id,availableIds:z.map(de=>de.id)});}catch(Y){m.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:Y});}let Z=typeof k.output=="string"?Bp(k.output):Bp(JSON.stringify(k.output));Z=this.enrichToolResult(Z,k.name,k.executionTime||0);let H=z.find(Y=>Y.id===k.id),se={};if(H){let Y=bn(H.function.arguments||"{}");Y.ok&&(se=Y.args);}if(this.toolOutputGuardrails.length>0)try{let Y=this.tools.find(de=>de.name===k.name);if(Y){let de={tool_name:k.name,tool_input:se,tool_call_id:k.id},Ae=await Is.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:de,agent_name:this.agentName,tool:Y,output:k.output});Ae.should_use_output||(Z=Ae.replacement_message||"[Output blocked by guardrail]",ge.toolError(k.name,"Output blocked by guardrail"));}}catch(Y){Y instanceof yt&&ge.toolError(k.name,`Output guardrail tripwire triggered: ${Y.message}`);}if(!k.success&&typeof k.output=="string"){let Y=k.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}}xl(this.runContext,k.name,se,k.success),m.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${k.name}`,{toolName:k.name,success:k.success,rawLength:typeof k.output=="string"?k.output.length:JSON.stringify(k.output).length,truncatedLength:Z.length,outputPreview:Z.substring(0,500)}),this.memory.addToolResult(k.id,k.name,Z);let be=k.success?"success":"error";try{let Y=typeof k.output=="string"?k.output:JSON.stringify(k.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:k.name,status:be,executionTime:k.executionTime||0}),_.length>24&&_.shift(),be==="error"?re++:be==="already_done"?(V++,this.isVerificationTool(k.name)&&(pe=!0)):(B++,this.isVerificationTool(k.name)&&(pe=!0)),be==="error"){let Y=(C.get(k.name)||0)+1;if(C.set(k.name,Y),k.name==="edit_file"&&(Y===2||Y===3)){let de=typeof k.output=="string"?k.output:JSON.stringify(k.output),Ae=k.name,et=Lp(Ae,de);this.memory.add({role:"system",content:et});}}else C.set(k.name,0);}if(p>0&&p%5===0){let k=this.buildPerformanceHint();k&&(this.memory.add({role:"system",content:k}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",k));}let Re=B+V>0;if(S=re>0&&!Re?S+1:0,process.env.CLI_DEBUG==="1"&&m.debug("LOOP_GATE","Iteration quality",{iteration:p,executionTask:M,success:B,alreadyDone:V,error:re,lowProgressStreak:S,verificationSuccess:pe}),M&&S>=2&&(this.memory.add({role:"system",content:this.buildLowProgressReplanPrompt(S)}),T++,S=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"&&qe.stats&&(yield {type:"raw_response_event",data:{type:"parallel_execution.stats",stats:qe.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 Is.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(L){if(L?.type==="stream_retry"){R=true,yield L;continue}let $=L instanceof Ce?L:ft(L);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=br($.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 fn(G),p--;continue}let D=Wi($),N=$.message;D&&!N.includes(D)&&(N=`${N}
|
|
1488
1488
|
|
|
1489
|
-
\u{1F4A1} Suggestion: ${
|
|
1489
|
+
\u{1F4A1} Suggestion: ${D}`),b=true;let O=Ip(N,{providerName:this.providerName});ge.agentError(O),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:O};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 Kp(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 Ol="You are Claude Code, Anthropic's official CLI for Claude.",uw=["claude-code-20250219","interleaved-thinking-2025-05-14"],to="2023-06-01",so=64,dw=1024;var Vp=18e4,Yp=6e4,Xp={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"},Ll={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"},wn=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||uw,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?Ol:null),this.sanitizeToolsForProxy=false,this.disableCaching=e.disableCaching||false,this.client=ew.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=mn("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: ${Kp(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,S)=>S?.content?typeof S.content=="string"?C+S.content.length:Array.isArray(S.content)?C+S.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=Ui(u.response?.headers),h=br(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 Ms(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?Ll[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}`,
|
|
1699
|
-
`),L="";for(let $ of A){let
|
|
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?Ll[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: ${Kp(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(),S=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
|
+
`),L="";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)),L+=N;}else L+=D;}if(!(!L||L==="[DONE]"))try{let $=L.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(),O=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(O.yield){let G=Date.now();if(yield O.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(O.roleSent!==void 0&&(b=O.roleSent),O.incrementToolIndex&&f++,O.usage&&(y=O.usage),O.error)throw new Error(O.error);O.contentBlockStart&&(T++,O.blockType&&(M=O.blockType)),O.contentBlockStop&&(S++,M==="thinking"&&(yield {choices:[{delta:{reasoning_complete:!0},index:0}]}),M=null),O.messageStop&&(w=!0),O.stopReason&&(_=O.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:S,toolCallsCount:g.length,duration:`${R}ms`}),!w&&!_){let v=new Error(`Stream incomplete: message_stop not received (blocks: ${T} started, ${S} completed)`);throw v.code="STREAM_INCOMPLETE",v.isNetworkInterrupt=!0,this.debugLog("Stream incomplete detected",{messageStopReceived:w,stopReason:_,contentBlocksStarted:T,contentBlocksCompleted:S,toolCallsCount:g.length,duration:`${R}ms`}),v}if(T!==S)if(_==="max_tokens")this.debugLog("Content blocks mismatch due to max_tokens (expected, not an error)",{contentBlocksStarted:T,contentBlocksCompleted:S,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, ${S} completed)`);throw v.code="STREAM_INCOMPLETE",v.isNetworkInterrupt=!0,this.debugLog("Content blocks mismatch",{contentBlocksStarted:T,contentBlocksCompleted:S,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=Ui(u.response?.headers),b=br(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 Ms(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:Ol}),n&&o.push({type:"text",text:`
|
|
1700
1700
|
`+n})):(o.push({type:"text",text:Ol,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>Rr){if(this.debugLog("Request body exceeds limit",{bodySize:s,limit:Rr,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 ${(Rr/1024/1024).toFixed(1)}MB limit. Request may fail.`);}else s>lw&&this.debugLog("Request body approaching limit",{bodySize:s,limit:Rr,percentage:(s/Rr*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 Er(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 Fl(a,e){return a.length<=e?a:a.slice(0,e-1).trimEnd()+"\u2026"}function Rw(a){return a.replace(/\s+/g," ").trim()}function $l(a,e){if(a.length===0)return {summary:"",lines:0};let t=[];for(let n of a){if(t.length>=Cw)break;let r=n.role==="assistant"?"Assistant":n.role==="user"?"User":n.role,i=me(n.content),l=(i?Rw(i):"")||(n.tool_calls?.length?`Tool calls: ${n.tool_calls.map(c=>c.function.name).join(", ")}`:"No textual content");t.push(`- [${r}] ${Fl(l,Sw)}`);}return {summary:`${e}
|
|
1811
1811
|
${t.join(`
|
|
1812
|
-
`)}`,lines:t.length}}async function jl(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((
|
|
1812
|
+
`)}`,lines:t.length}}async function jl(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((O,G)=>({entry:O,index:G})).filter(({entry:O})=>O.item.type==="message");if(u.length===0)return null;u.filter(({entry:O})=>O.item.data.role==="system");let p=u.filter(({entry:O})=>O.item.data.role!=="system");if(p.length===0)return null;let h=0,g=p.length;for(let O=p.length-1;O>=0;O--){let G=p[O].entry.item.data;if(h+=Er(G),h>=l){g=O;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:O})=>O.item.data);if(f.length===0)return null;let b={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let O of f){let G=Er(O);O.role==="user"?b.userTokens+=G:O.role==="assistant"?b.assistantTokens+=G:O.role==="tool"&&(b.toolTokens+=G),b.totalTokens+=G;}let y=p.slice(g).map(({entry:O})=>O.item.data),w={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let O of y){let G=Er(O);O.role==="user"?w.userTokens+=G:O.role==="assistant"?w.assistantTokens+=G:O.role==="tool"&&(w.toolTokens+=G),w.totalTokens+=G;}let C=b.totalTokens;r?.("summarizing",`Summarizing ${f.length} messages with AI...`);let S=Tw(f),T=S==="zh"?xw:kw,_=_w(f),M,F;try{let O=new AbortController,G=setTimeout(()=>O.abort(),i),z=o?AbortSignal.any([o,O.signal]):O.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}=$l(f,Nl);M=oe;}}catch(O){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",O.message);let{summary:G}=$l(f,Nl);M=G;}r?.("saving","Saving compacted history...");let R=`${S==="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},
|
|
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:Fl(M,2e3),originalCount:f.length,compactedAt:new Date().toISOString(),method:"smart",llmTokensUsed:F}},timestamp:v,seq:0},I=[],A=false,L=new Set(p.slice(0,g).map(({entry:O})=>O));for(let O of c){if(O.item.type!=="message"){I.push({...O});continue}if(O.item.data.role==="system"){I.push({...O});continue}L.has(O)?A||(I.push({...E}),I.push({...P}),A=true):I.push({...O});}if(!A)return null;let $=I.map((O,G)=>({item:O.item,timestamp:O.timestamp??Date.now(),seq:G}));await e.replaceTimeline($);let D=Er({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 sm(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+=Er(_),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}=$l(u,a.summaryHeader??Nl);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:Fl(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 S=y.map((T,_)=>({item:T.item,timestamp:T.timestamp??Date.now(),seq:_}));return await e.replaceTimeline(S),{removedMessages:u.length,keptMessages:h,summaryText:d,summaryLines:p}}function nm(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 co=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()}},uo=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 Ns(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 rm(a,e){let t=nm(a);if(t)return `MCP ${t.serverId}/${t.toolName}`;switch(a){case "readfile":let s=Ns(a,e);return s?`Reading ${s}`:"Reading file";case "write_file":case "create_file":let n=Ns(a,e);return n?`Writing ${n}`:"Writing file";case "edit_file":case "Edit":let r=Ns(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 ${Ns(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 po=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 Aw={default:["Thinking...","Processing...","Analyzing...","Pondering...","Contemplating..."]};var mo={};function Ew(a,e,t=true){mo[e]||(mo[e]=0);let s=mo[e]%a.length,n=a[s];return t&&(mo[e]=(s+1)%a.length),n}function im(){let a=Aw.default;return Ew(a,"default")}function om(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 am(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 lm(a,e,t){let s=wp(a,e,t),n=Wi(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 go=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 um=12e3,ho=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 go;descriptionExtractor=new co;commandGenerator=new uo;lastAssistantMessage="";batchDetector=new po;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=Eu(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: ${S(C.userTokens)} \u2022 Assistant: ${S(C.assistantTokens)} \u2022 Tool: ${S(C.toolTokens)}`,b+=`
|
|
1842
1842
|
\u51C0\u8282\u7701: ${S(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 sm({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=Bs(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 S=()=>{this.shouldInterrupt=true,this.abortController?.abort();};C.addEventListener("abort",S,{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,S=await this.sessionSync.createCheckpoint(`turn_${C}`);this.emitEvent({type:"checkpoint",id:S,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 S=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(S++,process.env.CLI_DEBUG==="1"&&m.debug("TASK",` \u4E8B\u4EF6 #${S}: ${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:im()}),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((L,$)=>{let
|
|
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
|
|
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=Bs(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 S=()=>{this.shouldInterrupt=true,this.abortController?.abort();};C.addEventListener("abort",S,{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,S=await this.sessionSync.createCheckpoint(`turn_${C}`);this.emitEvent({type:"checkpoint",id:S,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 S=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(S++,process.env.CLI_DEBUG==="1"&&m.debug("TASK",` \u4E8B\u4EF6 #${S}: ${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:im()}),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((L,$)=>{let D=typeof L.content=="string"?L.content.length:JSON.stringify(L.content).length;m.debug("CONTEXT",` [${$}] role=${L.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 O=f.match(/"file_path"\s*:\s*"([^"]+)"/),G=f.match(/"content"\s*:\s*"/);if(O&&G){let z=O[1],oe=f.indexOf('"',G.index+9+1)+1;if(oe>0){let ue=f.substring(oe),ke=-1,q=0;for(let ne=0;ne<ue.length;ne++)if(ue[ne]==="\\")q++;else {if(ue[ne]==='"'&&q%2===0){ke=ne;break}q=0;}ke>0&&(ue=ue.substring(0,ke));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(),L=am(v.name,A);if(L.isTruncated){process.env.CLI_DEBUG_CONSOLE==="1"&&m.log("MK",`[AgentHost] \u26A0\uFE0F Truncation detected: ${L.reason}`);let K=om(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: ${L.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=Ns(P,N),G=this.descriptionExtractor.extractFromAssistantMessage(h,P);G||(G=rm(P,N));let z=this.commandGenerator.generateEquivalentCommand(P,N),oe=v.id||`tool-${++this.toolCallIdCounter}-${Math.floor(Date.now())}`,ue=Date.now(),ke=this.batchDetector.detectBatch(oe,P,D||"",N,ue);this.recentToolCalls.set(oe,{toolId:oe,batchId:ke.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:ke.type==="batch",batchId:ke.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 L=lm(v.name,v.arguments||"",A),$=L.category==="tool_truncated"?`\u274C Tool ${v.name}: content truncated during streaming`:`\u274C Tool ${v.name}: ${L.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:L.code,_errorCategory:L.category,_errorMessage:L.message,_suggestion:L.suggestion,_retryable:L.retryable},timestamp:Date.now()});let P=v.id;P&&this.recentToolCalls.delete(P),this.emitEvent({type:"tool_output",name:v.name,output:JSON.stringify(L),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),L=A.length,$=v.success??!0,P=A.slice(0,um),N=A.length>um;m.info("TOOL",`\u{1F916} [AGENT] Result: ${v.name} ${$?"\u2713":"\u2717"}`,{success:$,resultLength:L,outputString:A});let D=v.id,G=D?this.recentToolCalls.get(D):void 0,{batchId:z,targetPath:oe,args:ue}=G||{},ke=G?.toolName||v.name,q=ue||{},J=oe||Ns(ke,q)||(q&&typeof q.directory=="string"?q.directory:void 0),ie=this.buildToolOutputSummary(ke,q,A,L,J,$);if(m.info("TOOL",`\u{1F525} tool_output \u2192 emitting tool_call_end: realName=${ke} toolId=${D} summary=${ie?.substring(0,60)}`),$&&J&&this.batchDetector.recordCompletion(ke,J),this.emitEvent({type:"tool_call_end",name:ke,success:$,resultLength:L,timestamp:Date.now(),toolId:D,batchId:z,targetPath:J,summary:ie,output:P,outputTruncated:N,args:q}),ke==="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(ke==="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(ke==="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,L=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+=L,process.env.CLI_DEBUG&&(m.debug("CONTEXT","token_usage event received:"),m.debug("CONTEXT",` actualInputTokens=${A}, actualOutputTokens=${L}`),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,L,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:L,totalTokens:G+L,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 L=A.droppedMessages||0,$=A.compressedMessages||0;if(L>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 ${L} \u6761\u6D88\u606F${$>0?`\uFF0C\u538B\u7F29 ${$} \u6761`:""}\uFF0C\u8282\u7701\u7EA6 ${P.toLocaleString()} tokens`),this.emitEvent({type:"status",status:"compacting",message:`Context compacted: -${L} 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 O=v;this.emitEvent({type:"stream_recovered",attempt:O.attempt,maxRetries:O.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: ${S}`),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(),L=am(v.name,A);if(L.isTruncated){process.env.CLI_DEBUG_CONSOLE==="1"&&m.log("MK",`[AgentHost] \u26A0\uFE0F Truncation detected: ${L.reason}`);let K=om(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: ${L.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 O=Ns(D,N),G=this.descriptionExtractor.extractFromAssistantMessage(h,D);G||(G=rm(D,N));let z=this.commandGenerator.generateEquivalentCommand(D,N),oe=v.id||`tool-${++this.toolCallIdCounter}-${Math.floor(Date.now())}`,ue=Date.now(),ke=this.batchDetector.detectBatch(oe,D,O||"",N,ue);this.recentToolCalls.set(oe,{toolId:oe,batchId:ke.batchId,targetPath:O,args:N,toolName:D});let q={targetPath:O,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:O,description:G,equivalentCommand:z,timestamp:ue+Math.random()*.1,toolId:oe,isBatch:ke.type==="batch",batchId:ke.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 L=lm(v.name,v.arguments||"",A),$=L.category==="tool_truncated"?`\u274C Tool ${v.name}: content truncated during streaming`:`\u274C Tool ${v.name}: ${L.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:L.code,_errorCategory:L.category,_errorMessage:L.message,_suggestion:L.suggestion,_retryable:L.retryable},timestamp:Date.now()});let D=v.id;D&&this.recentToolCalls.delete(D),this.emitEvent({type:"tool_output",name:v.name,output:JSON.stringify(L),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),L=A.length,$=v.success??!0,D=A.slice(0,um),N=A.length>um;m.info("TOOL",`\u{1F916} [AGENT] Result: ${v.name} ${$?"\u2713":"\u2717"}`,{success:$,resultLength:L,outputString:A});let O=v.id,G=O?this.recentToolCalls.get(O):void 0,{batchId:z,targetPath:oe,args:ue}=G||{},ke=G?.toolName||v.name,q=ue||{},J=oe||Ns(ke,q)||(q&&typeof q.directory=="string"?q.directory:void 0),ie=this.buildToolOutputSummary(ke,q,A,L,J,$);if(m.info("TOOL",`\u{1F525} tool_output \u2192 emitting tool_call_end: realName=${ke} toolId=${O} summary=${ie?.substring(0,60)}`),$&&J&&this.batchDetector.recordCompletion(ke,J),this.emitEvent({type:"tool_call_end",name:ke,success:$,resultLength:L,timestamp:Date.now(),toolId:O,batchId:z,targetPath:J,summary:ie,output:D,outputTruncated:N,args:q}),ke==="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(ke==="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(ke==="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:O});}break;case "token_usage":if(v.usage){p=v.usage.total_tokens;let A=v.usage.prompt_tokens||0,L=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,O=$||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+=L,process.env.CLI_DEBUG&&(m.debug("CONTEXT","token_usage event received:"),m.debug("CONTEXT",` actualInputTokens=${A}, actualOutputTokens=${L}`),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,L,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:L,totalTokens:G+L,cachedTokens:O>0?O: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 L=A.droppedMessages||0,$=A.compressedMessages||0;if(L>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 ${L} \u6761\u6D88\u606F${$>0?`\uFF0C\u538B\u7F29 ${$} \u6761`:""}\uFF0C\u8282\u7701\u7EA6 ${D.toLocaleString()} tokens`),this.emitEvent({type:"status",status:"compacting",message:`Context compacted: -${L} 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: ${S}`),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=Bs(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 Pw="ark.cn-beijing.volces.com";function Dw(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 Bl(a){return a.includes("doubao-seed")}function Gl(a){return !!a&&a.includes(Pw)}function Ow(a){let e=a?.getProvider?.();return e instanceof Vt?e:void 0}function Lw(a){let e=a?.getProvider?.();return e instanceof wn?e:void 0}function Nw(a){let e=a?.getProvider?.();return e instanceof Cn?e:void 0}function $w(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&&Gl(t)&&Bl(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 fo(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:Gl(i)&&Bl(t)?{type:"enabled"}:void 0},g=$t.createAdapter(n,h);o=g,l=Ow(g),l&&Gl(i)&&Bl(t)&&l.setDoubaoThinking({type:"enabled"});}else if(n==="anthropic"){let h={...e,defaultModel:t,lastSelectedModel:t},g=$t.createAdapter(n,h);o=g,c=Lw(g),c&&Dw(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 lo({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=$t.createAdapter(n,h);o=g,d=Nw(g);}else throw new Error(`Unsupported provider protocol: ${n}`);let p=$w({model:t,baseUrl:i,openaiProvider:l,anthropicProvider:c,doubaoProvider:u,geminiProvider:d});return {llmProvider:o,controls:p}}function dm(a){return new Yi({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??Up,toolOutputGuardrails:a.toolOutputGuardrails??Wp,compressionMode:a.compressionMode,workspacePath:a.workspacePath,permissionManager:a.permissionManager,disableSystemPrompt:a.disableSystemPrompt,enableFGTS:a.enableFGTS})}function pm(a){return new ho({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 yo(a){return new at(a)}W();async function Ul(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:S,platformServices:T,sessionManager:_,sessionEnabled:M,disableSystemPrompt:F,enableFGTS:x}=a,R=p??yo(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}=fo({provider:t,model:s.model,sessionId:e}),O=s.compatProfile??null,I=O?new qr(O):void 0,A=d??await As(n,T),L=g??{maxIterations:0,temperature:.7},$=dm({llmProvider:v,model:s.model,tools:A,memory:R,config:L,agentName:l,agentDescription:c,instructions:i,contextInjection:f,plannerMode:b,structuredOutput:y,providerName:s.providerName,contextWindow:O?.contextWindow,tailTokenBudget:O?.tailTokenBudget,maxInputTokensOverride:s.maxInputTokens,toolInputGuardrails:w,toolOutputGuardrails:C,compressionMode:S,workspacePath:n,permissionManager:u,disableSystemPrompt:F,enableFGTS:x});return {host:pm({runner:$,memory:R,sessionManager:_??new Qt,sessionEnabled:M??false,workDir:r,model:s.model,memoryPressure:I,compatProfile:O,systemPrompt:o??(typeof i=="string"?i:""),llmProvider:v}),controls:E,llmProvider:v,runner:$,memory:R}}var Rt=class{hostController;platformServices;constructor(e){this.platformServices=e.platformServices,this.hostController=e.hostController??new Wr;}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:S,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:O,runner:I,memory:A}=await Ul({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:S,toolOutputGuardrails:T,compressionMode:_,platformServices:this.platformServices,sessionManager:M,sessionEnabled:F,disableSystemPrompt:x,enableFGTS:R});return j?.({host:v,controls:E,llmProvider:O,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 mm(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 Ir=240,bo=2e3;function At(a,e){return a?a.length<=e?a:a.slice(0,e).trimEnd()+"...":""}var vo=class extends Error{code;constructor(e){super(e),this.code="missing_provider";}},Et=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,S=null,T=this.actionLog?.createRunId();if(this.actionLog){let F=At(s,Ir);this.actionLog.record({type:"run_start",sessionId:t,runId:T,actor:"user",summary:F?`User: ${F}`:"User: (empty prompt)",data:{prompt:At(s,bo),promptLength:s.length,attachments:n?.attachments?.map(x=>({type:x.type,name:x.name,path:x.path}))}});}i&&o&&l&&(S=l.resolveProvider(o.modelAlias),S&&(w=S.providerId,C=S.modelName,b?.(S),S.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 mm({modelAlias:o?.modelAlias,initialProviderId:w,initialModelName:C,routeConfig:o,resolvedRoute:S,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: ${At(x,Ir)}`,data:{reason:x}});},runAttempt:async x=>{let R=this.resolveProvider(x.providerId,x.modelName);if(!R.provider||!R.llmConfig)throw new vo("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:O=>{if(O.type==="tool_call_end"&&m.info("ORCHESTRATOR",`\u{1F525} onEvent received tool_call_end: name=${O.name} toolId=${O.toolId}`),this.actionLog){let I=this.buildActionLogEntry(O,t,T);I&&this.actionLog.record(I);}u?.emit(t,O,v),g?.(O,v);}}),contextUsed:v.contextUsed,providerId:R.provider.id}}});if(S&&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: ${At(x,Ir)}`,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?At(JSON.stringify(e.args),bo):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?At(e.output,bo):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:At(e.oldString,200),newPreview:At(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:At(e.output,bo),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: ${At(e.message,Ir)}`,data:{message:e.message}};case "error_classified":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Error ${e.code}: ${At(e.message,Ir)}`,data:{category:e.category,code:e.code,message:e.message,suggestion:e.suggestion,retryable:e.retryable}};default:return null}}};W();var Fw=[".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".tiff",".tif",".mp3",".mp4",".avi",".mov",".wmv",".flv",".wav",".ogg",".webm",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".app",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".db",".sqlite",".sqlite3",".ttf",".otf",".woff",".woff2",".eot",".jar",".war",".class",".pyc",".pyo",".o",".a",".lib",".node",".wasm",".asar"],gm={ignoredPatterns:["**/.git/**","**/.cdundo/**","**/.svn/**","**/.hg/**","**/.DS_Store","**/Thumbs.db","**/desktop.ini","**/*.log","**/*.tmp","**/*.temp","**/*.swp","**/*.swo","**/*~","**/node_modules/**","**/bower_components/**","**/.npm/**","**/.yarn/**","**/.pnpm-store/**","**/package-lock.json","**/yarn.lock","**/pnpm-lock.yaml","**/dist/**","**/build/**","**/out/**","**/output/**","**/.output/**","**/target/**","**/bin/**","**/obj/**","**/*.bundle.js","**/*.bundle.css","**/*.min.js","**/*.min.css","**/.next/**","**/.nuxt/**","**/.svelte-kit/**","**/.astro/**","**/.vercel/**","**/.netlify/**","**/.turbo/**","**/.cache/**","**/.parcel-cache/**","**/.webpack/**","**/.vite/**","**/coverage/**","**/.nyc_output/**","**/jest_cache/**","**/.jest/**","**/__pycache__/**","**/*.pyc","**/*.pyo","**/*.pyd","**/.venv/**","**/venv/**","**/env/**","**/.env/**","**/virtualenv/**","**/.Python","**/pip-wheel-metadata/**","**/*.egg-info/**","**/.eggs/**","**/site-packages/**","**/target/**","**/.gradle/**","**/gradle/**","**/.m2/**","**/*.class","**/*.jar","**/*.war","**/*.ear","**/target/**","**/*.rlib","**/Cargo.lock","**/vendor/**","**/go.sum","**/bin/**","**/obj/**","**/packages/**","**/.nuget/**","**/*.dll","**/*.exe","**/*.pdb","**/vendor/bundle/**","**/.bundle/**","**/Gemfile.lock","**/vendor/**","**/composer.lock","**/.idea/**","**/.vscode/**","**/*.sublime-*","**/.project","**/.classpath","**/.settings/**","**/*.iml","**/.env.local","**/.env.*.local","**/.env.development","**/.env.production","**/*.sqlite","**/*.sqlite3","**/*.db","**/npm-debug.log*","**/yarn-debug.log*","**/yarn-error.log*","**/.pnpm-debug.log*"],maxCheckpoints:50,checkpointTTL:864e5,enabled:true,largeFileThreshold:1048576,veryLargeFileThreshold:10485760,binaryExtensions:Fw};var wo=class{workspacePath;shadowDir;shadowGitDir;git;watcher=null;changeBuffer=[];isWatching=false;currentSessionId=null;currentMessageIndex=0;config;changeCallbacks=new Set;initialized=false;debounceMap=new Map;DEBOUNCE_MS=100;gitOperationLock=Promise.resolve();GIT_RETRY_ATTEMPTS=3;GIT_RETRY_DELAY_MS=500;constructor(e={}){this.config={...gm,...e},this.workspacePath="",this.shadowDir="",this.shadowGitDir="",this.git=hm();}async init(e){if(this.initialized&&this.workspacePath===e){m.debug("CHECKPOINT","Already initialized for: "+e);return}this.workspacePath=e,this.shadowDir=te.join(e,".cdundo"),this.shadowGitDir=te.join(this.shadowDir,".git"),m.debug("CHECKPOINT","Initializing for workspace: "+e),await ce.mkdir(this.shadowDir,{recursive:true}),await this.addToGitignore();let t=Me.existsSync(this.shadowGitDir);this.git=hm(this.shadowDir),t?m.debug("CHECKPOINT","Using existing shadow git repository"):(await this.git.init(),await this.git.addConfig("user.email","checkpoint@neox.local"),await this.git.addConfig("user.name","Neox Checkpoint"),m.debug("CHECKPOINT","Created new shadow git repository")),await this.syncWorkspaceToShadow(),await this.withGitLock(async()=>{if((await this.git.status()).files.length>0||!t){await this.git.add(".");try{await this.git.commit("Initial checkpoint - workspace sync"),m.debug("CHECKPOINT","Created initial checkpoint");}catch{m.debug("CHECKPOINT","No changes to commit for initial checkpoint");}}}),this.initialized=true,m.debug("CHECKPOINT","Initialization complete");}beforeCheckpointId=null;async startWatching(e,t=0){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized. Call init() first.");if(this.isWatching)return m.debug("CHECKPOINT","Already watching, updating session info"),m.debug("CHECKPOINT","Clearing changeBuffer (was: "+this.changeBuffer.length+" items)"),this.currentSessionId=e,this.currentMessageIndex=t,this.changeBuffer=[],this.beforeCheckpointId;m.debug("CHECKPOINT","Starting new watch, clearing changeBuffer (was: "+this.changeBuffer.length+" items)"),this.currentSessionId=e,this.currentMessageIndex=t,this.changeBuffer=[];try{await this.withGitLock(async()=>{await this.syncWorkspaceToShadow(),await this.git.add("."),(await this.git.status()).files.length>0&&await this.git.commit(`Before session ${e} - auto checkpoint`);let r=await this.git.log({maxCount:1});this.beforeCheckpointId=r.latest?.hash||null,m.debug("CHECKPOINT","Created before-checkpoint: "+this.beforeCheckpointId);});}catch(n){m.error("CHECKPOINT","Failed to create before-checkpoint",{error:n});try{let r=await this.git.log({maxCount:1});this.beforeCheckpointId=r.latest?.hash||null;}catch{this.beforeCheckpointId=null;}}m.debug("CHECKPOINT","Starting file watcher for session: "+e);let s=n=>!!(n.includes(".cdundo")||n.includes("/.cdundo/")||n.includes("node_modules")||n.includes("/node_modules/")||n.includes("/.git/")||n.endsWith("/.git")||n.includes("/dist/")||n.includes("/build/")||n.includes("/.next/")||n.includes(".DS_Store")||n.includes(".swp")||n.includes(".swo")||n.endsWith("package-lock.json")||n.endsWith("yarn.lock")||n.endsWith("pnpm-lock.yaml"));return this.watcher=fm.watch(this.workspacePath,{ignored:s,persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},followSymlinks:false}),this.watcher.on("add",n=>this.handleChange("create",n)).on("change",n=>this.handleChange("modify",n)).on("unlink",n=>this.handleChange("delete",n)).on("addDir",n=>this.handleChange("mkdir",n)).on("unlinkDir",n=>this.handleChange("rmdir",n)).on("error",n=>m.error("CHECKPOINT","Watcher error",{error:n})),this.isWatching=true,m.debug("CHECKPOINT","File watcher started"),this.beforeCheckpointId}getBeforeCheckpointId(){return this.beforeCheckpointId}async stopWatching(){this.watcher&&(await this.watcher.close(),this.watcher=null),this.isWatching=false,this.currentSessionId=null;for(let e of this.debounceMap.values())clearTimeout(e);this.debounceMap.clear(),this.changeBuffer=[],m.debug("CHECKPOINT","File watcher stopped");}handleChange(e,t){if(!this.isWatching)return;let s=te.relative(this.workspacePath,t);if(this.shouldIgnorePath(s))return;let n=`${e}:${s}`,r=this.debounceMap.get(n);r&&clearTimeout(r),this.debounceMap.set(n,setTimeout(()=>{this.recordChange(e,s,t),this.debounceMap.delete(n);},this.DEBOUNCE_MS));}isBinaryFile(e){let t=te.extname(e).toLowerCase();return this.config.binaryExtensions.includes(t)}async detectBinaryContent(e){try{let t=await ce.open(e,"r"),s=Buffer.alloc(8192),{bytesRead:n}=await t.read(s,0,8192,0);await t.close();for(let r=0;r<n;r++)if(s[r]===0)return !0;return !1}catch{return false}}async recordChange(e,t,s){let n={type:e,path:t,timestamp:Date.now()},r=this.isBinaryFile(t);n.isBinary=r;let i=0,o=false,l=false;if(e==="create"||e==="modify")try{let d=await ce.stat(s);if(d.isFile()&&(i=d.size,n.size=i,o=i>this.config.veryLargeFileThreshold,l=i>this.config.largeFileThreshold,n.isLargeFile=l,!r&&!l)){let p=await this.detectBinaryContent(s);n.isBinary=p;}}catch{}if((e==="delete"||e==="modify")&&!n.isBinary&&!l){let d=te.join(this.shadowDir,t);try{let p=await ce.stat(d);p.isFile()&&p.size<this.config.largeFileThreshold&&(n.previousContent=await ce.readFile(d,"utf-8"));}catch{}}if((e==="create"||e==="modify")&&!n.isBinary&&!l)try{n.newContent=await ce.readFile(s,"utf-8");}catch{}this.changeBuffer.push(n),o?m.debug("CHECKPOINT",`Skipping very large file (${(i/1024/1024).toFixed(1)}MB): ${t}`):await this.syncFileToShadow(t,e,s);for(let d of this.changeCallbacks)try{d(n);}catch(p){m.error("CHECKPOINT","Callback error",{error:p});}let c=i?` (${this.formatFileSize(i)})`:"",u=n.isBinary?" [binary]":"";m.debug("CHECKPOINT",`Recorded ${e}: ${t}${c}${u}`);}formatFileSize(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}async syncFileToShadow(e,t,s){let n=te.join(this.shadowDir,e),r=te.dirname(n);try{switch(t){case "create":case "modify":await ce.mkdir(r,{recursive:!0}),await ce.copyFile(s,n);break;case "delete":await ce.unlink(n).catch(()=>{});break;case "mkdir":await ce.mkdir(n,{recursive:!0});break;case "rmdir":await ce.rm(n,{recursive:!0,force:!0}).catch(()=>{});break}}catch(i){m.error("CHECKPOINT",`Failed to sync ${e}`,{error:i});}}async syncWorkspaceToShadow(){m.debug("CHECKPOINT","Syncing workspace to shadow...");let e=0,t=0,s=0,n=async(r,i)=>{let o;try{o=await ce.readdir(r,{withFileTypes:!0});}catch{return}for(let l of o){let c=te.join(r,l.name),u=te.join(i,l.name),d=te.relative(this.workspacePath,c);if(!this.shouldIgnore(d)){if(l.isDirectory())await ce.mkdir(u,{recursive:true}),await n(c,u);else if(l.isFile())try{let p=await ce.stat(c);if(p.size>this.config.veryLargeFileThreshold){t++,m.debug("CHECKPOINT",`Skipping very large file: ${d} (${this.formatFileSize(p.size)})`);continue}await ce.mkdir(te.dirname(u),{recursive:!0}),await ce.copyFile(c,u),e++,s+=p.size;}catch{m.warn("CHECKPOINT",`Failed to sync file: ${d}`);}}}};await n(this.workspacePath,this.shadowDir),m.debug("CHECKPOINT",`Workspace sync complete: ${e} files (${this.formatFileSize(s)}), ${t} large files skipped`);}shouldIgnorePath(e){return !!(e.startsWith(".cdundo")||e.includes("/.cdundo/")||e.includes("node_modules/")||e.startsWith("node_modules")||e.startsWith(".git")||e.includes("/.git/")||e.startsWith("dist/")||e.includes("/dist/")||e.startsWith("build/")||e.includes("/build/")||e.startsWith(".next/")||e.includes("/.next/")||e.includes(".DS_Store")||e.endsWith(".swp")||e.endsWith(".swo")||e.endsWith("package-lock.json")||e.endsWith("yarn.lock")||e.endsWith("pnpm-lock.yaml"))}shouldIgnore(e){if(this.shouldIgnorePath(e))return true;for(let t of this.config.ignoredPatterns)if(this.matchPattern(e,t))return true;return false}matchPattern(e,t){let s=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`).test(e)}async createCheckpoint(e){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");return m.debug("CHECKPOINT","Creating checkpoint: "+e),await this.withGitLock(async()=>{if(await this.git.add("."),(await this.git.status()).files.length===0&&this.changeBuffer.length===0)return m.debug("CHECKPOINT","No changes to checkpoint"),{id:(await this.git.log({maxCount:1})).latest?.hash||"no-changes",label:e,timestamp:Date.now(),sessionId:this.currentSessionId||"",messageIndex:this.currentMessageIndex,changes:[],stats:{created:0,modified:0,deleted:0,directories:0,total:0}};let s=this.calculateStats(),n=this.formatCommitMessage(e,s),r=await this.git.commit(n),i={id:r.commit,label:e,timestamp:Date.now(),sessionId:this.currentSessionId||"",messageIndex:this.currentMessageIndex,changes:[...this.changeBuffer],stats:s};return this.changeBuffer=[],this.currentMessageIndex++,m.debug("CHECKPOINT",`Checkpoint created: ${r.commit} (${s.total} changes)`),await this.cleanupOldCheckpoints(),i})}lastRollbackFromId=null;getLastRollbackFromId(){return this.lastRollbackFromId}async rollbackTo(e){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");m.debug("CHECKPOINT","Rolling back to checkpoint: "+e);let t=[],s=[],n;try{return await this.withGitLock(async()=>{await this.git.add(".");let r=await this.git.status();if(m.debug("CHECKPOINT","Current git status before rollback: "+r.files.length+" files"),r.files.length>0)try{await this.git.commit("Changes before rollback (for reapply)"),m.debug("CHECKPOINT","Created commit for rollback comparison");}catch{m.debug("CHECKPOINT","No changes to commit (might be already committed)");}n=(await this.git.log({maxCount:1})).latest?.hash,this.lastRollbackFromId=n||null,m.debug("CHECKPOINT","Saved reapply checkpoint: "+n);let o=await this.git.diff([e,"HEAD","--name-status"]),l=o.trim().split(`
|
|
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 Pw="ark.cn-beijing.volces.com";function Dw(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 Bl(a){return a.includes("doubao-seed")}function Gl(a){return !!a&&a.includes(Pw)}function Ow(a){let e=a?.getProvider?.();return e instanceof Vt?e:void 0}function Lw(a){let e=a?.getProvider?.();return e instanceof wn?e:void 0}function Nw(a){let e=a?.getProvider?.();return e instanceof Cn?e:void 0}function $w(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&&Gl(t)&&Bl(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 fo(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:Gl(i)&&Bl(t)?{type:"enabled"}:void 0},g=$t.createAdapter(n,h);o=g,l=Ow(g),l&&Gl(i)&&Bl(t)&&l.setDoubaoThinking({type:"enabled"});}else if(n==="anthropic"){let h={...e,defaultModel:t,lastSelectedModel:t},g=$t.createAdapter(n,h);o=g,c=Lw(g),c&&Dw(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 lo({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=$t.createAdapter(n,h);o=g,d=Nw(g);}else throw new Error(`Unsupported provider protocol: ${n}`);let p=$w({model:t,baseUrl:i,openaiProvider:l,anthropicProvider:c,doubaoProvider:u,geminiProvider:d});return {llmProvider:o,controls:p}}function dm(a){return new Yi({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??Up,toolOutputGuardrails:a.toolOutputGuardrails??Wp,compressionMode:a.compressionMode,workspacePath:a.workspacePath,permissionManager:a.permissionManager,disableSystemPrompt:a.disableSystemPrompt,enableFGTS:a.enableFGTS})}function pm(a){return new ho({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 yo(a){return new at(a)}W();async function Ul(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:S,platformServices:T,sessionManager:_,sessionEnabled:M,disableSystemPrompt:F,enableFGTS:x}=a,R=p??yo(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}=fo({provider:t,model:s.model,sessionId:e}),P=s.compatProfile??null,I=P?new qr(P):void 0,A=d??await As(n,T),L=g??{maxIterations:0,temperature:.7},$=dm({llmProvider:v,model:s.model,tools:A,memory:R,config:L,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:S,workspacePath:n,permissionManager:u,disableSystemPrompt:F,enableFGTS:x});return {host:pm({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 Rt=class{hostController;platformServices;constructor(e){this.platformServices=e.platformServices,this.hostController=e.hostController??new Wr;}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:S,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 Ul({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:S,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 mm(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 Ir=240,bo=2e3;function At(a,e){return a?a.length<=e?a:a.slice(0,e).trimEnd()+"...":""}var vo=class extends Error{code;constructor(e){super(e),this.code="missing_provider";}},Et=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,S=null,T=this.actionLog?.createRunId();if(this.actionLog){let F=At(s,Ir);this.actionLog.record({type:"run_start",sessionId:t,runId:T,actor:"user",summary:F?`User: ${F}`:"User: (empty prompt)",data:{prompt:At(s,bo),promptLength:s.length,attachments:n?.attachments?.map(x=>({type:x.type,name:x.name,path:x.path}))}});}i&&o&&l&&(S=l.resolveProvider(o.modelAlias),S&&(w=S.providerId,C=S.modelName,b?.(S),S.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 mm({modelAlias:o?.modelAlias,initialProviderId:w,initialModelName:C,routeConfig:o,resolvedRoute:S,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: ${At(x,Ir)}`,data:{reason:x}});},runAttempt:async x=>{let R=this.resolveProvider(x.providerId,x.modelName);if(!R.provider||!R.llmConfig)throw new vo("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(S&&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: ${At(x,Ir)}`,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?At(JSON.stringify(e.args),bo):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?At(e.output,bo):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:At(e.oldString,200),newPreview:At(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:At(e.output,bo),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: ${At(e.message,Ir)}`,data:{message:e.message}};case "error_classified":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Error ${e.code}: ${At(e.message,Ir)}`,data:{category:e.category,code:e.code,message:e.message,suggestion:e.suggestion,retryable:e.retryable}};default:return null}}};W();var Fw=[".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".tiff",".tif",".mp3",".mp4",".avi",".mov",".wmv",".flv",".wav",".ogg",".webm",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".app",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".db",".sqlite",".sqlite3",".ttf",".otf",".woff",".woff2",".eot",".jar",".war",".class",".pyc",".pyo",".o",".a",".lib",".node",".wasm",".asar"],gm={ignoredPatterns:["**/.git/**","**/.cdundo/**","**/.svn/**","**/.hg/**","**/.DS_Store","**/Thumbs.db","**/desktop.ini","**/*.log","**/*.tmp","**/*.temp","**/*.swp","**/*.swo","**/*~","**/node_modules/**","**/bower_components/**","**/.npm/**","**/.yarn/**","**/.pnpm-store/**","**/package-lock.json","**/yarn.lock","**/pnpm-lock.yaml","**/dist/**","**/build/**","**/out/**","**/output/**","**/.output/**","**/target/**","**/bin/**","**/obj/**","**/*.bundle.js","**/*.bundle.css","**/*.min.js","**/*.min.css","**/.next/**","**/.nuxt/**","**/.svelte-kit/**","**/.astro/**","**/.vercel/**","**/.netlify/**","**/.turbo/**","**/.cache/**","**/.parcel-cache/**","**/.webpack/**","**/.vite/**","**/coverage/**","**/.nyc_output/**","**/jest_cache/**","**/.jest/**","**/__pycache__/**","**/*.pyc","**/*.pyo","**/*.pyd","**/.venv/**","**/venv/**","**/env/**","**/.env/**","**/virtualenv/**","**/.Python","**/pip-wheel-metadata/**","**/*.egg-info/**","**/.eggs/**","**/site-packages/**","**/target/**","**/.gradle/**","**/gradle/**","**/.m2/**","**/*.class","**/*.jar","**/*.war","**/*.ear","**/target/**","**/*.rlib","**/Cargo.lock","**/vendor/**","**/go.sum","**/bin/**","**/obj/**","**/packages/**","**/.nuget/**","**/*.dll","**/*.exe","**/*.pdb","**/vendor/bundle/**","**/.bundle/**","**/Gemfile.lock","**/vendor/**","**/composer.lock","**/.idea/**","**/.vscode/**","**/*.sublime-*","**/.project","**/.classpath","**/.settings/**","**/*.iml","**/.env.local","**/.env.*.local","**/.env.development","**/.env.production","**/*.sqlite","**/*.sqlite3","**/*.db","**/npm-debug.log*","**/yarn-debug.log*","**/yarn-error.log*","**/.pnpm-debug.log*"],maxCheckpoints:50,checkpointTTL:864e5,enabled:true,largeFileThreshold:1048576,veryLargeFileThreshold:10485760,binaryExtensions:Fw};var wo=class{workspacePath;shadowDir;shadowGitDir;git;watcher=null;changeBuffer=[];isWatching=false;currentSessionId=null;currentMessageIndex=0;config;changeCallbacks=new Set;initialized=false;debounceMap=new Map;DEBOUNCE_MS=100;gitOperationLock=Promise.resolve();GIT_RETRY_ATTEMPTS=3;GIT_RETRY_DELAY_MS=500;constructor(e={}){this.config={...gm,...e},this.workspacePath="",this.shadowDir="",this.shadowGitDir="",this.git=hm();}async init(e){if(this.initialized&&this.workspacePath===e){m.debug("CHECKPOINT","Already initialized for: "+e);return}this.workspacePath=e,this.shadowDir=te.join(e,".cdundo"),this.shadowGitDir=te.join(this.shadowDir,".git"),m.debug("CHECKPOINT","Initializing for workspace: "+e),await ce.mkdir(this.shadowDir,{recursive:true}),await this.addToGitignore();let t=Me.existsSync(this.shadowGitDir);this.git=hm(this.shadowDir),t?m.debug("CHECKPOINT","Using existing shadow git repository"):(await this.git.init(),await this.git.addConfig("user.email","checkpoint@neox.local"),await this.git.addConfig("user.name","Neox Checkpoint"),m.debug("CHECKPOINT","Created new shadow git repository")),await this.syncWorkspaceToShadow(),await this.withGitLock(async()=>{if((await this.git.status()).files.length>0||!t){await this.git.add(".");try{await this.git.commit("Initial checkpoint - workspace sync"),m.debug("CHECKPOINT","Created initial checkpoint");}catch{m.debug("CHECKPOINT","No changes to commit for initial checkpoint");}}}),this.initialized=true,m.debug("CHECKPOINT","Initialization complete");}beforeCheckpointId=null;async startWatching(e,t=0){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized. Call init() first.");if(this.isWatching)return m.debug("CHECKPOINT","Already watching, updating session info"),m.debug("CHECKPOINT","Clearing changeBuffer (was: "+this.changeBuffer.length+" items)"),this.currentSessionId=e,this.currentMessageIndex=t,this.changeBuffer=[],this.beforeCheckpointId;m.debug("CHECKPOINT","Starting new watch, clearing changeBuffer (was: "+this.changeBuffer.length+" items)"),this.currentSessionId=e,this.currentMessageIndex=t,this.changeBuffer=[];try{await this.withGitLock(async()=>{await this.syncWorkspaceToShadow(),await this.git.add("."),(await this.git.status()).files.length>0&&await this.git.commit(`Before session ${e} - auto checkpoint`);let r=await this.git.log({maxCount:1});this.beforeCheckpointId=r.latest?.hash||null,m.debug("CHECKPOINT","Created before-checkpoint: "+this.beforeCheckpointId);});}catch(n){m.error("CHECKPOINT","Failed to create before-checkpoint",{error:n});try{let r=await this.git.log({maxCount:1});this.beforeCheckpointId=r.latest?.hash||null;}catch{this.beforeCheckpointId=null;}}m.debug("CHECKPOINT","Starting file watcher for session: "+e);let s=n=>!!(n.includes(".cdundo")||n.includes("/.cdundo/")||n.includes("node_modules")||n.includes("/node_modules/")||n.includes("/.git/")||n.endsWith("/.git")||n.includes("/dist/")||n.includes("/build/")||n.includes("/.next/")||n.includes(".DS_Store")||n.includes(".swp")||n.includes(".swo")||n.endsWith("package-lock.json")||n.endsWith("yarn.lock")||n.endsWith("pnpm-lock.yaml"));return this.watcher=fm.watch(this.workspacePath,{ignored:s,persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},followSymlinks:false}),this.watcher.on("add",n=>this.handleChange("create",n)).on("change",n=>this.handleChange("modify",n)).on("unlink",n=>this.handleChange("delete",n)).on("addDir",n=>this.handleChange("mkdir",n)).on("unlinkDir",n=>this.handleChange("rmdir",n)).on("error",n=>m.error("CHECKPOINT","Watcher error",{error:n})),this.isWatching=true,m.debug("CHECKPOINT","File watcher started"),this.beforeCheckpointId}getBeforeCheckpointId(){return this.beforeCheckpointId}async stopWatching(){this.watcher&&(await this.watcher.close(),this.watcher=null),this.isWatching=false,this.currentSessionId=null;for(let e of this.debounceMap.values())clearTimeout(e);this.debounceMap.clear(),this.changeBuffer=[],m.debug("CHECKPOINT","File watcher stopped");}handleChange(e,t){if(!this.isWatching)return;let s=te.relative(this.workspacePath,t);if(this.shouldIgnorePath(s))return;let n=`${e}:${s}`,r=this.debounceMap.get(n);r&&clearTimeout(r),this.debounceMap.set(n,setTimeout(()=>{this.recordChange(e,s,t),this.debounceMap.delete(n);},this.DEBOUNCE_MS));}isBinaryFile(e){let t=te.extname(e).toLowerCase();return this.config.binaryExtensions.includes(t)}async detectBinaryContent(e){try{let t=await ce.open(e,"r"),s=Buffer.alloc(8192),{bytesRead:n}=await t.read(s,0,8192,0);await t.close();for(let r=0;r<n;r++)if(s[r]===0)return !0;return !1}catch{return false}}async recordChange(e,t,s){let n={type:e,path:t,timestamp:Date.now()},r=this.isBinaryFile(t);n.isBinary=r;let i=0,o=false,l=false;if(e==="create"||e==="modify")try{let d=await ce.stat(s);if(d.isFile()&&(i=d.size,n.size=i,o=i>this.config.veryLargeFileThreshold,l=i>this.config.largeFileThreshold,n.isLargeFile=l,!r&&!l)){let p=await this.detectBinaryContent(s);n.isBinary=p;}}catch{}if((e==="delete"||e==="modify")&&!n.isBinary&&!l){let d=te.join(this.shadowDir,t);try{let p=await ce.stat(d);p.isFile()&&p.size<this.config.largeFileThreshold&&(n.previousContent=await ce.readFile(d,"utf-8"));}catch{}}if((e==="create"||e==="modify")&&!n.isBinary&&!l)try{n.newContent=await ce.readFile(s,"utf-8");}catch{}this.changeBuffer.push(n),o?m.debug("CHECKPOINT",`Skipping very large file (${(i/1024/1024).toFixed(1)}MB): ${t}`):await this.syncFileToShadow(t,e,s);for(let d of this.changeCallbacks)try{d(n);}catch(p){m.error("CHECKPOINT","Callback error",{error:p});}let c=i?` (${this.formatFileSize(i)})`:"",u=n.isBinary?" [binary]":"";m.debug("CHECKPOINT",`Recorded ${e}: ${t}${c}${u}`);}formatFileSize(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}async syncFileToShadow(e,t,s){let n=te.join(this.shadowDir,e),r=te.dirname(n);try{switch(t){case "create":case "modify":await ce.mkdir(r,{recursive:!0}),await ce.copyFile(s,n);break;case "delete":await ce.unlink(n).catch(()=>{});break;case "mkdir":await ce.mkdir(n,{recursive:!0});break;case "rmdir":await ce.rm(n,{recursive:!0,force:!0}).catch(()=>{});break}}catch(i){m.error("CHECKPOINT",`Failed to sync ${e}`,{error:i});}}async syncWorkspaceToShadow(){m.debug("CHECKPOINT","Syncing workspace to shadow...");let e=0,t=0,s=0,n=async(r,i)=>{let o;try{o=await ce.readdir(r,{withFileTypes:!0});}catch{return}for(let l of o){let c=te.join(r,l.name),u=te.join(i,l.name),d=te.relative(this.workspacePath,c);if(!this.shouldIgnore(d)){if(l.isDirectory())await ce.mkdir(u,{recursive:true}),await n(c,u);else if(l.isFile())try{let p=await ce.stat(c);if(p.size>this.config.veryLargeFileThreshold){t++,m.debug("CHECKPOINT",`Skipping very large file: ${d} (${this.formatFileSize(p.size)})`);continue}await ce.mkdir(te.dirname(u),{recursive:!0}),await ce.copyFile(c,u),e++,s+=p.size;}catch{m.warn("CHECKPOINT",`Failed to sync file: ${d}`);}}}};await n(this.workspacePath,this.shadowDir),m.debug("CHECKPOINT",`Workspace sync complete: ${e} files (${this.formatFileSize(s)}), ${t} large files skipped`);}shouldIgnorePath(e){return !!(e.startsWith(".cdundo")||e.includes("/.cdundo/")||e.includes("node_modules/")||e.startsWith("node_modules")||e.startsWith(".git")||e.includes("/.git/")||e.startsWith("dist/")||e.includes("/dist/")||e.startsWith("build/")||e.includes("/build/")||e.startsWith(".next/")||e.includes("/.next/")||e.includes(".DS_Store")||e.endsWith(".swp")||e.endsWith(".swo")||e.endsWith("package-lock.json")||e.endsWith("yarn.lock")||e.endsWith("pnpm-lock.yaml"))}shouldIgnore(e){if(this.shouldIgnorePath(e))return true;for(let t of this.config.ignoredPatterns)if(this.matchPattern(e,t))return true;return false}matchPattern(e,t){let s=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`).test(e)}async createCheckpoint(e){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");return m.debug("CHECKPOINT","Creating checkpoint: "+e),await this.withGitLock(async()=>{if(await this.git.add("."),(await this.git.status()).files.length===0&&this.changeBuffer.length===0)return m.debug("CHECKPOINT","No changes to checkpoint"),{id:(await this.git.log({maxCount:1})).latest?.hash||"no-changes",label:e,timestamp:Date.now(),sessionId:this.currentSessionId||"",messageIndex:this.currentMessageIndex,changes:[],stats:{created:0,modified:0,deleted:0,directories:0,total:0}};let s=this.calculateStats(),n=this.formatCommitMessage(e,s),r=await this.git.commit(n),i={id:r.commit,label:e,timestamp:Date.now(),sessionId:this.currentSessionId||"",messageIndex:this.currentMessageIndex,changes:[...this.changeBuffer],stats:s};return this.changeBuffer=[],this.currentMessageIndex++,m.debug("CHECKPOINT",`Checkpoint created: ${r.commit} (${s.total} changes)`),await this.cleanupOldCheckpoints(),i})}lastRollbackFromId=null;getLastRollbackFromId(){return this.lastRollbackFromId}async rollbackTo(e){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");m.debug("CHECKPOINT","Rolling back to checkpoint: "+e);let t=[],s=[],n;try{return await this.withGitLock(async()=>{await this.git.add(".");let r=await this.git.status();if(m.debug("CHECKPOINT","Current git status before rollback: "+r.files.length+" files"),r.files.length>0)try{await this.git.commit("Changes before rollback (for reapply)"),m.debug("CHECKPOINT","Created commit for rollback comparison");}catch{m.debug("CHECKPOINT","No changes to commit (might be already committed)");}n=(await this.git.log({maxCount:1})).latest?.hash,this.lastRollbackFromId=n||null,m.debug("CHECKPOINT","Saved reapply checkpoint: "+n);let o=await this.git.diff([e,"HEAD","--name-status"]),l=o.trim().split(`
|
|
1864
1864
|
`).filter(c=>c.trim());m.debug("CHECKPOINT","Diff output: "+o),m.debug("CHECKPOINT","Files to rollback: "+l.length);for(let c of l){let[u,...d]=c.split(" "),p=d.join(" ");if(!p)continue;let h=te.join(this.workspacePath,p),g=te.join(this.shadowDir,p);m.debug("CHECKPOINT",`Processing: status=${u}, file=${p}`);try{switch(u){case "A":m.debug("CHECKPOINT",`Deleting added file: ${h}`),await ce.unlink(h).catch(f=>{m.debug("CHECKPOINT",`Failed to delete workspace file: ${f}`);}),await ce.unlink(g).catch(()=>{}),t.push(`deleted: ${p}`);break;case "M":m.debug("CHECKPOINT","Restoring modified file: "+p),await this.git.checkout([e,"--",p]),await ce.mkdir(te.dirname(h),{recursive:!0}),await ce.copyFile(g,h),t.push(`restored: ${p}`);break;case "D":m.debug("CHECKPOINT","Recovering deleted file: "+p),await this.git.checkout([e,"--",p]),await ce.mkdir(te.dirname(h),{recursive:!0}),await ce.copyFile(g,h),t.push(`recovered: ${p}`);break;default:m.debug("CHECKPOINT",`Unhandled status ${u} for ${p}`);}}catch(f){m.error("CHECKPOINT",`Error processing ${p}`,{error:f}),s.push(`${p}: ${f}`);}}await this.git.reset(["--hard",e]),this.changeBuffer=[],m.debug("CHECKPOINT",`Rollback complete: ${t.length} restored, ${s.length} errors`);}),{success:s.length===0,restored:t,errors:s,reapplyCheckpointId:n}}catch(r){return m.error("CHECKPOINT","Rollback failed",{error:r}),{success:false,restored:t,errors:[String(r)],reapplyCheckpointId:n}}}async rollbackSingleFile(e){if(!this.initialized)return {success:false,error:"ShadowGitCheckpoint not initialized"};m.debug("CHECKPOINT","Rolling back single file: "+e);let t=this.beforeCheckpointId;if(!t)return {success:false,error:"No before checkpoint available. Make sure startWatching() was called before this message."};let s=te.join(this.workspacePath,e),n=te.join(this.shadowDir,e);try{return await this.withGitLock(async()=>{let r=await this.git.diff([t,"HEAD","--name-status","--",e]);if(m.debug("CHECKPOINT","File diff status: "+r.trim()),!r.trim())return m.debug("CHECKPOINT","File has no changes since before checkpoint"),{success:!0};let[i]=r.trim().split(" ");switch(i){case "A":m.debug("CHECKPOINT","File was added after checkpoint, deleting: "+e);try{return await ce.unlink(s),await ce.unlink(n).catch(()=>{}),{success:!0}}catch(o){return {success:!1,error:`Failed to delete file: ${o}`}}case "M":case "D":m.debug("CHECKPOINT","Restoring file from before checkpoint: "+e);try{return await this.git.checkout([t,"--",e]),await ce.mkdir(te.dirname(s),{recursive:!0}),await ce.copyFile(n,s),m.debug("CHECKPOINT","Successfully rolled back file: "+e),{success:!0}}catch(o){return {success:!1,error:`Failed to restore file: ${o}`}}default:return m.debug("CHECKPOINT","Unhandled status: "+i),{success:!1,error:`Unhandled file status: ${i}`}}})}catch(r){return m.error("CHECKPOINT","Failed to rollback single file",{error:r}),{success:false,error:String(r)}}}async reapplySingleFile(e){if(!this.initialized)return {success:false,error:"ShadowGitCheckpoint not initialized"};m.debug("CHECKPOINT","Reapplying single file: "+e);try{return await this.withGitLock(async()=>{let t=te.join(this.workspacePath,e),s=te.join(this.shadowDir,e);try{return await this.git.checkout(["HEAD","--",e]),await ce.mkdir(te.dirname(t),{recursive:!0}),await ce.copyFile(s,t),m.debug("CHECKPOINT","Successfully reapplied file: "+e),{success:!0}}catch(n){return {success:!1,error:`File not found in HEAD: ${n}`}}})}catch(t){return m.error("CHECKPOINT","Failed to reapply single file",{error:t}),{success:false,error:String(t)}}}async getCheckpoints(e=50,t){if(!this.initialized)return [];try{let s=t?e*3:e,r=(await this.git.log({maxCount:s})).all.map(i=>{let o=this.parseCommitMessage(i.message);return {id:i.hash,label:o.label,timestamp:new Date(i.date).getTime(),sessionId:o.sessionId,messageIndex:o.messageIndex,stats:o.stats}});return t&&(r=r.filter(i=>i.sessionId===t)),r.slice(0,e)}catch(s){return m.error("CHECKPOINT","Failed to get checkpoints",{error:s}),[]}}async getDiff(e,t="HEAD"){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");await this.git.diff([e,t,"--stat","--numstat"]);let n=await this.git.diffSummary([e,t]),r=n.files.map(i=>{let o="insertions"in i&&"deletions"in i;return {path:i.file,status:this.getFileStatus(i),additions:o?i.insertions:0,deletions:o?i.deletions:0,lines:[]}});return {checkpointId:e,files:r,stats:{filesChanged:n.changed,additions:n.insertions,deletions:n.deletions}}}getChangeBuffer(){return this.isWatching?[...this.changeBuffer]:(m.debug("CHECKPOINT","getChangeBuffer called but not watching, returning empty array"),[])}getCurrentStats(){if(!this.isWatching)return m.debug("CHECKPOINT","getCurrentStats called but not watching, returning empty stats"),{created:0,modified:0,deleted:0,directories:0,total:0};let e=this.calculateStats();return m.debug("CHECKPOINT","getCurrentStats called, changeBuffer length: "+this.changeBuffer.length),this.changeBuffer.length>0&&m.debug("CHECKPOINT","changeBuffer contents: "+this.changeBuffer.map(t=>`${t.type}: ${t.path}`).join(", ")),e}onFileChange(e){return this.changeCallbacks.add(e),()=>this.changeCallbacks.delete(e)}isInitialized(){return this.initialized}isActive(){return this.isWatching}getShadowDir(){return this.shadowDir}calculateStats(){let e={created:0,modified:0,deleted:0,directories:0,total:0};for(let t of this.changeBuffer)switch(t.type){case "create":e.created++;break;case "modify":e.modified++;break;case "delete":e.deleted++;break;case "mkdir":case "rmdir":e.directories++;break}return e.total=e.created+e.modified+e.deleted+e.directories,e}formatCommitMessage(e,t){let s=this.currentSessionId?`
|
|
1865
1865
|
|
|
1866
1866
|
Session: ${this.currentSessionId}
|
|
@@ -2018,7 +2018,7 @@ ${i.output}`}let o=i.toolCalls.map(c=>` ${c.name} (${c.durationMs}ms)`).join(`
|
|
|
2018
2018
|
${o}
|
|
2019
2019
|
${i.output}`}}}var kn=class{config;hostService;orchestrator;abortController=null;toolTreeEngine=null;constructor(e){this.config=e,this.hostService=new Rt({platformServices:e.services}),this.orchestrator=new Et({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=Kl({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=Tm(this.config.tools);c.push(b),m.info("SINGLE_AGENT","PTC tool injected");}this.toolTreeEngine=new To(c);let u=this.toolTreeEngine.liveTools,p=[this.config.systemPrompt??"Single agent mode",Vl,oC];if(this.config.enablePTC&&p.push(aC),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 km(this.config.workDir);b&&p.push(b);}catch(b){m.warn("SINGLE_AGENT","Project memory load failed",{error:b.message});}let h=p.join(`
|
|
2020
2020
|
|
|
2021
|
-
`),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"}},oC=`
|
|
2021
|
+
`),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"}},oC=`
|
|
2022
2022
|
## \u5DE5\u5177\u6811
|
|
2023
2023
|
\u4F60\u7684\u5DE5\u5177\u6309\u7C7B\u522B\u7EC4\u7EC7\u3002\u9ED8\u8BA4\u53EA\u6709\u5E38\u9A7B\u5DE5\u5177\u53EF\u7528\u3002
|
|
2024
2024
|
\u9700\u8981\u5176\u4ED6\u5DE5\u5177\u65F6\uFF1A
|
|
@@ -3368,7 +3368,7 @@ ${R.lines.join(`
|
|
|
3368
3368
|
`)}`),x.lines.length>0&&I.push(`${x.title}
|
|
3369
3369
|
${x.lines.join(`
|
|
3370
3370
|
`)}`),I.join(`
|
|
3371
|
-
`)},v=["activity","session","lesson","standard","progress","pinned"],E=new Map([["activity",x],["session",R],...F.map(I=>[I.key,I])]),
|
|
3371
|
+
`)},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 L of v){let $=E.get(L);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??qc,n=e?.maxSessionItems??zc,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 S=this.tokenizeQuery(c);d={tokens:S,graphMatches:await this.getGraphRunMatches(S)};}let p=[];if(i){let S=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=>`- [${Br(M.ts)}] ${M.summary}`);p=[{key:"pinned",title:u.pinned,lines:T(S.pinned)},{key:"progress",title:u.progress,lines:T(S.progress)},{key:"standard",title:u.standard,lines:T(S.standard)},{key:"lesson",title:u.lesson,lines:T(S.lesson)}];}let h=o?await this.getLastMeaningfulSessionSummary():null,g=h?[`- [${Br(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=>`- [${Br(M.ts)}] ${M.summary}`);}if(p.every(S=>S.lines.length===0)&&f.length===0&&g.length===0)return null;let b=()=>{let S=[],T=p.filter(_=>_.lines.length>0).map(_=>`${_.title}
|
|
3372
3372
|
${_.lines.join(`
|
|
3373
3373
|
`)}`);return T.length>0&&S.push(`${u.memoryHeader}
|
|
3374
3374
|
${T.join(`
|
|
@@ -3409,7 +3409,7 @@ ${e.map(s=>{let n=Br(s.ts),r=s.files&&s.files.length>0?` files=${s.files.join(",
|
|
|
3409
3409
|
[
|
|
3410
3410
|
{"category":"progress","summary":"\u5B8C\u6210\u4E86 X\uFF0C\u4E0B\u4E00\u6B65 Y","files":["src/app.ts"],"confidence":0.7},
|
|
3411
3411
|
{"category":"lesson","summary":"\u907F\u514D\u91CD\u590D\u6267\u884C Z\uFF0C\u5BB9\u6613\u8D85\u65F6","confidence":0.5}
|
|
3412
|
-
]`}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>=TS)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}`,xS),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 Xo=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(){}},Qo=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 Xo:this.provider=new Xo,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 Hc=te.join(Dn.homedir(),".neox"),Ur=te.join(Hc,"server.pid");function $S(a){Me.existsSync(Hc)||Me.mkdirSync(Hc,{recursive:true}),Me.writeFileSync(Ur,JSON.stringify(a,null,2));}function lg(){try{Me.existsSync(Ur)&&Me.unlinkSync(Ur);}catch{}}function cg(){try{return Me.existsSync(Ur)?JSON.parse(Me.readFileSync(Ur,"utf-8")):null}catch{return null}}function FS(){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 jS(a,e){let t=Le(),s=Ts(),n=new rt(t),r=t.agentApprovalMode||t.approvalMode||"auto",i=new ls({defaultPermission:"allow"}),o=(v,E)=>{let O=n.getProvider(v);if(!O)return {provider:null,llmConfig:null};let I=E||O.defaultModel||O.models?.[0]?.name;return {provider:O,llmConfig:{model:I,providerName:O.name||O.id,maxInputTokens:O.contextWindow||128e3}}},l=yo(500),c=new Gr({workspacePath:a,source:"server",agentName:"Neox Server"}),u=new Qo(t.tts??{enabled:false});t.tts?.enabled&&(u.setSummarizeFn(async(v,E,O)=>{let I=g;if(!I)return v.substring(0,E);let A=$t.createAdapter(I.protocol,I),L=O||"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:L,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||v.substring(0,E)}),await u.init());let d=await As(a,s),p=wr({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 Pr;w.setWorkspace(a);let C=null,S=null,T=null,_=null,M=t.runMode||"single";try{C=new kn({...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{S=new Rn({...y,actionLog:c});}catch(v){m.error("SERVER","Failed to init AssistantRuntime",{error:v});}try{let v=new It(void 0,"cooperate");T=new ms({...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(O,I,A)=>{let L=g;if(!L)throw new Error("No provider configured for NetworkRuntime");let $=$t.createAdapter(L.protocol,L),P=[{role:"system",content:O},{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 It(void 0,"network");_=new In({llmCall:v,executionCapability:{orchestrator:new Et({hostService:new Rt({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 O=new AbortController;x.set(v,O);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}`);});}},L=N=>{e.publish({sessionId:v,type:"error",data:{type:"error",message:N.message},timestamp:Date.now()});},$={onRuntimeEvent:(N,D)=>I(N,D),onError:L},P={onRuntimeEvent:N=>I(N),onError:L};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"&&S)S.removeAllListeners("worker_event"),S.removeAllListeners("worker_result"),S.on("worker_event",G=>{if(G?.event){let z={...G.event,sourceLabel:G.agentId,workerRole:G.role,workerTask:G.taskSummary};I(z,G.tracker);}}),S.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 S.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(),S&&S.abort(),T&&T.abort?.();},replyPermission(v,E,O){let I=R.get(v);I&&(I.resolve(E),R.delete(v));},getActiveSessions(){return [...F]},setRunMode(v){Yo.isValidMode(v)&&(M=v,m.info("SERVER",`Run mode changed to: ${M}`));},getRunMode(){return M},setSandboxMode(v,E){fp(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,O){l.add({role:E,content:O});},getToolList(){return {count:d.length,names:d.map(v=>v.name)}},async reloadTools(v){let E=await As(v,s);d.length=0,d.push(...E),m.info("SERVER",`Reloaded ${d.length} tools for ${v}`);},async setWorkspace(v){let E=await As(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:O}=await import('child_process');try{v=O("git rev-parse --abbrev-ref HEAD",{cwd:a,encoding:"utf-8",timeout:5e3}).trim();}catch{}try{E=O("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[O,I]of x)I.abort();C&&C.abort(),S&&S.abort(),T&&T.abort?.();let E=F.size>0;return F.clear(),x.clear(),{interrupted:E}},async hostSendCommand(v,E){let O=`cmd-${Date.now()}`,I={prompt:v};return j.chat(O,I).catch(A=>{m.error("SERVER",`hostSendCommand failed: ${A.message}`);}),{queued:true,sessionId:O}},setTTSEnabled(v){let E=u.isEnabled();u.updateConfig({enabled:v,provider:"edge"}),v&&!E&&(u.summarizeFn||u.setSummarizeFn(async(O,I,A)=>{let L=g;if(!L)return O.substring(0,I);let $=$t.createAdapter(L.protocol,L),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:O}],{model:P,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||O.substring(0,I)}),u.init().catch(O=>{m.error("SERVER",`TTS init failed: ${O.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(O=>{m.error("SERVER",`TTS init failed: ${O.message}`);});}};return j}async function BS(){let{port:a,workDir:e,daemon:t}=FS(),s=Le(),n=s.remote??{};m.info("SERVER",`Starting Neox Server on port ${a}, workDir: ${e}`);let r=new xo,i=new $s,o=await jS(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}=vm(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");$S({pid:process.pid,port:a,workDir:e,startedAt:Date.now(),daemon:t});let h=()=>{m.info("SERVER","Shutting down..."),ht.stopWatch(),u.stopAll().catch(()=>{}),lg(),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});});}BS().catch(a=>{m.error("SERVER","Failed to start server",{error:a}),lg(),process.exit(1);});W();var WS=4399,zS=3e3,Kc=15e3,qS=te.join(Dn.homedir(),".neox");te.join(qS,"server.log");async function HS(a){return new Promise(e=>{let t=Lu.createServer();t.once("error",()=>e(false)),t.once("listening",()=>{t.close(()=>e(true));}),t.listen(a,"127.0.0.1");})}async function JS(a=WS){for(let e=a;e<a+100;e++)if(await HS(e))return e;throw new Error("No free port found")}async function KS(a){try{let e=new AbortController,t=setTimeout(()=>e.abort(),zS),s=await fetch(`http://127.0.0.1:${a}/health`,{signal:e.signal});return clearTimeout(t),s.ok}catch{return false}}async function VS(a){let e=cg();if(e){if(process.stderr.write(`[BOOT] ensureServer: found pid file, checking health on port ${e.port}...
|
|
3412
|
+
]`}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>=TS)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}`,xS),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 Xo=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(){}},Qo=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 Xo:this.provider=new Xo,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 Hc=te.join(Dn.homedir(),".neox"),Ur=te.join(Hc,"server.pid");function $S(a){Me.existsSync(Hc)||Me.mkdirSync(Hc,{recursive:true}),Me.writeFileSync(Ur,JSON.stringify(a,null,2));}function lg(){try{Me.existsSync(Ur)&&Me.unlinkSync(Ur);}catch{}}function cg(){try{return Me.existsSync(Ur)?JSON.parse(Me.readFileSync(Ur,"utf-8")):null}catch{return null}}function FS(){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 jS(a,e){let t=Le(),s=Ts(),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=yo(500),c=new Gr({workspacePath:a,source:"server",agentName:"Neox Server"}),u=new Qo(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=$t.createAdapter(I.protocol,I),L=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:L,maxTokens:300,temperature:.3})).choices?.[0]?.message?.content||v.substring(0,E)}),await u.init());let d=await As(a,s),p=wr({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 Pr;w.setWorkspace(a);let C=null,S=null,T=null,_=null,M=t.runMode||"single";try{C=new kn({...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{S=new Rn({...y,actionLog:c});}catch(v){m.error("SERVER","Failed to init AssistantRuntime",{error:v});}try{let v=new It(void 0,"cooperate");T=new ms({...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 L=g;if(!L)throw new Error("No provider configured for NetworkRuntime");let $=$t.createAdapter(L.protocol,L),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 It(void 0,"network");_=new In({llmCall:v,executionCapability:{orchestrator:new Et({hostService:new Rt({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,O)=>{if(m.info("SERVER",`\u{1F4E1} publishRawEvent: type=${N.type} sessionId=${v}`),e.publish({sessionId:v,type:N.type,data:N,tracker:O,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}`);});}},L=N=>{e.publish({sessionId:v,type:"error",data:{type:"error",message:N.message},timestamp:Date.now()});},$={onRuntimeEvent:(N,O)=>I(N,O),onError:L},D={onRuntimeEvent:N=>I(N),onError:L};try{let N=E.mode??M,O=E.attachments?{attachments:E.attachments}:void 0;if(N==="single"&&C)await C.chat({sessionId:v,prompt:E.prompt,metadata:O,providerId:E.providerId,modelName:E.modelName},$);else if(N==="assistant"&&S)S.removeAllListeners("worker_event"),S.removeAllListeners("worker_result"),S.on("worker_event",G=>{if(G?.event){let z={...G.event,sourceLabel:G.agentId,workerRole:G.role,workerTask:G.taskSummary};I(z,G.tracker);}}),S.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 S.chat({sessionId:v,prompt:E.prompt,metadata:O});else if(N==="cooperate"&&T)await T.chat({sessionId:v,prompt:E.prompt,metadata:O},D);else if(N==="network"&&_)await _.chat({prompt:E.prompt,history:[]});else if(C)await C.chat({sessionId:v,prompt:E.prompt,metadata:O,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(),S&&S.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){Yo.isValidMode(v)&&(M=v,m.info("SERVER",`Run mode changed to: ${M}`));},getRunMode(){return M},setSandboxMode(v,E){fp(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 As(v,s);d.length=0,d.push(...E),m.info("SERVER",`Reloaded ${d.length} tools for ${v}`);},async setWorkspace(v){let E=await As(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(),S&&S.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 L=g;if(!L)return P.substring(0,I);let $=$t.createAdapter(L.protocol,L),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 BS(){let{port:a,workDir:e,daemon:t}=FS(),s=Le(),n=s.remote??{};m.info("SERVER",`Starting Neox Server on port ${a}, workDir: ${e}`);let r=new xo,i=new $s,o=await jS(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}=vm(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");$S({pid:process.pid,port:a,workDir:e,startedAt:Date.now(),daemon:t});let h=()=>{m.info("SERVER","Shutting down..."),ht.stopWatch(),u.stopAll().catch(()=>{}),lg(),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});});}BS().catch(a=>{m.error("SERVER","Failed to start server",{error:a}),lg(),process.exit(1);});W();var WS=4399,zS=3e3,Kc=15e3,qS=te.join(Dn.homedir(),".neox");te.join(qS,"server.log");async function HS(a){return new Promise(e=>{let t=Lu.createServer();t.once("error",()=>e(false)),t.once("listening",()=>{t.close(()=>e(true));}),t.listen(a,"127.0.0.1");})}async function JS(a=WS){for(let e=a;e<a+100;e++)if(await HS(e))return e;throw new Error("No free port found")}async function KS(a){try{let e=new AbortController,t=setTimeout(()=>e.abort(),zS),s=await fetch(`http://127.0.0.1:${a}/health`,{signal:e.signal});return clearTimeout(t),s.ok}catch{return false}}async function VS(a){let e=cg();if(e){if(process.stderr.write(`[BOOT] ensureServer: found pid file, checking health on port ${e.port}...
|
|
3413
3413
|
`),await KS(e.port))return m.info("PROCESS_MGR",`Reusing existing server on port ${e.port}${e.daemon?" (daemon)":""}`),{port:e.port,baseUrl:`http://127.0.0.1:${e.port}`,reused:true};process.stderr.write(`[BOOT] ensureServer: stale pid file, starting new server
|
|
3414
3414
|
`),m.info("PROCESS_MGR","Stale pid file found, starting new server");}let t=await JS();process.stderr.write(`[BOOT] ensureServer: starting server on port ${t}...
|
|
3415
3415
|
`);let s=await YS(a,t);return {port:t,baseUrl:`http://127.0.0.1:${t}`,process:s,reused:false}}async function YS(a,e){let t=te.resolve(te.dirname(fileURLToPath(import.meta.url)),".."),s=te.join(t,"server","main.js");process.stderr.write(`[BOOT] startServer: entry=${s}
|